babylon.viewer.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010
  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. var vertexSource;
  301. var fragmentSource;
  302. if (baseName.vertexElement) {
  303. vertexSource = document.getElementById(baseName.vertexElement);
  304. if (!vertexSource) {
  305. vertexSource = baseName.vertexElement;
  306. }
  307. }
  308. else {
  309. vertexSource = baseName.vertex || baseName;
  310. }
  311. if (baseName.fragmentElement) {
  312. fragmentSource = document.getElementById(baseName.fragmentElement);
  313. if (!fragmentSource) {
  314. fragmentSource = baseName.fragmentElement;
  315. }
  316. }
  317. else {
  318. fragmentSource = baseName.fragment || baseName;
  319. }
  320. var finalVertexCode;
  321. this._loadVertexShaderAsync(vertexSource)
  322. .then(function (vertexCode) {
  323. return _this._processIncludesAsync(vertexCode);
  324. })
  325. .then(function (vertexCodeWithIncludes) {
  326. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  327. return _this._loadFragmentShaderAsync(fragmentSource);
  328. })
  329. .then(function (fragmentCode) {
  330. return _this._processIncludesAsync(fragmentCode);
  331. })
  332. .then(function (fragmentCodeWithIncludes) {
  333. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  334. if (baseName) {
  335. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  336. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  337. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  338. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  339. }
  340. else {
  341. _this._vertexSourceCode = finalVertexCode;
  342. _this._fragmentSourceCode = migratedFragmentCode;
  343. }
  344. _this._prepareEffect();
  345. });
  346. }
  347. Object.defineProperty(Effect.prototype, "key", {
  348. /**
  349. * Unique key for this effect
  350. */
  351. get: function () {
  352. return this._key;
  353. },
  354. enumerable: true,
  355. configurable: true
  356. });
  357. /**
  358. * If the effect has been compiled and prepared.
  359. * @returns if the effect is compiled and prepared.
  360. */
  361. Effect.prototype.isReady = function () {
  362. return this._isReady;
  363. };
  364. /**
  365. * The engine the effect was initialized with.
  366. * @returns the engine.
  367. */
  368. Effect.prototype.getEngine = function () {
  369. return this._engine;
  370. };
  371. /**
  372. * The compiled webGL program for the effect
  373. * @returns the webGL program.
  374. */
  375. Effect.prototype.getProgram = function () {
  376. return this._program;
  377. };
  378. /**
  379. * The set of names of attribute variables for the shader.
  380. * @returns An array of attribute names.
  381. */
  382. Effect.prototype.getAttributesNames = function () {
  383. return this._attributesNames;
  384. };
  385. /**
  386. * Returns the attribute at the given index.
  387. * @param index The index of the attribute.
  388. * @returns The location of the attribute.
  389. */
  390. Effect.prototype.getAttributeLocation = function (index) {
  391. return this._attributes[index];
  392. };
  393. /**
  394. * Returns the attribute based on the name of the variable.
  395. * @param name of the attribute to look up.
  396. * @returns the attribute location.
  397. */
  398. Effect.prototype.getAttributeLocationByName = function (name) {
  399. var index = this._attributesNames.indexOf(name);
  400. return this._attributes[index];
  401. };
  402. /**
  403. * The number of attributes.
  404. * @returns the numnber of attributes.
  405. */
  406. Effect.prototype.getAttributesCount = function () {
  407. return this._attributes.length;
  408. };
  409. /**
  410. * Gets the index of a uniform variable.
  411. * @param uniformName of the uniform to look up.
  412. * @returns the index.
  413. */
  414. Effect.prototype.getUniformIndex = function (uniformName) {
  415. return this._uniformsNames.indexOf(uniformName);
  416. };
  417. /**
  418. * Returns the attribute based on the name of the variable.
  419. * @param uniformName of the uniform to look up.
  420. * @returns the location of the uniform.
  421. */
  422. Effect.prototype.getUniform = function (uniformName) {
  423. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  424. };
  425. /**
  426. * Returns an array of sampler variable names
  427. * @returns The array of sampler variable neames.
  428. */
  429. Effect.prototype.getSamplers = function () {
  430. return this._samplers;
  431. };
  432. /**
  433. * The error from the last compilation.
  434. * @returns the error string.
  435. */
  436. Effect.prototype.getCompilationError = function () {
  437. return this._compilationError;
  438. };
  439. /**
  440. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  441. * @param func The callback to be used.
  442. */
  443. Effect.prototype.executeWhenCompiled = function (func) {
  444. if (this.isReady()) {
  445. func(this);
  446. return;
  447. }
  448. this.onCompileObservable.add(function (effect) {
  449. func(effect);
  450. });
  451. };
  452. /** @ignore */
  453. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  454. if (BABYLON.Tools.IsWindowObjectExist()) {
  455. // DOM element ?
  456. if (vertex instanceof HTMLElement) {
  457. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  458. return Promise.resolve(vertexCode);
  459. }
  460. }
  461. // Base64 encoded ?
  462. if (vertex.substr(0, 7) === "base64:") {
  463. var vertexBinary = window.atob(vertex.substr(7));
  464. return Promise.resolve(vertexBinary);
  465. }
  466. // Is in local store ?
  467. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  468. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  469. }
  470. var vertexShaderUrl;
  471. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  472. vertexShaderUrl = vertex;
  473. }
  474. else {
  475. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  476. }
  477. // Vertex shader
  478. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  479. };
  480. /** @ignore */
  481. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  482. if (BABYLON.Tools.IsWindowObjectExist()) {
  483. // DOM element ?
  484. if (fragment instanceof HTMLElement) {
  485. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  486. return Promise.resolve(fragmentCode);
  487. }
  488. }
  489. // Base64 encoded ?
  490. if (fragment.substr(0, 7) === "base64:") {
  491. var fragmentBinary = window.atob(fragment.substr(7));
  492. return Promise.resolve(fragmentBinary);
  493. }
  494. // Is in local store ?
  495. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  496. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  497. }
  498. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  499. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  500. }
  501. var fragmentShaderUrl;
  502. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  503. fragmentShaderUrl = fragment;
  504. }
  505. else {
  506. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  507. }
  508. // Fragment shader
  509. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  510. };
  511. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  512. // Rebuild shaders source code
  513. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  514. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  515. vertexCode = prefix + vertexCode;
  516. fragmentCode = prefix + fragmentCode;
  517. // Number lines of shaders source code
  518. var i = 2;
  519. var regex = /\n/gm;
  520. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  521. i = 2;
  522. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  523. // Dump shaders name and formatted source code
  524. if (this.name.vertexElement) {
  525. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  526. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  527. }
  528. else if (this.name.vertex) {
  529. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  530. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  531. }
  532. else {
  533. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  534. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  535. }
  536. };
  537. ;
  538. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  539. var preparedSourceCode = this._processPrecision(sourceCode);
  540. if (this._engine.webGLVersion == 1) {
  541. return preparedSourceCode;
  542. }
  543. // Already converted
  544. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  545. return preparedSourceCode.replace("#version 300 es", "");
  546. }
  547. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  548. // Remove extensions
  549. // #extension GL_OES_standard_derivatives : enable
  550. // #extension GL_EXT_shader_texture_lod : enable
  551. // #extension GL_EXT_frag_depth : enable
  552. // #extension GL_EXT_draw_buffers : require
  553. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  554. var result = preparedSourceCode.replace(regex, "");
  555. // Migrate to GLSL v300
  556. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  557. result = result.replace(/attribute[ \t]/g, "in ");
  558. result = result.replace(/[ \t]attribute/g, " in");
  559. if (isFragment) {
  560. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  561. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  562. result = result.replace(/texture2D\s*\(/g, "texture(");
  563. result = result.replace(/textureCube\s*\(/g, "texture(");
  564. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  565. result = result.replace(/gl_FragColor/g, "glFragColor");
  566. result = result.replace(/gl_FragData/g, "glFragData");
  567. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  568. }
  569. return result;
  570. };
  571. Effect.prototype._processIncludesAsync = function (sourceCode) {
  572. var _this = this;
  573. return new Promise(function (resolve, reject) {
  574. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  575. var match = regex.exec(sourceCode);
  576. var returnValue = sourceCode;
  577. while (match != null) {
  578. var includeFile = match[1];
  579. // Uniform declaration
  580. if (includeFile.indexOf("__decl__") !== -1) {
  581. includeFile = includeFile.replace(/__decl__/, "");
  582. if (_this._engine.supportsUniformBuffers) {
  583. includeFile = includeFile.replace(/Vertex/, "Ubo");
  584. includeFile = includeFile.replace(/Fragment/, "Ubo");
  585. }
  586. includeFile = includeFile + "Declaration";
  587. }
  588. if (Effect.IncludesShadersStore[includeFile]) {
  589. // Substitution
  590. var includeContent = Effect.IncludesShadersStore[includeFile];
  591. if (match[2]) {
  592. var splits = match[3].split(",");
  593. for (var index = 0; index < splits.length; index += 2) {
  594. var source = new RegExp(splits[index], "g");
  595. var dest = splits[index + 1];
  596. includeContent = includeContent.replace(source, dest);
  597. }
  598. }
  599. if (match[4]) {
  600. var indexString = match[5];
  601. if (indexString.indexOf("..") !== -1) {
  602. var indexSplits = indexString.split("..");
  603. var minIndex = parseInt(indexSplits[0]);
  604. var maxIndex = parseInt(indexSplits[1]);
  605. var sourceIncludeContent = includeContent.slice(0);
  606. includeContent = "";
  607. if (isNaN(maxIndex)) {
  608. maxIndex = _this._indexParameters[indexSplits[1]];
  609. }
  610. for (var i = minIndex; i < maxIndex; i++) {
  611. if (!_this._engine.supportsUniformBuffers) {
  612. // Ubo replacement
  613. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  614. return p1 + "{X}";
  615. });
  616. }
  617. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  618. }
  619. }
  620. else {
  621. if (!_this._engine.supportsUniformBuffers) {
  622. // Ubo replacement
  623. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  624. return p1 + "{X}";
  625. });
  626. }
  627. includeContent = includeContent.replace(/\{X\}/g, indexString);
  628. }
  629. }
  630. // Replace
  631. returnValue = returnValue.replace(match[0], includeContent);
  632. }
  633. else {
  634. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  635. _this._engine._loadFileAsync(includeShaderUrl)
  636. .then(function (fileContent) {
  637. Effect.IncludesShadersStore[includeFile] = fileContent;
  638. return _this._processIncludesAsync(returnValue);
  639. })
  640. .then(function (returnValue) {
  641. resolve(returnValue);
  642. });
  643. return;
  644. }
  645. match = regex.exec(sourceCode);
  646. }
  647. resolve(returnValue);
  648. });
  649. };
  650. Effect.prototype._processPrecision = function (source) {
  651. if (source.indexOf("precision highp float") === -1) {
  652. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  653. source = "precision mediump float;\n" + source;
  654. }
  655. else {
  656. source = "precision highp float;\n" + source;
  657. }
  658. }
  659. else {
  660. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  661. source = source.replace("precision highp float", "precision mediump float");
  662. }
  663. }
  664. return source;
  665. };
  666. /**
  667. * Recompiles the webGL program
  668. * @param vertexSourceCode The source code for the vertex shader.
  669. * @param fragmentSourceCode The source code for the fragment shader.
  670. * @param onCompiled Callback called when completed.
  671. * @param onError Callback called on error.
  672. */
  673. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  674. var _this = this;
  675. this._isReady = false;
  676. this._vertexSourceCodeOverride = vertexSourceCode;
  677. this._fragmentSourceCodeOverride = fragmentSourceCode;
  678. this.onError = function (effect, error) {
  679. if (onError) {
  680. onError(error);
  681. }
  682. };
  683. this.onCompiled = function () {
  684. var scenes = _this.getEngine().scenes;
  685. for (var i = 0; i < scenes.length; i++) {
  686. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  687. }
  688. if (onCompiled) {
  689. onCompiled(_this._program);
  690. }
  691. };
  692. this._fallbacks = null;
  693. this._prepareEffect();
  694. };
  695. /**
  696. * Gets the uniform locations of the the specified variable names
  697. * @param names THe names of the variables to lookup.
  698. * @returns Array of locations in the same order as variable names.
  699. */
  700. Effect.prototype.getSpecificUniformLocations = function (names) {
  701. var engine = this._engine;
  702. return engine.getUniforms(this._program, names);
  703. };
  704. /**
  705. * Prepares the effect
  706. */
  707. Effect.prototype._prepareEffect = function () {
  708. var attributesNames = this._attributesNames;
  709. var defines = this.defines;
  710. var fallbacks = this._fallbacks;
  711. this._valueCache = {};
  712. var previousProgram = this._program;
  713. try {
  714. var engine = this._engine;
  715. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  716. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  717. }
  718. else {
  719. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  720. }
  721. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  722. if (engine.supportsUniformBuffers) {
  723. for (var name in this._uniformBuffersNames) {
  724. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  725. }
  726. }
  727. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  728. this._attributes = engine.getAttributes(this._program, attributesNames);
  729. var index;
  730. for (index = 0; index < this._samplers.length; index++) {
  731. var sampler = this.getUniform(this._samplers[index]);
  732. if (sampler == null) {
  733. this._samplers.splice(index, 1);
  734. index--;
  735. }
  736. }
  737. engine.bindSamplers(this);
  738. this._compilationError = "";
  739. this._isReady = true;
  740. if (this.onCompiled) {
  741. this.onCompiled(this);
  742. }
  743. this.onCompileObservable.notifyObservers(this);
  744. this.onCompileObservable.clear();
  745. // Unbind mesh reference in fallbacks
  746. if (this._fallbacks) {
  747. this._fallbacks.unBindMesh();
  748. }
  749. if (previousProgram) {
  750. this.getEngine()._deleteProgram(previousProgram);
  751. }
  752. }
  753. catch (e) {
  754. this._compilationError = e.message;
  755. // Let's go through fallbacks then
  756. BABYLON.Tools.Error("Unable to compile effect:");
  757. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  758. return " " + uniform;
  759. }));
  760. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  761. return " " + attribute;
  762. }));
  763. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  764. BABYLON.Tools.Error("Error: " + this._compilationError);
  765. if (previousProgram) {
  766. this._program = previousProgram;
  767. this._isReady = true;
  768. if (this.onError) {
  769. this.onError(this, this._compilationError);
  770. }
  771. this.onErrorObservable.notifyObservers(this);
  772. }
  773. if (fallbacks && fallbacks.isMoreFallbacks) {
  774. BABYLON.Tools.Error("Trying next fallback.");
  775. this.defines = fallbacks.reduce(this.defines, this);
  776. this._prepareEffect();
  777. }
  778. else {
  779. if (this.onError) {
  780. this.onError(this, this._compilationError);
  781. }
  782. this.onErrorObservable.notifyObservers(this);
  783. this.onErrorObservable.clear();
  784. // Unbind mesh reference in fallbacks
  785. if (this._fallbacks) {
  786. this._fallbacks.unBindMesh();
  787. }
  788. }
  789. }
  790. };
  791. Object.defineProperty(Effect.prototype, "isSupported", {
  792. /**
  793. * Checks if the effect is supported. (Must be called after compilation)
  794. */
  795. get: function () {
  796. return this._compilationError === "";
  797. },
  798. enumerable: true,
  799. configurable: true
  800. });
  801. /**
  802. * Binds a texture to the engine to be used as output of the shader.
  803. * @param channel Name of the output variable.
  804. * @param texture Texture to bind.
  805. */
  806. Effect.prototype._bindTexture = function (channel, texture) {
  807. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  808. };
  809. /**
  810. * Sets a texture on the engine to be used in the shader.
  811. * @param channel Name of the sampler variable.
  812. * @param texture Texture to set.
  813. */
  814. Effect.prototype.setTexture = function (channel, texture) {
  815. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  816. };
  817. /**
  818. * Sets an array of textures on the engine to be used in the shader.
  819. * @param channel Name of the variable.
  820. * @param textures Textures to set.
  821. */
  822. Effect.prototype.setTextureArray = function (channel, textures) {
  823. if (this._samplers.indexOf(channel + "Ex") === -1) {
  824. var initialPos = this._samplers.indexOf(channel);
  825. for (var index = 1; index < textures.length; index++) {
  826. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  827. }
  828. }
  829. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  830. };
  831. /**
  832. * 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)
  833. * @param channel Name of the sampler variable.
  834. * @param postProcess Post process to get the input texture from.
  835. */
  836. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  837. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  838. };
  839. /** @ignore */
  840. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  841. var cache = this._valueCache[uniformName];
  842. var flag = matrix.updateFlag;
  843. if (cache !== undefined && cache === flag) {
  844. return false;
  845. }
  846. this._valueCache[uniformName] = flag;
  847. return true;
  848. };
  849. /** @ignore */
  850. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  851. var cache = this._valueCache[uniformName];
  852. if (!cache) {
  853. cache = [x, y];
  854. this._valueCache[uniformName] = cache;
  855. return true;
  856. }
  857. var changed = false;
  858. if (cache[0] !== x) {
  859. cache[0] = x;
  860. changed = true;
  861. }
  862. if (cache[1] !== y) {
  863. cache[1] = y;
  864. changed = true;
  865. }
  866. return changed;
  867. };
  868. /** @ignore */
  869. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  870. var cache = this._valueCache[uniformName];
  871. if (!cache) {
  872. cache = [x, y, z];
  873. this._valueCache[uniformName] = cache;
  874. return true;
  875. }
  876. var changed = false;
  877. if (cache[0] !== x) {
  878. cache[0] = x;
  879. changed = true;
  880. }
  881. if (cache[1] !== y) {
  882. cache[1] = y;
  883. changed = true;
  884. }
  885. if (cache[2] !== z) {
  886. cache[2] = z;
  887. changed = true;
  888. }
  889. return changed;
  890. };
  891. /** @ignore */
  892. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  893. var cache = this._valueCache[uniformName];
  894. if (!cache) {
  895. cache = [x, y, z, w];
  896. this._valueCache[uniformName] = cache;
  897. return true;
  898. }
  899. var changed = false;
  900. if (cache[0] !== x) {
  901. cache[0] = x;
  902. changed = true;
  903. }
  904. if (cache[1] !== y) {
  905. cache[1] = y;
  906. changed = true;
  907. }
  908. if (cache[2] !== z) {
  909. cache[2] = z;
  910. changed = true;
  911. }
  912. if (cache[3] !== w) {
  913. cache[3] = w;
  914. changed = true;
  915. }
  916. return changed;
  917. };
  918. /**
  919. * Binds a buffer to a uniform.
  920. * @param buffer Buffer to bind.
  921. * @param name Name of the uniform variable to bind to.
  922. */
  923. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  924. var bufferName = this._uniformBuffersNames[name];
  925. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  926. return;
  927. }
  928. Effect._baseCache[bufferName] = buffer;
  929. this._engine.bindUniformBufferBase(buffer, bufferName);
  930. };
  931. /**
  932. * Binds block to a uniform.
  933. * @param blockName Name of the block to bind.
  934. * @param index Index to bind.
  935. */
  936. Effect.prototype.bindUniformBlock = function (blockName, index) {
  937. this._engine.bindUniformBlock(this._program, blockName, index);
  938. };
  939. /**
  940. * Sets an interger value on a uniform variable.
  941. * @param uniformName Name of the variable.
  942. * @param value Value to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setInt = function (uniformName, value) {
  946. var cache = this._valueCache[uniformName];
  947. if (cache !== undefined && cache === value)
  948. return this;
  949. this._valueCache[uniformName] = value;
  950. this._engine.setInt(this.getUniform(uniformName), value);
  951. return this;
  952. };
  953. /**
  954. * Sets an int array on a uniform variable.
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setIntArray = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setIntArray(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * 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)
  966. * @param uniformName Name of the variable.
  967. * @param array array to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setIntArray2 = function (uniformName, array) {
  971. this._valueCache[uniformName] = null;
  972. this._engine.setIntArray2(this.getUniform(uniformName), array);
  973. return this;
  974. };
  975. /**
  976. * 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)
  977. * @param uniformName Name of the variable.
  978. * @param array array to be set.
  979. * @returns this effect.
  980. */
  981. Effect.prototype.setIntArray3 = function (uniformName, array) {
  982. this._valueCache[uniformName] = null;
  983. this._engine.setIntArray3(this.getUniform(uniformName), array);
  984. return this;
  985. };
  986. /**
  987. * 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)
  988. * @param uniformName Name of the variable.
  989. * @param array array to be set.
  990. * @returns this effect.
  991. */
  992. Effect.prototype.setIntArray4 = function (uniformName, array) {
  993. this._valueCache[uniformName] = null;
  994. this._engine.setIntArray4(this.getUniform(uniformName), array);
  995. return this;
  996. };
  997. /**
  998. * Sets an float array on a uniform variable.
  999. * @param uniformName Name of the variable.
  1000. * @param array array to be set.
  1001. * @returns this effect.
  1002. */
  1003. Effect.prototype.setFloatArray = function (uniformName, array) {
  1004. this._valueCache[uniformName] = null;
  1005. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1006. return this;
  1007. };
  1008. /**
  1009. * 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)
  1010. * @param uniformName Name of the variable.
  1011. * @param array array to be set.
  1012. * @returns this effect.
  1013. */
  1014. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1015. this._valueCache[uniformName] = null;
  1016. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1017. return this;
  1018. };
  1019. /**
  1020. * 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)
  1021. * @param uniformName Name of the variable.
  1022. * @param array array to be set.
  1023. * @returns this effect.
  1024. */
  1025. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1026. this._valueCache[uniformName] = null;
  1027. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1028. return this;
  1029. };
  1030. /**
  1031. * 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)
  1032. * @param uniformName Name of the variable.
  1033. * @param array array to be set.
  1034. * @returns this effect.
  1035. */
  1036. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1039. return this;
  1040. };
  1041. /**
  1042. * Sets an array on a uniform variable.
  1043. * @param uniformName Name of the variable.
  1044. * @param array array to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setArray = function (uniformName, array) {
  1048. this._valueCache[uniformName] = null;
  1049. this._engine.setArray(this.getUniform(uniformName), array);
  1050. return this;
  1051. };
  1052. /**
  1053. * 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)
  1054. * @param uniformName Name of the variable.
  1055. * @param array array to be set.
  1056. * @returns this effect.
  1057. */
  1058. Effect.prototype.setArray2 = function (uniformName, array) {
  1059. this._valueCache[uniformName] = null;
  1060. this._engine.setArray2(this.getUniform(uniformName), array);
  1061. return this;
  1062. };
  1063. /**
  1064. * 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)
  1065. * @param uniformName Name of the variable.
  1066. * @param array array to be set.
  1067. * @returns this effect.
  1068. */
  1069. Effect.prototype.setArray3 = function (uniformName, array) {
  1070. this._valueCache[uniformName] = null;
  1071. this._engine.setArray3(this.getUniform(uniformName), array);
  1072. return this;
  1073. };
  1074. /**
  1075. * 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)
  1076. * @param uniformName Name of the variable.
  1077. * @param array array to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setArray4 = function (uniformName, array) {
  1081. this._valueCache[uniformName] = null;
  1082. this._engine.setArray4(this.getUniform(uniformName), array);
  1083. return this;
  1084. };
  1085. /**
  1086. * Sets matrices on a uniform variable.
  1087. * @param uniformName Name of the variable.
  1088. * @param matrices matrices to be set.
  1089. * @returns this effect.
  1090. */
  1091. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1092. if (!matrices) {
  1093. return this;
  1094. }
  1095. this._valueCache[uniformName] = null;
  1096. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1097. return this;
  1098. };
  1099. /**
  1100. * Sets matrix on a uniform variable.
  1101. * @param uniformName Name of the variable.
  1102. * @param matrix matrix to be set.
  1103. * @returns this effect.
  1104. */
  1105. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1106. if (this._cacheMatrix(uniformName, matrix)) {
  1107. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1108. }
  1109. return this;
  1110. };
  1111. /**
  1112. * 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)
  1113. * @param uniformName Name of the variable.
  1114. * @param matrix matrix to be set.
  1115. * @returns this effect.
  1116. */
  1117. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1118. this._valueCache[uniformName] = null;
  1119. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1120. return this;
  1121. };
  1122. /**
  1123. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1124. * @param uniformName Name of the variable.
  1125. * @param matrix matrix to be set.
  1126. * @returns this effect.
  1127. */
  1128. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1129. this._valueCache[uniformName] = null;
  1130. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1131. return this;
  1132. };
  1133. /**
  1134. * Sets a float on a uniform variable.
  1135. * @param uniformName Name of the variable.
  1136. * @param value value to be set.
  1137. * @returns this effect.
  1138. */
  1139. Effect.prototype.setFloat = function (uniformName, value) {
  1140. var cache = this._valueCache[uniformName];
  1141. if (cache !== undefined && cache === value)
  1142. return this;
  1143. this._valueCache[uniformName] = value;
  1144. this._engine.setFloat(this.getUniform(uniformName), value);
  1145. return this;
  1146. };
  1147. /**
  1148. * Sets a boolean on a uniform variable.
  1149. * @param uniformName Name of the variable.
  1150. * @param bool value to be set.
  1151. * @returns this effect.
  1152. */
  1153. Effect.prototype.setBool = function (uniformName, bool) {
  1154. var cache = this._valueCache[uniformName];
  1155. if (cache !== undefined && cache === bool)
  1156. return this;
  1157. this._valueCache[uniformName] = bool;
  1158. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1159. return this;
  1160. };
  1161. /**
  1162. * Sets a Vector2 on a uniform variable.
  1163. * @param uniformName Name of the variable.
  1164. * @param vector2 vector2 to be set.
  1165. * @returns this effect.
  1166. */
  1167. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1168. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1169. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1170. }
  1171. return this;
  1172. };
  1173. /**
  1174. * Sets a float2 on a uniform variable.
  1175. * @param uniformName Name of the variable.
  1176. * @param x First float in float2.
  1177. * @param y Second float in float2.
  1178. * @returns this effect.
  1179. */
  1180. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1181. if (this._cacheFloat2(uniformName, x, y)) {
  1182. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1183. }
  1184. return this;
  1185. };
  1186. /**
  1187. * Sets a Vector3 on a uniform variable.
  1188. * @param uniformName Name of the variable.
  1189. * @param vector3 Value to be set.
  1190. * @returns this effect.
  1191. */
  1192. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1193. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1194. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1195. }
  1196. return this;
  1197. };
  1198. /**
  1199. * Sets a float3 on a uniform variable.
  1200. * @param uniformName Name of the variable.
  1201. * @param x First float in float3.
  1202. * @param y Second float in float3.
  1203. * @param z Third float in float3.
  1204. * @returns this effect.
  1205. */
  1206. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1207. if (this._cacheFloat3(uniformName, x, y, z)) {
  1208. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1209. }
  1210. return this;
  1211. };
  1212. /**
  1213. * Sets a Vector4 on a uniform variable.
  1214. * @param uniformName Name of the variable.
  1215. * @param vector4 Value to be set.
  1216. * @returns this effect.
  1217. */
  1218. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1219. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1220. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1221. }
  1222. return this;
  1223. };
  1224. /**
  1225. * Sets a float4 on a uniform variable.
  1226. * @param uniformName Name of the variable.
  1227. * @param x First float in float4.
  1228. * @param y Second float in float4.
  1229. * @param z Third float in float4.
  1230. * @param w Fourth float in float4.
  1231. * @returns this effect.
  1232. */
  1233. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1234. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1235. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1236. }
  1237. return this;
  1238. };
  1239. /**
  1240. * Sets a Color3 on a uniform variable.
  1241. * @param uniformName Name of the variable.
  1242. * @param color3 Value to be set.
  1243. * @returns this effect.
  1244. */
  1245. Effect.prototype.setColor3 = function (uniformName, color3) {
  1246. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1247. this._engine.setColor3(this.getUniform(uniformName), color3);
  1248. }
  1249. return this;
  1250. };
  1251. /**
  1252. * Sets a Color4 on a uniform variable.
  1253. * @param uniformName Name of the variable.
  1254. * @param color3 Value to be set.
  1255. * @param alpha Alpha value to be set.
  1256. * @returns this effect.
  1257. */
  1258. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1259. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1260. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1261. }
  1262. return this;
  1263. };
  1264. /**
  1265. * Sets a Color4 on a uniform variable
  1266. * @param uniformName defines the name of the variable
  1267. * @param color4 defines the value to be set
  1268. * @returns this effect.
  1269. */
  1270. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1271. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1272. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1273. }
  1274. return this;
  1275. };
  1276. /**
  1277. * Resets the cache of effects.
  1278. */
  1279. Effect.ResetCache = function () {
  1280. Effect._baseCache = {};
  1281. };
  1282. Effect._uniqueIdSeed = 0;
  1283. Effect._baseCache = {};
  1284. // Statics
  1285. /**
  1286. * Store of each shader (The can be looked up using effect.key)
  1287. */
  1288. Effect.ShadersStore = {};
  1289. /**
  1290. * Store of each included file for a shader (The can be looked up using effect.key)
  1291. */
  1292. Effect.IncludesShadersStore = {};
  1293. return Effect;
  1294. }());
  1295. BABYLON.Effect = Effect;
  1296. })(BABYLON || (BABYLON = {}));
  1297. //# sourceMappingURL=babylon.effect.js.map
  1298. //# sourceMappingURL=babylon.types.js.map
  1299. var BABYLON;
  1300. (function (BABYLON) {
  1301. var KeyboardEventTypes = /** @class */ (function () {
  1302. function KeyboardEventTypes() {
  1303. }
  1304. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1305. get: function () {
  1306. return KeyboardEventTypes._KEYDOWN;
  1307. },
  1308. enumerable: true,
  1309. configurable: true
  1310. });
  1311. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1312. get: function () {
  1313. return KeyboardEventTypes._KEYUP;
  1314. },
  1315. enumerable: true,
  1316. configurable: true
  1317. });
  1318. KeyboardEventTypes._KEYDOWN = 0x01;
  1319. KeyboardEventTypes._KEYUP = 0x02;
  1320. return KeyboardEventTypes;
  1321. }());
  1322. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1323. var KeyboardInfo = /** @class */ (function () {
  1324. function KeyboardInfo(type, event) {
  1325. this.type = type;
  1326. this.event = event;
  1327. }
  1328. return KeyboardInfo;
  1329. }());
  1330. BABYLON.KeyboardInfo = KeyboardInfo;
  1331. /**
  1332. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1333. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1334. */
  1335. var KeyboardInfoPre = /** @class */ (function (_super) {
  1336. __extends(KeyboardInfoPre, _super);
  1337. function KeyboardInfoPre(type, event) {
  1338. var _this = _super.call(this, type, event) || this;
  1339. _this.skipOnPointerObservable = false;
  1340. return _this;
  1341. }
  1342. return KeyboardInfoPre;
  1343. }(KeyboardInfo));
  1344. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1345. })(BABYLON || (BABYLON = {}));
  1346. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1347. var BABYLON;
  1348. (function (BABYLON) {
  1349. var PointerEventTypes = /** @class */ (function () {
  1350. function PointerEventTypes() {
  1351. }
  1352. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1353. get: function () {
  1354. return PointerEventTypes._POINTERDOWN;
  1355. },
  1356. enumerable: true,
  1357. configurable: true
  1358. });
  1359. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1360. get: function () {
  1361. return PointerEventTypes._POINTERUP;
  1362. },
  1363. enumerable: true,
  1364. configurable: true
  1365. });
  1366. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1367. get: function () {
  1368. return PointerEventTypes._POINTERMOVE;
  1369. },
  1370. enumerable: true,
  1371. configurable: true
  1372. });
  1373. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1374. get: function () {
  1375. return PointerEventTypes._POINTERWHEEL;
  1376. },
  1377. enumerable: true,
  1378. configurable: true
  1379. });
  1380. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1381. get: function () {
  1382. return PointerEventTypes._POINTERPICK;
  1383. },
  1384. enumerable: true,
  1385. configurable: true
  1386. });
  1387. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1388. get: function () {
  1389. return PointerEventTypes._POINTERTAP;
  1390. },
  1391. enumerable: true,
  1392. configurable: true
  1393. });
  1394. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1395. get: function () {
  1396. return PointerEventTypes._POINTERDOUBLETAP;
  1397. },
  1398. enumerable: true,
  1399. configurable: true
  1400. });
  1401. PointerEventTypes._POINTERDOWN = 0x01;
  1402. PointerEventTypes._POINTERUP = 0x02;
  1403. PointerEventTypes._POINTERMOVE = 0x04;
  1404. PointerEventTypes._POINTERWHEEL = 0x08;
  1405. PointerEventTypes._POINTERPICK = 0x10;
  1406. PointerEventTypes._POINTERTAP = 0x20;
  1407. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1408. return PointerEventTypes;
  1409. }());
  1410. BABYLON.PointerEventTypes = PointerEventTypes;
  1411. var PointerInfoBase = /** @class */ (function () {
  1412. function PointerInfoBase(type, event) {
  1413. this.type = type;
  1414. this.event = event;
  1415. }
  1416. return PointerInfoBase;
  1417. }());
  1418. BABYLON.PointerInfoBase = PointerInfoBase;
  1419. /**
  1420. * This class is used to store pointer related info for the onPrePointerObservable event.
  1421. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1422. */
  1423. var PointerInfoPre = /** @class */ (function (_super) {
  1424. __extends(PointerInfoPre, _super);
  1425. function PointerInfoPre(type, event, localX, localY) {
  1426. var _this = _super.call(this, type, event) || this;
  1427. _this.skipOnPointerObservable = false;
  1428. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1429. return _this;
  1430. }
  1431. return PointerInfoPre;
  1432. }(PointerInfoBase));
  1433. BABYLON.PointerInfoPre = PointerInfoPre;
  1434. /**
  1435. * This type contains all the data related to a pointer event in Babylon.js.
  1436. * 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.
  1437. */
  1438. var PointerInfo = /** @class */ (function (_super) {
  1439. __extends(PointerInfo, _super);
  1440. function PointerInfo(type, event, pickInfo) {
  1441. var _this = _super.call(this, type, event) || this;
  1442. _this.pickInfo = pickInfo;
  1443. return _this;
  1444. }
  1445. return PointerInfo;
  1446. }(PointerInfoBase));
  1447. BABYLON.PointerInfo = PointerInfo;
  1448. })(BABYLON || (BABYLON = {}));
  1449. //# sourceMappingURL=babylon.pointerEvents.js.map
  1450. var BABYLON;
  1451. (function (BABYLON) {
  1452. BABYLON.ToGammaSpace = 1 / 2.2;
  1453. BABYLON.ToLinearSpace = 2.2;
  1454. BABYLON.Epsilon = 0.001;
  1455. /**
  1456. * Class used to hold a RBG color
  1457. */
  1458. var Color3 = /** @class */ (function () {
  1459. /**
  1460. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1461. * @param r defines the red component (between 0 and 1, default is 0)
  1462. * @param g defines the green component (between 0 and 1, default is 0)
  1463. * @param b defines the blue component (between 0 and 1, default is 0)
  1464. */
  1465. function Color3(
  1466. /**
  1467. * Defines the red component (between 0 and 1, default is 0)
  1468. */
  1469. r,
  1470. /**
  1471. * Defines the green component (between 0 and 1, default is 0)
  1472. */
  1473. g,
  1474. /**
  1475. * Defines the blue component (between 0 and 1, default is 0)
  1476. */
  1477. b) {
  1478. if (r === void 0) { r = 0; }
  1479. if (g === void 0) { g = 0; }
  1480. if (b === void 0) { b = 0; }
  1481. this.r = r;
  1482. this.g = g;
  1483. this.b = b;
  1484. }
  1485. /**
  1486. * Creates a string with the Color3 current values
  1487. * @returns the string representation of the Color3 object
  1488. */
  1489. Color3.prototype.toString = function () {
  1490. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1491. };
  1492. /**
  1493. * Returns the string "Color3"
  1494. * @returns "Color3"
  1495. */
  1496. Color3.prototype.getClassName = function () {
  1497. return "Color3";
  1498. };
  1499. /**
  1500. * Compute the Color3 hash code
  1501. * @returns an unique number that can be used to hash Color3 objects
  1502. */
  1503. Color3.prototype.getHashCode = function () {
  1504. var hash = this.r || 0;
  1505. hash = (hash * 397) ^ (this.g || 0);
  1506. hash = (hash * 397) ^ (this.b || 0);
  1507. return hash;
  1508. };
  1509. // Operators
  1510. /**
  1511. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1512. * @param array defines the array where to store the r,g,b components
  1513. * @param index defines an optional index in the target array to define where to start storing values
  1514. * @returns the current Color3 object
  1515. */
  1516. Color3.prototype.toArray = function (array, index) {
  1517. if (index === undefined) {
  1518. index = 0;
  1519. }
  1520. array[index] = this.r;
  1521. array[index + 1] = this.g;
  1522. array[index + 2] = this.b;
  1523. return this;
  1524. };
  1525. /**
  1526. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1527. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1528. * @returns a new {BABYLON.Color4} object
  1529. */
  1530. Color3.prototype.toColor4 = function (alpha) {
  1531. if (alpha === void 0) { alpha = 1; }
  1532. return new Color4(this.r, this.g, this.b, alpha);
  1533. };
  1534. /**
  1535. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1536. * @returns the new array
  1537. */
  1538. Color3.prototype.asArray = function () {
  1539. var result = new Array();
  1540. this.toArray(result, 0);
  1541. return result;
  1542. };
  1543. /**
  1544. * Returns the luminance value
  1545. * @returns a float value
  1546. */
  1547. Color3.prototype.toLuminance = function () {
  1548. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1549. };
  1550. /**
  1551. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1552. * @param otherColor defines the second operand
  1553. * @returns the new Color3 object
  1554. */
  1555. Color3.prototype.multiply = function (otherColor) {
  1556. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1557. };
  1558. /**
  1559. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1560. * @param otherColor defines the second operand
  1561. * @param result defines the Color3 object where to store the result
  1562. * @returns the current Color3
  1563. */
  1564. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1565. result.r = this.r * otherColor.r;
  1566. result.g = this.g * otherColor.g;
  1567. result.b = this.b * otherColor.b;
  1568. return this;
  1569. };
  1570. /**
  1571. * Determines equality between Color3 objects
  1572. * @param otherColor defines the second operand
  1573. * @returns true if the rgb values are equal to the passed ones
  1574. */
  1575. Color3.prototype.equals = function (otherColor) {
  1576. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1577. };
  1578. /**
  1579. * Determines equality between the current Color3 object and a set of r,b,g values
  1580. * @param r defines the red component to check
  1581. * @param g defines the green component to check
  1582. * @param b defines the blue component to check
  1583. * @returns true if the rgb values are equal to the passed ones
  1584. */
  1585. Color3.prototype.equalsFloats = function (r, g, b) {
  1586. return this.r === r && this.g === g && this.b === b;
  1587. };
  1588. /**
  1589. * Multiplies in place each rgb value by scale
  1590. * @param scale defines the scaling factor
  1591. * @returns the updated Color3.
  1592. */
  1593. Color3.prototype.scale = function (scale) {
  1594. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1595. };
  1596. /**
  1597. * Multiplies the rgb values by scale and stores the result into "result"
  1598. * @param scale defines the scaling factor
  1599. * @param result defines the Color3 object where to store the result
  1600. * @returns the unmodified current Color3.
  1601. */
  1602. Color3.prototype.scaleToRef = function (scale, result) {
  1603. result.r = this.r * scale;
  1604. result.g = this.g * scale;
  1605. result.b = this.b * scale;
  1606. return this;
  1607. };
  1608. /**
  1609. * Clamps the rgb values by the min and max values and stores the result into "result"
  1610. * @param min defines minimum clamping value (default is 0)
  1611. * @param max defines maximum clamping value (default is 1)
  1612. * @param result defines color to store the result into
  1613. * @returns the original Color3
  1614. */
  1615. Color3.prototype.clampToRef = function (min, max, result) {
  1616. if (min === void 0) { min = 0; }
  1617. if (max === void 0) { max = 1; }
  1618. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1619. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1620. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1621. return this;
  1622. };
  1623. /**
  1624. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1625. * @param otherColor defines the second operand
  1626. * @returns the new Color3
  1627. */
  1628. Color3.prototype.add = function (otherColor) {
  1629. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1630. };
  1631. /**
  1632. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1633. * @param otherColor defines the second operand
  1634. * @param result defines Color3 object to store the result into
  1635. * @returns the unmodified current Color3
  1636. */
  1637. Color3.prototype.addToRef = function (otherColor, result) {
  1638. result.r = this.r + otherColor.r;
  1639. result.g = this.g + otherColor.g;
  1640. result.b = this.b + otherColor.b;
  1641. return this;
  1642. };
  1643. /**
  1644. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1645. * @param otherColor defines the second operand
  1646. * @returns the new Color3
  1647. */
  1648. Color3.prototype.subtract = function (otherColor) {
  1649. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1650. };
  1651. /**
  1652. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1653. * @param otherColor defines the second operand
  1654. * @param result defines Color3 object to store the result into
  1655. * @returns the unmodified current Color3
  1656. */
  1657. Color3.prototype.subtractToRef = function (otherColor, result) {
  1658. result.r = this.r - otherColor.r;
  1659. result.g = this.g - otherColor.g;
  1660. result.b = this.b - otherColor.b;
  1661. return this;
  1662. };
  1663. /**
  1664. * Copy the current object
  1665. * @returns a new Color3 copied the current one
  1666. */
  1667. Color3.prototype.clone = function () {
  1668. return new Color3(this.r, this.g, this.b);
  1669. };
  1670. /**
  1671. * Copies the rgb values from the source in the current Color3
  1672. * @param source defines the source Color3 object
  1673. * @returns the updated Color3 object
  1674. */
  1675. Color3.prototype.copyFrom = function (source) {
  1676. this.r = source.r;
  1677. this.g = source.g;
  1678. this.b = source.b;
  1679. return this;
  1680. };
  1681. /**
  1682. * Updates the Color3 rgb values from the passed floats
  1683. * @param r defines the red component to read from
  1684. * @param g defines the green component to read from
  1685. * @param b defines the blue component to read from
  1686. * @returns the current Color3 object
  1687. */
  1688. Color3.prototype.copyFromFloats = function (r, g, b) {
  1689. this.r = r;
  1690. this.g = g;
  1691. this.b = b;
  1692. return this;
  1693. };
  1694. /**
  1695. * Updates the Color3 rgb values from the passed floats
  1696. * @param r defines the red component to read from
  1697. * @param g defines the green component to read from
  1698. * @param b defines the blue component to read from
  1699. * @returns the current Color3 object
  1700. */
  1701. Color3.prototype.set = function (r, g, b) {
  1702. return this.copyFromFloats(r, g, b);
  1703. };
  1704. /**
  1705. * Compute the Color3 hexadecimal code as a string
  1706. * @returns a string containing the hexadecimal representation of the Color3 object
  1707. */
  1708. Color3.prototype.toHexString = function () {
  1709. var intR = (this.r * 255) | 0;
  1710. var intG = (this.g * 255) | 0;
  1711. var intB = (this.b * 255) | 0;
  1712. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1713. };
  1714. /**
  1715. * Computes a new Color3 converted from the current one to linear space
  1716. * @returns a new Color3 object
  1717. */
  1718. Color3.prototype.toLinearSpace = function () {
  1719. var convertedColor = new Color3();
  1720. this.toLinearSpaceToRef(convertedColor);
  1721. return convertedColor;
  1722. };
  1723. /**
  1724. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1725. * @param convertedColor defines the Color3 object where to store the linear space version
  1726. * @returns the unmodified Color3
  1727. */
  1728. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1729. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1730. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1731. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1732. return this;
  1733. };
  1734. /**
  1735. * Computes a new Color3 converted from the current one to gamma space
  1736. * @returns a new Color3 object
  1737. */
  1738. Color3.prototype.toGammaSpace = function () {
  1739. var convertedColor = new Color3();
  1740. this.toGammaSpaceToRef(convertedColor);
  1741. return convertedColor;
  1742. };
  1743. /**
  1744. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1745. * @param convertedColor defines the Color3 object where to store the gamma space version
  1746. * @returns the unmodified Color3
  1747. */
  1748. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1749. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1750. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1751. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1752. return this;
  1753. };
  1754. // Statics
  1755. /**
  1756. * Creates a new Color3 from the string containing valid hexadecimal values
  1757. * @param hex defines a string containing valid hexadecimal values
  1758. * @returns a new Color3 object
  1759. */
  1760. Color3.FromHexString = function (hex) {
  1761. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1762. return new Color3(0, 0, 0);
  1763. }
  1764. var r = parseInt(hex.substring(1, 3), 16);
  1765. var g = parseInt(hex.substring(3, 5), 16);
  1766. var b = parseInt(hex.substring(5, 7), 16);
  1767. return Color3.FromInts(r, g, b);
  1768. };
  1769. /**
  1770. * Creates a new Vector3 from the starting index of the passed array
  1771. * @param array defines the source array
  1772. * @param offset defines an offset in the source array
  1773. * @returns a new Color3 object
  1774. */
  1775. Color3.FromArray = function (array, offset) {
  1776. if (offset === void 0) { offset = 0; }
  1777. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1778. };
  1779. /**
  1780. * Creates a new Color3 from integer values (< 256)
  1781. * @param r defines the red component to read from (value between 0 and 255)
  1782. * @param g defines the green component to read from (value between 0 and 255)
  1783. * @param b defines the blue component to read from (value between 0 and 255)
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.FromInts = function (r, g, b) {
  1787. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1788. };
  1789. /**
  1790. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1791. * @param start defines the start Color3 value
  1792. * @param end defines the end Color3 value
  1793. * @param amount defines the gradient value between start and end
  1794. * @returns a new Color3 object
  1795. */
  1796. Color3.Lerp = function (start, end, amount) {
  1797. var r = start.r + ((end.r - start.r) * amount);
  1798. var g = start.g + ((end.g - start.g) * amount);
  1799. var b = start.b + ((end.b - start.b) * amount);
  1800. return new Color3(r, g, b);
  1801. };
  1802. /**
  1803. * Returns a Color3 value containing a red color
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.Red = function () { return new Color3(1, 0, 0); };
  1807. /**
  1808. * Returns a Color3 value containing a green color
  1809. * @returns a new Color3 object
  1810. */
  1811. Color3.Green = function () { return new Color3(0, 1, 0); };
  1812. /**
  1813. * Returns a Color3 value containing a blue color
  1814. * @returns a new Color3 object
  1815. */
  1816. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1817. /**
  1818. * Returns a Color3 value containing a black color
  1819. * @returns a new Color3 object
  1820. */
  1821. Color3.Black = function () { return new Color3(0, 0, 0); };
  1822. /**
  1823. * Returns a Color3 value containing a white color
  1824. * @returns a new Color3 object
  1825. */
  1826. Color3.White = function () { return new Color3(1, 1, 1); };
  1827. /**
  1828. * Returns a Color3 value containing a purple color
  1829. * @returns a new Color3 object
  1830. */
  1831. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1832. /**
  1833. * Returns a Color3 value containing a magenta color
  1834. * @returns a new Color3 object
  1835. */
  1836. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1837. /**
  1838. * Returns a Color3 value containing a yellow color
  1839. * @returns a new Color3 object
  1840. */
  1841. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1842. /**
  1843. * Returns a Color3 value containing a gray color
  1844. * @returns a new Color3 object
  1845. */
  1846. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1847. /**
  1848. * Returns a Color3 value containing a teal color
  1849. * @returns a new Color3 object
  1850. */
  1851. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1852. /**
  1853. * Returns a Color3 value containing a random color
  1854. * @returns a new Color3 object
  1855. */
  1856. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1857. return Color3;
  1858. }());
  1859. BABYLON.Color3 = Color3;
  1860. /**
  1861. * Class used to hold a RBGA color
  1862. */
  1863. var Color4 = /** @class */ (function () {
  1864. /**
  1865. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1866. * @param r defines the red component (between 0 and 1, default is 0)
  1867. * @param g defines the green component (between 0 and 1, default is 0)
  1868. * @param b defines the blue component (between 0 and 1, default is 0)
  1869. * @param a defines the alpha component (between 0 and 1, default is 1)
  1870. */
  1871. function Color4(
  1872. /**
  1873. * Defines the red component (between 0 and 1, default is 0)
  1874. */
  1875. r,
  1876. /**
  1877. * Defines the green component (between 0 and 1, default is 0)
  1878. */
  1879. g,
  1880. /**
  1881. * Defines the blue component (between 0 and 1, default is 0)
  1882. */
  1883. b,
  1884. /**
  1885. * Defines the alpha component (between 0 and 1, default is 1)
  1886. */
  1887. a) {
  1888. if (r === void 0) { r = 0; }
  1889. if (g === void 0) { g = 0; }
  1890. if (b === void 0) { b = 0; }
  1891. if (a === void 0) { a = 1; }
  1892. this.r = r;
  1893. this.g = g;
  1894. this.b = b;
  1895. this.a = a;
  1896. }
  1897. // Operators
  1898. /**
  1899. * Adds in place the passed Color4 values to the current Color4 object
  1900. * @param right defines the second operand
  1901. * @returns the current updated Color4 object
  1902. */
  1903. Color4.prototype.addInPlace = function (right) {
  1904. this.r += right.r;
  1905. this.g += right.g;
  1906. this.b += right.b;
  1907. this.a += right.a;
  1908. return this;
  1909. };
  1910. /**
  1911. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1912. * @returns the new array
  1913. */
  1914. Color4.prototype.asArray = function () {
  1915. var result = new Array();
  1916. this.toArray(result, 0);
  1917. return result;
  1918. };
  1919. /**
  1920. * Stores from the starting index in the passed array the Color4 successive values
  1921. * @param array defines the array where to store the r,g,b components
  1922. * @param index defines an optional index in the target array to define where to start storing values
  1923. * @returns the current Color4 object
  1924. */
  1925. Color4.prototype.toArray = function (array, index) {
  1926. if (index === undefined) {
  1927. index = 0;
  1928. }
  1929. array[index] = this.r;
  1930. array[index + 1] = this.g;
  1931. array[index + 2] = this.b;
  1932. array[index + 3] = this.a;
  1933. return this;
  1934. };
  1935. /**
  1936. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1937. * @param right defines the second operand
  1938. * @returns a new Color4 object
  1939. */
  1940. Color4.prototype.add = function (right) {
  1941. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1942. };
  1943. /**
  1944. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1945. * @param right defines the second operand
  1946. * @returns a new Color4 object
  1947. */
  1948. Color4.prototype.subtract = function (right) {
  1949. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1950. };
  1951. /**
  1952. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1953. * @param right defines the second operand
  1954. * @param result defines the Color4 object where to store the result
  1955. * @returns the current Color4 object
  1956. */
  1957. Color4.prototype.subtractToRef = function (right, result) {
  1958. result.r = this.r - right.r;
  1959. result.g = this.g - right.g;
  1960. result.b = this.b - right.b;
  1961. result.a = this.a - right.a;
  1962. return this;
  1963. };
  1964. /**
  1965. * Creates a new Color4 with the current Color4 values multiplied by scale
  1966. * @param scale defines the scaling factor to apply
  1967. * @returns a new Color4 object
  1968. */
  1969. Color4.prototype.scale = function (scale) {
  1970. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1971. };
  1972. /**
  1973. * Multiplies the current Color4 values by scale and stores the result in "result"
  1974. * @param scale defines the scaling factor to apply
  1975. * @param result defines the Color4 object where to store the result
  1976. * @returns the current Color4.
  1977. */
  1978. Color4.prototype.scaleToRef = function (scale, result) {
  1979. result.r = this.r * scale;
  1980. result.g = this.g * scale;
  1981. result.b = this.b * scale;
  1982. result.a = this.a * scale;
  1983. return this;
  1984. };
  1985. /**
  1986. * Clamps the rgb values by the min and max values and stores the result into "result"
  1987. * @param min defines minimum clamping value (default is 0)
  1988. * @param max defines maximum clamping value (default is 1)
  1989. * @param result defines color to store the result into.
  1990. * @returns the cuurent Color4
  1991. */
  1992. Color4.prototype.clampToRef = function (min, max, result) {
  1993. if (min === void 0) { min = 0; }
  1994. if (max === void 0) { max = 1; }
  1995. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1996. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1997. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1998. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1999. return this;
  2000. };
  2001. /**
  2002. * Multipy an Color4 value by another and return a new Color4 object
  2003. * @param color defines the Color4 value to multiply by
  2004. * @returns a new Color4 object
  2005. */
  2006. Color4.prototype.multiply = function (color) {
  2007. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2008. };
  2009. /**
  2010. * Multipy a Color4 value by another and push the result in a reference value
  2011. * @param color defines the Color4 value to multiply by
  2012. * @param result defines the Color4 to fill the result in
  2013. * @returns the result Color4
  2014. */
  2015. Color4.prototype.multiplyToRef = function (color, result) {
  2016. result.r = this.r * color.r;
  2017. result.g = this.g * color.g;
  2018. result.b = this.b * color.b;
  2019. result.a = this.a * color.a;
  2020. return result;
  2021. };
  2022. /**
  2023. * Creates a string with the Color4 current values
  2024. * @returns the string representation of the Color4 object
  2025. */
  2026. Color4.prototype.toString = function () {
  2027. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2028. };
  2029. /**
  2030. * Returns the string "Color4"
  2031. * @returns "Color4"
  2032. */
  2033. Color4.prototype.getClassName = function () {
  2034. return "Color4";
  2035. };
  2036. /**
  2037. * Compute the Color4 hash code
  2038. * @returns an unique number that can be used to hash Color4 objects
  2039. */
  2040. Color4.prototype.getHashCode = function () {
  2041. var hash = this.r || 0;
  2042. hash = (hash * 397) ^ (this.g || 0);
  2043. hash = (hash * 397) ^ (this.b || 0);
  2044. hash = (hash * 397) ^ (this.a || 0);
  2045. return hash;
  2046. };
  2047. /**
  2048. * Creates a new Color4 copied from the current one
  2049. * @returns a new Color4 object
  2050. */
  2051. Color4.prototype.clone = function () {
  2052. return new Color4(this.r, this.g, this.b, this.a);
  2053. };
  2054. /**
  2055. * Copies the passed Color4 values into the current one
  2056. * @param source defines the source Color4 object
  2057. * @returns the current updated Color4 object
  2058. */
  2059. Color4.prototype.copyFrom = function (source) {
  2060. this.r = source.r;
  2061. this.g = source.g;
  2062. this.b = source.b;
  2063. this.a = source.a;
  2064. return this;
  2065. };
  2066. /**
  2067. * Copies the passed float values into the current one
  2068. * @param r defines the red component to read from
  2069. * @param g defines the green component to read from
  2070. * @param b defines the blue component to read from
  2071. * @param a defines the alpha component to read from
  2072. * @returns the current updated Color4 object
  2073. */
  2074. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2075. this.r = r;
  2076. this.g = g;
  2077. this.b = b;
  2078. this.a = a;
  2079. return this;
  2080. };
  2081. /**
  2082. * Copies the passed float values into the current one
  2083. * @param r defines the red component to read from
  2084. * @param g defines the green component to read from
  2085. * @param b defines the blue component to read from
  2086. * @param a defines the alpha component to read from
  2087. * @returns the current updated Color4 object
  2088. */
  2089. Color4.prototype.set = function (r, g, b, a) {
  2090. return this.copyFromFloats(r, g, b, a);
  2091. };
  2092. /**
  2093. * Compute the Color4 hexadecimal code as a string
  2094. * @returns a string containing the hexadecimal representation of the Color4 object
  2095. */
  2096. Color4.prototype.toHexString = function () {
  2097. var intR = (this.r * 255) | 0;
  2098. var intG = (this.g * 255) | 0;
  2099. var intB = (this.b * 255) | 0;
  2100. var intA = (this.a * 255) | 0;
  2101. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2102. };
  2103. /**
  2104. * Computes a new Color4 converted from the current one to linear space
  2105. * @returns a new Color4 object
  2106. */
  2107. Color4.prototype.toLinearSpace = function () {
  2108. var convertedColor = new Color4();
  2109. this.toLinearSpaceToRef(convertedColor);
  2110. return convertedColor;
  2111. };
  2112. /**
  2113. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2114. * @param convertedColor defines the Color4 object where to store the linear space version
  2115. * @returns the unmodified Color4
  2116. */
  2117. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2118. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2119. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2120. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2121. convertedColor.a = this.a;
  2122. return this;
  2123. };
  2124. /**
  2125. * Computes a new Color4 converted from the current one to gamma space
  2126. * @returns a new Color4 object
  2127. */
  2128. Color4.prototype.toGammaSpace = function () {
  2129. var convertedColor = new Color4();
  2130. this.toGammaSpaceToRef(convertedColor);
  2131. return convertedColor;
  2132. };
  2133. /**
  2134. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2135. * @param convertedColor defines the Color4 object where to store the gamma space version
  2136. * @returns the unmodified Color4
  2137. */
  2138. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2139. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2140. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2141. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2142. convertedColor.a = this.a;
  2143. return this;
  2144. };
  2145. // Statics
  2146. /**
  2147. * Creates a new Color4 from the string containing valid hexadecimal values
  2148. * @param hex defines a string containing valid hexadecimal values
  2149. * @returns a new Color4 object
  2150. */
  2151. Color4.FromHexString = function (hex) {
  2152. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2153. return new Color4(0.0, 0.0, 0.0, 0.0);
  2154. }
  2155. var r = parseInt(hex.substring(1, 3), 16);
  2156. var g = parseInt(hex.substring(3, 5), 16);
  2157. var b = parseInt(hex.substring(5, 7), 16);
  2158. var a = parseInt(hex.substring(7, 9), 16);
  2159. return Color4.FromInts(r, g, b, a);
  2160. };
  2161. /**
  2162. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2163. * @param left defines the start value
  2164. * @param right defines the end value
  2165. * @param amount defines the gradient factor
  2166. * @returns a new Color4 object
  2167. */
  2168. Color4.Lerp = function (left, right, amount) {
  2169. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2170. Color4.LerpToRef(left, right, amount, result);
  2171. return result;
  2172. };
  2173. /**
  2174. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2175. * @param left defines the start value
  2176. * @param right defines the end value
  2177. * @param amount defines the gradient factor
  2178. * @param result defines the Color4 object where to store data
  2179. */
  2180. Color4.LerpToRef = function (left, right, amount, result) {
  2181. result.r = left.r + (right.r - left.r) * amount;
  2182. result.g = left.g + (right.g - left.g) * amount;
  2183. result.b = left.b + (right.b - left.b) * amount;
  2184. result.a = left.a + (right.a - left.a) * amount;
  2185. };
  2186. /**
  2187. * Creates a new Color4 from the starting index element of the passed array
  2188. * @param array defines the source array to read from
  2189. * @param offset defines the offset in the source array
  2190. * @returns a new Color4 object
  2191. */
  2192. Color4.FromArray = function (array, offset) {
  2193. if (offset === void 0) { offset = 0; }
  2194. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2195. };
  2196. /**
  2197. * Creates a new Color3 from integer values (< 256)
  2198. * @param r defines the red component to read from (value between 0 and 255)
  2199. * @param g defines the green component to read from (value between 0 and 255)
  2200. * @param b defines the blue component to read from (value between 0 and 255)
  2201. * @param a defines the alpha component to read from (value between 0 and 255)
  2202. * @returns a new Color3 object
  2203. */
  2204. Color4.FromInts = function (r, g, b, a) {
  2205. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2206. };
  2207. /**
  2208. * Check the content of a given array and convert it to an array containing RGBA data
  2209. * If the original array was already containing count * 4 values then it is returned directly
  2210. * @param colors defines the array to check
  2211. * @param count defines the number of RGBA data to expect
  2212. * @returns an array containing count * 4 values (RGBA)
  2213. */
  2214. Color4.CheckColors4 = function (colors, count) {
  2215. // Check if color3 was used
  2216. if (colors.length === count * 3) {
  2217. var colors4 = [];
  2218. for (var index = 0; index < colors.length; index += 3) {
  2219. var newIndex = (index / 3) * 4;
  2220. colors4[newIndex] = colors[index];
  2221. colors4[newIndex + 1] = colors[index + 1];
  2222. colors4[newIndex + 2] = colors[index + 2];
  2223. colors4[newIndex + 3] = 1.0;
  2224. }
  2225. return colors4;
  2226. }
  2227. return colors;
  2228. };
  2229. return Color4;
  2230. }());
  2231. BABYLON.Color4 = Color4;
  2232. var Vector2 = /** @class */ (function () {
  2233. /**
  2234. * Creates a new Vector2 from the passed x and y coordinates.
  2235. */
  2236. function Vector2(x, y) {
  2237. this.x = x;
  2238. this.y = y;
  2239. }
  2240. /**
  2241. * Returns a string with the Vector2 coordinates.
  2242. */
  2243. Vector2.prototype.toString = function () {
  2244. return "{X: " + this.x + " Y:" + this.y + "}";
  2245. };
  2246. /**
  2247. * Returns the string "Vector2"
  2248. */
  2249. Vector2.prototype.getClassName = function () {
  2250. return "Vector2";
  2251. };
  2252. /**
  2253. * Returns the Vector2 hash code as a number.
  2254. */
  2255. Vector2.prototype.getHashCode = function () {
  2256. var hash = this.x || 0;
  2257. hash = (hash * 397) ^ (this.y || 0);
  2258. return hash;
  2259. };
  2260. // Operators
  2261. /**
  2262. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2263. * Returns the Vector2.
  2264. */
  2265. Vector2.prototype.toArray = function (array, index) {
  2266. if (index === void 0) { index = 0; }
  2267. array[index] = this.x;
  2268. array[index + 1] = this.y;
  2269. return this;
  2270. };
  2271. /**
  2272. * Returns a new array with 2 elements : the Vector2 coordinates.
  2273. */
  2274. Vector2.prototype.asArray = function () {
  2275. var result = new Array();
  2276. this.toArray(result, 0);
  2277. return result;
  2278. };
  2279. /**
  2280. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2281. * Returns the updated Vector2.
  2282. */
  2283. Vector2.prototype.copyFrom = function (source) {
  2284. this.x = source.x;
  2285. this.y = source.y;
  2286. return this;
  2287. };
  2288. /**
  2289. * Sets the Vector2 coordinates with the passed floats.
  2290. * Returns the updated Vector2.
  2291. */
  2292. Vector2.prototype.copyFromFloats = function (x, y) {
  2293. this.x = x;
  2294. this.y = y;
  2295. return this;
  2296. };
  2297. /**
  2298. * Sets the Vector2 coordinates with the passed floats.
  2299. * Returns the updated Vector2.
  2300. */
  2301. Vector2.prototype.set = function (x, y) {
  2302. return this.copyFromFloats(x, y);
  2303. };
  2304. /**
  2305. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2306. */
  2307. Vector2.prototype.add = function (otherVector) {
  2308. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2309. };
  2310. /**
  2311. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2312. * Returns the Vector2.
  2313. */
  2314. Vector2.prototype.addToRef = function (otherVector, result) {
  2315. result.x = this.x + otherVector.x;
  2316. result.y = this.y + otherVector.y;
  2317. return this;
  2318. };
  2319. /**
  2320. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2321. * Returns the updated Vector2.
  2322. */
  2323. Vector2.prototype.addInPlace = function (otherVector) {
  2324. this.x += otherVector.x;
  2325. this.y += otherVector.y;
  2326. return this;
  2327. };
  2328. /**
  2329. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2330. */
  2331. Vector2.prototype.addVector3 = function (otherVector) {
  2332. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2333. };
  2334. /**
  2335. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2336. */
  2337. Vector2.prototype.subtract = function (otherVector) {
  2338. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2339. };
  2340. /**
  2341. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2342. * Returns the Vector2.
  2343. */
  2344. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2345. result.x = this.x - otherVector.x;
  2346. result.y = this.y - otherVector.y;
  2347. return this;
  2348. };
  2349. /**
  2350. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2351. * Returns the updated Vector2.
  2352. */
  2353. Vector2.prototype.subtractInPlace = function (otherVector) {
  2354. this.x -= otherVector.x;
  2355. this.y -= otherVector.y;
  2356. return this;
  2357. };
  2358. /**
  2359. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2360. * Returns the updated Vector2.
  2361. */
  2362. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2363. this.x *= otherVector.x;
  2364. this.y *= otherVector.y;
  2365. return this;
  2366. };
  2367. /**
  2368. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2369. */
  2370. Vector2.prototype.multiply = function (otherVector) {
  2371. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2372. };
  2373. /**
  2374. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2375. * Returns the Vector2.
  2376. */
  2377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2378. result.x = this.x * otherVector.x;
  2379. result.y = this.y * otherVector.y;
  2380. return this;
  2381. };
  2382. /**
  2383. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2384. */
  2385. Vector2.prototype.multiplyByFloats = function (x, y) {
  2386. return new Vector2(this.x * x, this.y * y);
  2387. };
  2388. /**
  2389. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2390. */
  2391. Vector2.prototype.divide = function (otherVector) {
  2392. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2393. };
  2394. /**
  2395. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2396. * Returns the Vector2.
  2397. */
  2398. Vector2.prototype.divideToRef = function (otherVector, result) {
  2399. result.x = this.x / otherVector.x;
  2400. result.y = this.y / otherVector.y;
  2401. return this;
  2402. };
  2403. /**
  2404. * Divides the current Vector3 coordinates by the passed ones.
  2405. * Returns the updated Vector3.
  2406. */
  2407. Vector2.prototype.divideInPlace = function (otherVector) {
  2408. return this.divideToRef(otherVector, this);
  2409. };
  2410. /**
  2411. * Returns a new Vector2 with current Vector2 negated coordinates.
  2412. */
  2413. Vector2.prototype.negate = function () {
  2414. return new Vector2(-this.x, -this.y);
  2415. };
  2416. /**
  2417. * Multiply the Vector2 coordinates by scale.
  2418. * Returns the updated Vector2.
  2419. */
  2420. Vector2.prototype.scaleInPlace = function (scale) {
  2421. this.x *= scale;
  2422. this.y *= scale;
  2423. return this;
  2424. };
  2425. /**
  2426. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2427. */
  2428. Vector2.prototype.scale = function (scale) {
  2429. return new Vector2(this.x * scale, this.y * scale);
  2430. };
  2431. /**
  2432. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2433. */
  2434. Vector2.prototype.equals = function (otherVector) {
  2435. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2436. };
  2437. /**
  2438. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2439. */
  2440. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2441. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2442. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2443. };
  2444. // Properties
  2445. /**
  2446. * Returns the vector length (float).
  2447. */
  2448. Vector2.prototype.length = function () {
  2449. return Math.sqrt(this.x * this.x + this.y * this.y);
  2450. };
  2451. /**
  2452. * Returns the vector squared length (float);
  2453. */
  2454. Vector2.prototype.lengthSquared = function () {
  2455. return (this.x * this.x + this.y * this.y);
  2456. };
  2457. // Methods
  2458. /**
  2459. * Normalize the vector.
  2460. * Returns the updated Vector2.
  2461. */
  2462. Vector2.prototype.normalize = function () {
  2463. var len = this.length();
  2464. if (len === 0)
  2465. return this;
  2466. var num = 1.0 / len;
  2467. this.x *= num;
  2468. this.y *= num;
  2469. return this;
  2470. };
  2471. /**
  2472. * Returns a new Vector2 copied from the Vector2.
  2473. */
  2474. Vector2.prototype.clone = function () {
  2475. return new Vector2(this.x, this.y);
  2476. };
  2477. // Statics
  2478. /**
  2479. * Returns a new Vector2(0, 0)
  2480. */
  2481. Vector2.Zero = function () {
  2482. return new Vector2(0, 0);
  2483. };
  2484. /**
  2485. * Returns a new Vector2(1, 1)
  2486. */
  2487. Vector2.One = function () {
  2488. return new Vector2(1, 1);
  2489. };
  2490. /**
  2491. * Returns a new Vector2 set from the passed index element of the passed array.
  2492. */
  2493. Vector2.FromArray = function (array, offset) {
  2494. if (offset === void 0) { offset = 0; }
  2495. return new Vector2(array[offset], array[offset + 1]);
  2496. };
  2497. /**
  2498. * Sets "result" from the passed index element of the passed array.
  2499. */
  2500. Vector2.FromArrayToRef = function (array, offset, result) {
  2501. result.x = array[offset];
  2502. result.y = array[offset + 1];
  2503. };
  2504. /**
  2505. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2506. */
  2507. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2508. var squared = amount * amount;
  2509. var cubed = amount * squared;
  2510. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2511. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2512. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2513. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2514. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2515. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2516. return new Vector2(x, y);
  2517. };
  2518. /**
  2519. * 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".
  2520. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2521. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2522. */
  2523. Vector2.Clamp = function (value, min, max) {
  2524. var x = value.x;
  2525. x = (x > max.x) ? max.x : x;
  2526. x = (x < min.x) ? min.x : x;
  2527. var y = value.y;
  2528. y = (y > max.y) ? max.y : y;
  2529. y = (y < min.y) ? min.y : y;
  2530. return new Vector2(x, y);
  2531. };
  2532. /**
  2533. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2534. */
  2535. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2536. var squared = amount * amount;
  2537. var cubed = amount * squared;
  2538. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2539. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2540. var part3 = (cubed - (2.0 * squared)) + amount;
  2541. var part4 = cubed - squared;
  2542. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2543. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2544. return new Vector2(x, y);
  2545. };
  2546. /**
  2547. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2548. */
  2549. Vector2.Lerp = function (start, end, amount) {
  2550. var x = start.x + ((end.x - start.x) * amount);
  2551. var y = start.y + ((end.y - start.y) * amount);
  2552. return new Vector2(x, y);
  2553. };
  2554. /**
  2555. * Returns the dot product (float) of the vector "left" and the vector "right".
  2556. */
  2557. Vector2.Dot = function (left, right) {
  2558. return left.x * right.x + left.y * right.y;
  2559. };
  2560. /**
  2561. * Returns a new Vector2 equal to the normalized passed vector.
  2562. */
  2563. Vector2.Normalize = function (vector) {
  2564. var newVector = vector.clone();
  2565. newVector.normalize();
  2566. return newVector;
  2567. };
  2568. /**
  2569. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2570. */
  2571. Vector2.Minimize = function (left, right) {
  2572. var x = (left.x < right.x) ? left.x : right.x;
  2573. var y = (left.y < right.y) ? left.y : right.y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2578. */
  2579. Vector2.Maximize = function (left, right) {
  2580. var x = (left.x > right.x) ? left.x : right.x;
  2581. var y = (left.y > right.y) ? left.y : right.y;
  2582. return new Vector2(x, y);
  2583. };
  2584. /**
  2585. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2586. */
  2587. Vector2.Transform = function (vector, transformation) {
  2588. var r = Vector2.Zero();
  2589. Vector2.TransformToRef(vector, transformation, r);
  2590. return r;
  2591. };
  2592. /**
  2593. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2594. */
  2595. Vector2.TransformToRef = function (vector, transformation, result) {
  2596. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2597. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2598. result.x = x;
  2599. result.y = y;
  2600. };
  2601. /**
  2602. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2603. */
  2604. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2605. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2606. var sign = a < 0 ? -1 : 1;
  2607. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2608. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2609. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2610. };
  2611. /**
  2612. * Returns the distance (float) between the vectors "value1" and "value2".
  2613. */
  2614. Vector2.Distance = function (value1, value2) {
  2615. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2616. };
  2617. /**
  2618. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2619. */
  2620. Vector2.DistanceSquared = function (value1, value2) {
  2621. var x = value1.x - value2.x;
  2622. var y = value1.y - value2.y;
  2623. return (x * x) + (y * y);
  2624. };
  2625. /**
  2626. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2627. */
  2628. Vector2.Center = function (value1, value2) {
  2629. var center = value1.add(value2);
  2630. center.scaleInPlace(0.5);
  2631. return center;
  2632. };
  2633. /**
  2634. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2635. */
  2636. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2637. var l2 = Vector2.DistanceSquared(segA, segB);
  2638. if (l2 === 0.0) {
  2639. return Vector2.Distance(p, segA);
  2640. }
  2641. var v = segB.subtract(segA);
  2642. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2643. var proj = segA.add(v.multiplyByFloats(t, t));
  2644. return Vector2.Distance(p, proj);
  2645. };
  2646. return Vector2;
  2647. }());
  2648. BABYLON.Vector2 = Vector2;
  2649. /**
  2650. * Classed used to store (x,y,z) vector representation
  2651. * A Vector3 is the main object used in 3D geometry
  2652. * It can represent etiher the coordinates of a point the space, either a direction
  2653. * Reminder: Babylon.js uses a left handed forward facing system
  2654. */
  2655. var Vector3 = /** @class */ (function () {
  2656. /**
  2657. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2658. * @param x defines the first coordinates (on X axis)
  2659. * @param y defines the second coordinates (on Y axis)
  2660. * @param z defines the third coordinates (on Z axis)
  2661. */
  2662. function Vector3(
  2663. /**
  2664. * Defines the first coordinates (on X axis)
  2665. */
  2666. x,
  2667. /**
  2668. * Defines the second coordinates (on Y axis)
  2669. */
  2670. y,
  2671. /**
  2672. * Defines the third coordinates (on Z axis)
  2673. */
  2674. z) {
  2675. this.x = x;
  2676. this.y = y;
  2677. this.z = z;
  2678. }
  2679. /**
  2680. * Creates a string representation of the Vector3
  2681. * @returns a string with the Vector3 coordinates.
  2682. */
  2683. Vector3.prototype.toString = function () {
  2684. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2685. };
  2686. /**
  2687. * Gets the class name
  2688. * @returns the string "Vector3"
  2689. */
  2690. Vector3.prototype.getClassName = function () {
  2691. return "Vector3";
  2692. };
  2693. /**
  2694. * Creates the Vector3 hash code
  2695. * @returns a number which tends to be unique between Vector3 instances
  2696. */
  2697. Vector3.prototype.getHashCode = function () {
  2698. var hash = this.x || 0;
  2699. hash = (hash * 397) ^ (this.y || 0);
  2700. hash = (hash * 397) ^ (this.z || 0);
  2701. return hash;
  2702. };
  2703. // Operators
  2704. /**
  2705. * Creates an array containing three elements : the coordinates of the Vector3
  2706. * @returns a new array of numbers
  2707. */
  2708. Vector3.prototype.asArray = function () {
  2709. var result = [];
  2710. this.toArray(result, 0);
  2711. return result;
  2712. };
  2713. /**
  2714. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2715. * @param array defines the destination array
  2716. * @param index defines the offset in the destination array
  2717. * @returns the current Vector3
  2718. */
  2719. Vector3.prototype.toArray = function (array, index) {
  2720. if (index === void 0) { index = 0; }
  2721. array[index] = this.x;
  2722. array[index + 1] = this.y;
  2723. array[index + 2] = this.z;
  2724. return this;
  2725. };
  2726. /**
  2727. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2728. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2729. */
  2730. Vector3.prototype.toQuaternion = function () {
  2731. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2732. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2733. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2734. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2735. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2736. var cosy = Math.cos(this.y * 0.5);
  2737. var siny = Math.sin(this.y * 0.5);
  2738. result.x = coszMinusx * siny;
  2739. result.y = -sinzMinusx * siny;
  2740. result.z = sinxPlusz * cosy;
  2741. result.w = cosxPlusz * cosy;
  2742. return result;
  2743. };
  2744. /**
  2745. * Adds the passed vector to the current Vector3
  2746. * @param otherVector defines the second operand
  2747. * @returns the current updated Vector3
  2748. */
  2749. Vector3.prototype.addInPlace = function (otherVector) {
  2750. this.x += otherVector.x;
  2751. this.y += otherVector.y;
  2752. this.z += otherVector.z;
  2753. return this;
  2754. };
  2755. /**
  2756. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2757. * @param otherVector defines the second operand
  2758. * @returns the resulting Vector3
  2759. */
  2760. Vector3.prototype.add = function (otherVector) {
  2761. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2762. };
  2763. /**
  2764. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2765. * @param otherVector defines the second operand
  2766. * @param result defines the Vector3 object where to store the result
  2767. * @returns the current Vector3
  2768. */
  2769. Vector3.prototype.addToRef = function (otherVector, result) {
  2770. result.x = this.x + otherVector.x;
  2771. result.y = this.y + otherVector.y;
  2772. result.z = this.z + otherVector.z;
  2773. return this;
  2774. };
  2775. /**
  2776. * Subtract the passed vector from the current Vector3
  2777. * @param otherVector defines the second operand
  2778. * @returns the current updated Vector3
  2779. */
  2780. Vector3.prototype.subtractInPlace = function (otherVector) {
  2781. this.x -= otherVector.x;
  2782. this.y -= otherVector.y;
  2783. this.z -= otherVector.z;
  2784. return this;
  2785. };
  2786. /**
  2787. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2788. * @param otherVector defines the second operand
  2789. * @returns the resulting Vector3
  2790. */
  2791. Vector3.prototype.subtract = function (otherVector) {
  2792. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2793. };
  2794. /**
  2795. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2796. * @param otherVector defines the second operand
  2797. * @param result defines the Vector3 object where to store the result
  2798. * @returns the current Vector3
  2799. */
  2800. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2801. result.x = this.x - otherVector.x;
  2802. result.y = this.y - otherVector.y;
  2803. result.z = this.z - otherVector.z;
  2804. return this;
  2805. };
  2806. /**
  2807. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2808. * @param x defines the x coordinate of the operand
  2809. * @param y defines the y coordinate of the operand
  2810. * @param z defines the z coordinate of the operand
  2811. * @returns the resulting Vector3
  2812. */
  2813. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2814. return new Vector3(this.x - x, this.y - y, this.z - z);
  2815. };
  2816. /**
  2817. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2818. * @param x defines the x coordinate of the operand
  2819. * @param y defines the y coordinate of the operand
  2820. * @param z defines the z coordinate of the operand
  2821. * @param result defines the Vector3 object where to store the result
  2822. * @returns the current Vector3
  2823. */
  2824. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2825. result.x = this.x - x;
  2826. result.y = this.y - y;
  2827. result.z = this.z - z;
  2828. return this;
  2829. };
  2830. /**
  2831. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2832. * @returns a new Vector3
  2833. */
  2834. Vector3.prototype.negate = function () {
  2835. return new Vector3(-this.x, -this.y, -this.z);
  2836. };
  2837. /**
  2838. * Multiplies the Vector3 coordinates by the float "scale"
  2839. * @param scale defines the multiplier factor
  2840. * @returns the current updated Vector3
  2841. */
  2842. Vector3.prototype.scaleInPlace = function (scale) {
  2843. this.x *= scale;
  2844. this.y *= scale;
  2845. this.z *= scale;
  2846. return this;
  2847. };
  2848. /**
  2849. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2850. * @param scale defines the multiplier factor
  2851. * @returns a new Vector3
  2852. */
  2853. Vector3.prototype.scale = function (scale) {
  2854. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2855. };
  2856. /**
  2857. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2858. * @param scale defines the multiplier factor
  2859. * @param result defines the Vector3 object where to store the result
  2860. * @returns the current Vector3
  2861. */
  2862. Vector3.prototype.scaleToRef = function (scale, result) {
  2863. result.x = this.x * scale;
  2864. result.y = this.y * scale;
  2865. result.z = this.z * scale;
  2866. return this;
  2867. };
  2868. /**
  2869. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2870. * @param otherVector defines the second operand
  2871. * @returns true if both vectors are equals
  2872. */
  2873. Vector3.prototype.equals = function (otherVector) {
  2874. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2875. };
  2876. /**
  2877. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2878. * @param otherVector defines the second operand
  2879. * @param epsilon defines the minimal distance to define values as equals
  2880. * @returns true if both vectors are distant less than epsilon
  2881. */
  2882. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2883. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2884. 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);
  2885. };
  2886. /**
  2887. * Returns true if the current Vector3 coordinates equals the passed floats
  2888. * @param x defines the x coordinate of the operand
  2889. * @param y defines the y coordinate of the operand
  2890. * @param z defines the z coordinate of the operand
  2891. * @returns true if both vectors are equals
  2892. */
  2893. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2894. return this.x === x && this.y === y && this.z === z;
  2895. };
  2896. /**
  2897. * Multiplies the current Vector3 coordinates by the passed ones
  2898. * @param otherVector defines the second operand
  2899. * @returns the current updated Vector3
  2900. */
  2901. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2902. this.x *= otherVector.x;
  2903. this.y *= otherVector.y;
  2904. this.z *= otherVector.z;
  2905. return this;
  2906. };
  2907. /**
  2908. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2909. * @param otherVector defines the second operand
  2910. * @returns the new Vector3
  2911. */
  2912. Vector3.prototype.multiply = function (otherVector) {
  2913. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2914. };
  2915. /**
  2916. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2917. * @param otherVector defines the second operand
  2918. * @param result defines the Vector3 object where to store the result
  2919. * @returns the current Vector3
  2920. */
  2921. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2922. result.x = this.x * otherVector.x;
  2923. result.y = this.y * otherVector.y;
  2924. result.z = this.z * otherVector.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2929. * @param x defines the x coordinate of the operand
  2930. * @param y defines the y coordinate of the operand
  2931. * @param z defines the z coordinate of the operand
  2932. * @returns the new Vector3
  2933. */
  2934. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2935. return new Vector3(this.x * x, this.y * y, this.z * z);
  2936. };
  2937. /**
  2938. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2939. * @param otherVector defines the second operand
  2940. * @returns the new Vector3
  2941. */
  2942. Vector3.prototype.divide = function (otherVector) {
  2943. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2944. };
  2945. /**
  2946. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2947. * @param otherVector defines the second operand
  2948. * @param result defines the Vector3 object where to store the result
  2949. * @returns the current Vector3
  2950. */
  2951. Vector3.prototype.divideToRef = function (otherVector, result) {
  2952. result.x = this.x / otherVector.x;
  2953. result.y = this.y / otherVector.y;
  2954. result.z = this.z / otherVector.z;
  2955. return this;
  2956. };
  2957. /**
  2958. * Divides the current Vector3 coordinates by the passed ones.
  2959. * @param otherVector defines the second operand
  2960. * @returns the current updated Vector3
  2961. */
  2962. Vector3.prototype.divideInPlace = function (otherVector) {
  2963. return this.divideToRef(otherVector, this);
  2964. };
  2965. /**
  2966. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2967. * @param other defines the second operand
  2968. * @returns the current updated Vector3
  2969. */
  2970. Vector3.prototype.minimizeInPlace = function (other) {
  2971. if (other.x < this.x)
  2972. this.x = other.x;
  2973. if (other.y < this.y)
  2974. this.y = other.y;
  2975. if (other.z < this.z)
  2976. this.z = other.z;
  2977. return this;
  2978. };
  2979. /**
  2980. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2981. * @param other defines the second operand
  2982. * @returns the current updated Vector3
  2983. */
  2984. Vector3.prototype.maximizeInPlace = function (other) {
  2985. if (other.x > this.x)
  2986. this.x = other.x;
  2987. if (other.y > this.y)
  2988. this.y = other.y;
  2989. if (other.z > this.z)
  2990. this.z = other.z;
  2991. return this;
  2992. };
  2993. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2994. /**
  2995. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2996. */
  2997. get: function () {
  2998. var absX = Math.abs(this.x);
  2999. var absY = Math.abs(this.y);
  3000. if (absX !== absY) {
  3001. return true;
  3002. }
  3003. var absZ = Math.abs(this.z);
  3004. if (absX !== absZ) {
  3005. return true;
  3006. }
  3007. if (absY !== absZ) {
  3008. return true;
  3009. }
  3010. return false;
  3011. },
  3012. enumerable: true,
  3013. configurable: true
  3014. });
  3015. // Properties
  3016. /**
  3017. * Gets the length of the Vector3
  3018. * @returns the length of the Vecto3
  3019. */
  3020. Vector3.prototype.length = function () {
  3021. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3022. };
  3023. /**
  3024. * Gets the squared length of the Vector3
  3025. * @returns squared length of the Vector3
  3026. */
  3027. Vector3.prototype.lengthSquared = function () {
  3028. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3029. };
  3030. /**
  3031. * Normalize the current Vector3.
  3032. * Please note that this is an in place operation.
  3033. * @returns the current updated Vector3
  3034. */
  3035. Vector3.prototype.normalize = function () {
  3036. var len = this.length();
  3037. if (len === 0 || len === 1.0)
  3038. return this;
  3039. var num = 1.0 / len;
  3040. this.x *= num;
  3041. this.y *= num;
  3042. this.z *= num;
  3043. return this;
  3044. };
  3045. /**
  3046. * Normalize the current Vector3 to a new vector
  3047. * @returns the new Vector3
  3048. */
  3049. Vector3.prototype.normalizeToNew = function () {
  3050. var normalized = new Vector3(0, 0, 0);
  3051. this.normalizeToRef(normalized);
  3052. return normalized;
  3053. };
  3054. /**
  3055. * Normalize the current Vector3 to the reference
  3056. * @param reference define the Vector3 to update
  3057. * @returns the updated Vector3
  3058. */
  3059. Vector3.prototype.normalizeToRef = function (reference) {
  3060. var len = this.length();
  3061. if (len === 0 || len === 1.0) {
  3062. reference.set(this.x, this.y, this.z);
  3063. return reference;
  3064. }
  3065. var scale = 1.0 / len;
  3066. this.scaleToRef(scale, reference);
  3067. return reference;
  3068. };
  3069. /**
  3070. * Creates a new Vector3 copied from the current Vector3
  3071. * @returns the new Vector3
  3072. */
  3073. Vector3.prototype.clone = function () {
  3074. return new Vector3(this.x, this.y, this.z);
  3075. };
  3076. /**
  3077. * Copies the passed vector coordinates to the current Vector3 ones
  3078. * @param source defines the source Vector3
  3079. * @returns the current updated Vector3
  3080. */
  3081. Vector3.prototype.copyFrom = function (source) {
  3082. this.x = source.x;
  3083. this.y = source.y;
  3084. this.z = source.z;
  3085. return this;
  3086. };
  3087. /**
  3088. * Copies the passed floats to the current Vector3 coordinates
  3089. * @param x defines the x coordinate of the operand
  3090. * @param y defines the y coordinate of the operand
  3091. * @param z defines the z coordinate of the operand
  3092. * @returns the current updated Vector3
  3093. */
  3094. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3095. this.x = x;
  3096. this.y = y;
  3097. this.z = z;
  3098. return this;
  3099. };
  3100. /**
  3101. * Copies the passed floats to the current Vector3 coordinates
  3102. * @param x defines the x coordinate of the operand
  3103. * @param y defines the y coordinate of the operand
  3104. * @param z defines the z coordinate of the operand
  3105. * @returns the current updated Vector3
  3106. */
  3107. Vector3.prototype.set = function (x, y, z) {
  3108. return this.copyFromFloats(x, y, z);
  3109. };
  3110. // Statics
  3111. /**
  3112. * Get the clip factor between two vectors
  3113. * @param vector0 defines the first operand
  3114. * @param vector1 defines the second operand
  3115. * @param axis defines the axis to use
  3116. * @param size defines the size along the axis
  3117. * @returns the clip factor
  3118. */
  3119. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3120. var d0 = Vector3.Dot(vector0, axis) - size;
  3121. var d1 = Vector3.Dot(vector1, axis) - size;
  3122. var s = d0 / (d0 - d1);
  3123. return s;
  3124. };
  3125. /**
  3126. * Get angle between two vectors
  3127. * @param vector0 angle between vector0 and vector1
  3128. * @param vector1 angle between vector0 and vector1
  3129. * @param normal direction of the normal
  3130. * @return the angle between vector0 and vector1
  3131. */
  3132. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3133. var v0 = vector0.clone().normalize();
  3134. var v1 = vector1.clone().normalize();
  3135. var dot = Vector3.Dot(v0, v1);
  3136. var n = Vector3.Cross(v0, v1);
  3137. if (Vector3.Dot(n, normal) > 0) {
  3138. return Math.acos(dot);
  3139. }
  3140. return -Math.acos(dot);
  3141. };
  3142. /**
  3143. * Returns a new Vector3 set from the index "offset" of the passed array
  3144. * @param array defines the source array
  3145. * @param offset defines the offset in the source array
  3146. * @returns the new Vector3
  3147. */
  3148. Vector3.FromArray = function (array, offset) {
  3149. if (!offset) {
  3150. offset = 0;
  3151. }
  3152. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3153. };
  3154. /**
  3155. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3156. * This function is deprecated. Use FromArray instead
  3157. * @param array defines the source array
  3158. * @param offset defines the offset in the source array
  3159. * @returns the new Vector3
  3160. */
  3161. Vector3.FromFloatArray = function (array, offset) {
  3162. return Vector3.FromArray(array, offset);
  3163. };
  3164. /**
  3165. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3166. * @param array defines the source array
  3167. * @param offset defines the offset in the source array
  3168. * @param result defines the Vector3 where to store the result
  3169. */
  3170. Vector3.FromArrayToRef = function (array, offset, result) {
  3171. result.x = array[offset];
  3172. result.y = array[offset + 1];
  3173. result.z = array[offset + 2];
  3174. };
  3175. /**
  3176. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3177. * This function is deprecated. Use FromArrayToRef instead.
  3178. * @param array defines the source array
  3179. * @param offset defines the offset in the source array
  3180. * @param result defines the Vector3 where to store the result
  3181. */
  3182. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3183. return Vector3.FromArrayToRef(array, offset, result);
  3184. };
  3185. /**
  3186. * Sets the passed vector "result" with the passed floats.
  3187. * @param x defines the x coordinate of the source
  3188. * @param y defines the y coordinate of the source
  3189. * @param z defines the z coordinate of the source
  3190. * @param result defines the Vector3 where to store the result
  3191. */
  3192. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3193. result.x = x;
  3194. result.y = y;
  3195. result.z = z;
  3196. };
  3197. /**
  3198. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3199. * @returns a new empty Vector3
  3200. */
  3201. Vector3.Zero = function () {
  3202. return new Vector3(0.0, 0.0, 0.0);
  3203. };
  3204. /**
  3205. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3206. * @returns a new unit Vector3
  3207. */
  3208. Vector3.One = function () {
  3209. return new Vector3(1.0, 1.0, 1.0);
  3210. };
  3211. /**
  3212. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3213. * @returns a new up Vector3
  3214. */
  3215. Vector3.Up = function () {
  3216. return new Vector3(0.0, 1.0, 0.0);
  3217. };
  3218. /**
  3219. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3220. * @returns a new forward Vector3
  3221. */
  3222. Vector3.Forward = function () {
  3223. return new Vector3(0.0, 0.0, 1.0);
  3224. };
  3225. /**
  3226. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3227. * @returns a new right Vector3
  3228. */
  3229. Vector3.Right = function () {
  3230. return new Vector3(1.0, 0.0, 0.0);
  3231. };
  3232. /**
  3233. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3234. * @returns a new left Vector3
  3235. */
  3236. Vector3.Left = function () {
  3237. return new Vector3(-1.0, 0.0, 0.0);
  3238. };
  3239. /**
  3240. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3241. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3242. * @param vector defines the Vector3 to transform
  3243. * @param transformation defines the transformation matrix
  3244. * @returns the transformed Vector3
  3245. */
  3246. Vector3.TransformCoordinates = function (vector, transformation) {
  3247. var result = Vector3.Zero();
  3248. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3249. return result;
  3250. };
  3251. /**
  3252. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3253. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3254. * @param vector defines the Vector3 to transform
  3255. * @param transformation defines the transformation matrix
  3256. * @param result defines the Vector3 where to store the result
  3257. */
  3258. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3259. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3260. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3261. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3262. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3263. result.x = x / w;
  3264. result.y = y / w;
  3265. result.z = z / w;
  3266. };
  3267. /**
  3268. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3269. * This method computes tranformed coordinates only, not transformed direction vectors
  3270. * @param x define the x coordinate of the source vector
  3271. * @param y define the y coordinate of the source vector
  3272. * @param z define the z coordinate of the source vector
  3273. * @param transformation defines the transformation matrix
  3274. * @param result defines the Vector3 where to store the result
  3275. */
  3276. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3277. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3278. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3279. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3280. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3281. result.x = rx / rw;
  3282. result.y = ry / rw;
  3283. result.z = rz / rw;
  3284. };
  3285. /**
  3286. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3287. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3288. * @param vector defines the Vector3 to transform
  3289. * @param transformation defines the transformation matrix
  3290. * @returns the new Vector3
  3291. */
  3292. Vector3.TransformNormal = function (vector, transformation) {
  3293. var result = Vector3.Zero();
  3294. Vector3.TransformNormalToRef(vector, transformation, result);
  3295. return result;
  3296. };
  3297. /**
  3298. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3299. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3300. * @param vector defines the Vector3 to transform
  3301. * @param transformation defines the transformation matrix
  3302. * @param result defines the Vector3 where to store the result
  3303. */
  3304. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3305. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3306. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3307. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3308. result.x = x;
  3309. result.y = y;
  3310. result.z = z;
  3311. };
  3312. /**
  3313. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3314. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3315. * @param x define the x coordinate of the source vector
  3316. * @param y define the y coordinate of the source vector
  3317. * @param z define the z coordinate of the source vector
  3318. * @param transformation defines the transformation matrix
  3319. * @param result defines the Vector3 where to store the result
  3320. */
  3321. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3322. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3323. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3324. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3325. };
  3326. /**
  3327. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3328. * @param value1 defines the first control point
  3329. * @param value2 defines the second control point
  3330. * @param value3 defines the third control point
  3331. * @param value4 defines the fourth control point
  3332. * @param amount defines the amount on the spline to use
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3336. var squared = amount * amount;
  3337. var cubed = amount * squared;
  3338. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3339. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3340. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3341. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3342. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3343. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3344. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3345. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3346. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3347. return new Vector3(x, y, z);
  3348. };
  3349. /**
  3350. * 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"
  3351. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3352. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3353. * @param value defines the current value
  3354. * @param min defines the lower range value
  3355. * @param max defines the upper range value
  3356. * @returns the new Vector3
  3357. */
  3358. Vector3.Clamp = function (value, min, max) {
  3359. var x = value.x;
  3360. x = (x > max.x) ? max.x : x;
  3361. x = (x < min.x) ? min.x : x;
  3362. var y = value.y;
  3363. y = (y > max.y) ? max.y : y;
  3364. y = (y < min.y) ? min.y : y;
  3365. var z = value.z;
  3366. z = (z > max.z) ? max.z : z;
  3367. z = (z < min.z) ? min.z : z;
  3368. return new Vector3(x, y, z);
  3369. };
  3370. /**
  3371. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3372. * @param value1 defines the first control point
  3373. * @param tangent1 defines the first tangent vector
  3374. * @param value2 defines the second control point
  3375. * @param tangent2 defines the second tangent vector
  3376. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3377. * @returns the new Vector3
  3378. */
  3379. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3380. var squared = amount * amount;
  3381. var cubed = amount * squared;
  3382. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3383. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3384. var part3 = (cubed - (2.0 * squared)) + amount;
  3385. var part4 = cubed - squared;
  3386. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3387. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3388. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3389. return new Vector3(x, y, z);
  3390. };
  3391. /**
  3392. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3393. * @param start defines the start value
  3394. * @param end defines the end value
  3395. * @param amount max defines amount between both (between 0 and 1)
  3396. * @returns the new Vector3
  3397. */
  3398. Vector3.Lerp = function (start, end, amount) {
  3399. var result = new Vector3(0, 0, 0);
  3400. Vector3.LerpToRef(start, end, amount, result);
  3401. return result;
  3402. };
  3403. /**
  3404. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3405. * @param start defines the start value
  3406. * @param end defines the end value
  3407. * @param amount max defines amount between both (between 0 and 1)
  3408. * @param result defines the Vector3 where to store the result
  3409. */
  3410. Vector3.LerpToRef = function (start, end, amount, result) {
  3411. result.x = start.x + ((end.x - start.x) * amount);
  3412. result.y = start.y + ((end.y - start.y) * amount);
  3413. result.z = start.z + ((end.z - start.z) * amount);
  3414. };
  3415. /**
  3416. * Returns the dot product (float) between the vectors "left" and "right"
  3417. * @param left defines the left operand
  3418. * @param right defines the right operand
  3419. * @returns the dot product
  3420. */
  3421. Vector3.Dot = function (left, right) {
  3422. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3423. };
  3424. /**
  3425. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3426. * The cross product is then orthogonal to both "left" and "right"
  3427. * @param left defines the left operand
  3428. * @param right defines the right operand
  3429. * @returns the cross product
  3430. */
  3431. Vector3.Cross = function (left, right) {
  3432. var result = Vector3.Zero();
  3433. Vector3.CrossToRef(left, right, result);
  3434. return result;
  3435. };
  3436. /**
  3437. * Sets the passed vector "result" with the cross product of "left" and "right"
  3438. * The cross product is then orthogonal to both "left" and "right"
  3439. * @param left defines the left operand
  3440. * @param right defines the right operand
  3441. * @param result defines the Vector3 where to store the result
  3442. */
  3443. Vector3.CrossToRef = function (left, right, result) {
  3444. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3445. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3446. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3447. result.copyFrom(MathTmp.Vector3[0]);
  3448. };
  3449. /**
  3450. * Returns a new Vector3 as the normalization of the passed vector
  3451. * @param vector defines the Vector3 to normalize
  3452. * @returns the new Vector3
  3453. */
  3454. Vector3.Normalize = function (vector) {
  3455. var result = Vector3.Zero();
  3456. Vector3.NormalizeToRef(vector, result);
  3457. return result;
  3458. };
  3459. /**
  3460. * Sets the passed vector "result" with the normalization of the passed first vector
  3461. * @param vector defines the Vector3 to normalize
  3462. * @param result defines the Vector3 where to store the result
  3463. */
  3464. Vector3.NormalizeToRef = function (vector, result) {
  3465. result.copyFrom(vector);
  3466. result.normalize();
  3467. };
  3468. /**
  3469. * Project a Vector3 onto screen space
  3470. * @param vector defines the Vector3 to project
  3471. * @param world defines the world matrix to use
  3472. * @param transform defines the transform (view x projection) matrix to use
  3473. * @param viewport defines the screen viewport to use
  3474. * @returns the new Vector3
  3475. */
  3476. Vector3.Project = function (vector, world, transform, viewport) {
  3477. var cw = viewport.width;
  3478. var ch = viewport.height;
  3479. var cx = viewport.x;
  3480. var cy = viewport.y;
  3481. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3482. 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);
  3483. var matrix = MathTmp.Matrix[0];
  3484. world.multiplyToRef(transform, matrix);
  3485. matrix.multiplyToRef(viewportMatrix, matrix);
  3486. return Vector3.TransformCoordinates(vector, matrix);
  3487. };
  3488. /**
  3489. * Unproject from screen space to object space
  3490. * @param source defines the screen space Vector3 to use
  3491. * @param viewportWidth defines the current width of the viewport
  3492. * @param viewportHeight defines the current height of the viewport
  3493. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3494. * @param transform defines the transform (view x projection) matrix to use
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3498. var matrix = MathTmp.Matrix[0];
  3499. world.multiplyToRef(transform, matrix);
  3500. matrix.invert();
  3501. source.x = source.x / viewportWidth * 2 - 1;
  3502. source.y = -(source.y / viewportHeight * 2 - 1);
  3503. var vector = Vector3.TransformCoordinates(source, matrix);
  3504. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3505. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3506. vector = vector.scale(1.0 / num);
  3507. }
  3508. return vector;
  3509. };
  3510. /**
  3511. * Unproject from screen space to object space
  3512. * @param source defines the screen space Vector3 to use
  3513. * @param viewportWidth defines the current width of the viewport
  3514. * @param viewportHeight defines the current height of the viewport
  3515. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3516. * @param view defines the view matrix to use
  3517. * @param projection defines the projection matrix to use
  3518. * @returns the new Vector3
  3519. */
  3520. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3521. var result = Vector3.Zero();
  3522. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3523. return result;
  3524. };
  3525. /**
  3526. * Unproject from screen space to object space
  3527. * @param source defines the screen space Vector3 to use
  3528. * @param viewportWidth defines the current width of the viewport
  3529. * @param viewportHeight defines the current height of the viewport
  3530. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3531. * @param view defines the view matrix to use
  3532. * @param projection defines the projection matrix to use
  3533. * @param result defines the Vector3 where to store the result
  3534. */
  3535. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3536. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3537. };
  3538. /**
  3539. * Unproject from screen space to object space
  3540. * @param sourceX defines the screen space x coordinate to use
  3541. * @param sourceY defines the screen space y coordinate to use
  3542. * @param sourceZ defines the screen space z coordinate to use
  3543. * @param viewportWidth defines the current width of the viewport
  3544. * @param viewportHeight defines the current height of the viewport
  3545. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3546. * @param view defines the view matrix to use
  3547. * @param projection defines the projection matrix to use
  3548. * @param result defines the Vector3 where to store the result
  3549. */
  3550. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3551. var matrix = MathTmp.Matrix[0];
  3552. world.multiplyToRef(view, matrix);
  3553. matrix.multiplyToRef(projection, matrix);
  3554. matrix.invert();
  3555. var screenSource = MathTmp.Vector3[0];
  3556. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3557. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3558. screenSource.z = 2 * sourceZ - 1.0;
  3559. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3560. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3561. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3562. result.scaleInPlace(1.0 / num);
  3563. }
  3564. };
  3565. /**
  3566. * Gets the minimal coordinate values between two Vector3
  3567. * @param left defines the first operand
  3568. * @param right defines the second operand
  3569. * @returns the new Vector3
  3570. */
  3571. Vector3.Minimize = function (left, right) {
  3572. var min = left.clone();
  3573. min.minimizeInPlace(right);
  3574. return min;
  3575. };
  3576. /**
  3577. * Gets the maximal coordinate values between two Vector3
  3578. * @param left defines the first operand
  3579. * @param right defines the second operand
  3580. * @returns the new Vector3
  3581. */
  3582. Vector3.Maximize = function (left, right) {
  3583. var max = left.clone();
  3584. max.maximizeInPlace(right);
  3585. return max;
  3586. };
  3587. /**
  3588. * Returns the distance between the vectors "value1" and "value2"
  3589. * @param value1 defines the first operand
  3590. * @param value2 defines the second operand
  3591. * @returns the distance
  3592. */
  3593. Vector3.Distance = function (value1, value2) {
  3594. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3595. };
  3596. /**
  3597. * Returns the squared distance between the vectors "value1" and "value2"
  3598. * @param value1 defines the first operand
  3599. * @param value2 defines the second operand
  3600. * @returns the squared distance
  3601. */
  3602. Vector3.DistanceSquared = function (value1, value2) {
  3603. var x = value1.x - value2.x;
  3604. var y = value1.y - value2.y;
  3605. var z = value1.z - value2.z;
  3606. return (x * x) + (y * y) + (z * z);
  3607. };
  3608. /**
  3609. * Returns a new Vector3 located at the center between "value1" and "value2"
  3610. * @param value1 defines the first operand
  3611. * @param value2 defines the second operand
  3612. * @returns the new Vector3
  3613. */
  3614. Vector3.Center = function (value1, value2) {
  3615. var center = value1.add(value2);
  3616. center.scaleInPlace(0.5);
  3617. return center;
  3618. };
  3619. /**
  3620. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3621. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3622. * to something in order to rotate it from its local system to the given target system
  3623. * Note: axis1, axis2 and axis3 are normalized during this operation
  3624. * @param axis1 defines the first axis
  3625. * @param axis2 defines the second axis
  3626. * @param axis3 defines the third axis
  3627. * @returns a new Vector3
  3628. */
  3629. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3630. var rotation = Vector3.Zero();
  3631. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3632. return rotation;
  3633. };
  3634. /**
  3635. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3636. * @param axis1 defines the first axis
  3637. * @param axis2 defines the second axis
  3638. * @param axis3 defines the third axis
  3639. * @param ref defines the Vector3 where to store the result
  3640. */
  3641. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3642. var quat = MathTmp.Quaternion[0];
  3643. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3644. quat.toEulerAnglesToRef(ref);
  3645. };
  3646. return Vector3;
  3647. }());
  3648. BABYLON.Vector3 = Vector3;
  3649. //Vector4 class created for EulerAngle class conversion to Quaternion
  3650. var Vector4 = /** @class */ (function () {
  3651. /**
  3652. * Creates a Vector4 object from the passed floats.
  3653. */
  3654. function Vector4(x, y, z, w) {
  3655. this.x = x;
  3656. this.y = y;
  3657. this.z = z;
  3658. this.w = w;
  3659. }
  3660. /**
  3661. * Returns the string with the Vector4 coordinates.
  3662. */
  3663. Vector4.prototype.toString = function () {
  3664. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3665. };
  3666. /**
  3667. * Returns the string "Vector4".
  3668. */
  3669. Vector4.prototype.getClassName = function () {
  3670. return "Vector4";
  3671. };
  3672. /**
  3673. * Returns the Vector4 hash code.
  3674. */
  3675. Vector4.prototype.getHashCode = function () {
  3676. var hash = this.x || 0;
  3677. hash = (hash * 397) ^ (this.y || 0);
  3678. hash = (hash * 397) ^ (this.z || 0);
  3679. hash = (hash * 397) ^ (this.w || 0);
  3680. return hash;
  3681. };
  3682. // Operators
  3683. /**
  3684. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3685. */
  3686. Vector4.prototype.asArray = function () {
  3687. var result = new Array();
  3688. this.toArray(result, 0);
  3689. return result;
  3690. };
  3691. /**
  3692. * Populates the passed array from the passed index with the Vector4 coordinates.
  3693. * Returns the Vector4.
  3694. */
  3695. Vector4.prototype.toArray = function (array, index) {
  3696. if (index === undefined) {
  3697. index = 0;
  3698. }
  3699. array[index] = this.x;
  3700. array[index + 1] = this.y;
  3701. array[index + 2] = this.z;
  3702. array[index + 3] = this.w;
  3703. return this;
  3704. };
  3705. /**
  3706. * Adds the passed vector to the current Vector4.
  3707. * Returns the updated Vector4.
  3708. */
  3709. Vector4.prototype.addInPlace = function (otherVector) {
  3710. this.x += otherVector.x;
  3711. this.y += otherVector.y;
  3712. this.z += otherVector.z;
  3713. this.w += otherVector.w;
  3714. return this;
  3715. };
  3716. /**
  3717. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3718. */
  3719. Vector4.prototype.add = function (otherVector) {
  3720. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3721. };
  3722. /**
  3723. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3724. * Returns the current Vector4.
  3725. */
  3726. Vector4.prototype.addToRef = function (otherVector, result) {
  3727. result.x = this.x + otherVector.x;
  3728. result.y = this.y + otherVector.y;
  3729. result.z = this.z + otherVector.z;
  3730. result.w = this.w + otherVector.w;
  3731. return this;
  3732. };
  3733. /**
  3734. * Subtract in place the passed vector from the current Vector4.
  3735. * Returns the updated Vector4.
  3736. */
  3737. Vector4.prototype.subtractInPlace = function (otherVector) {
  3738. this.x -= otherVector.x;
  3739. this.y -= otherVector.y;
  3740. this.z -= otherVector.z;
  3741. this.w -= otherVector.w;
  3742. return this;
  3743. };
  3744. /**
  3745. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3746. */
  3747. Vector4.prototype.subtract = function (otherVector) {
  3748. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3749. };
  3750. /**
  3751. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3752. * Returns the current Vector4.
  3753. */
  3754. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3755. result.x = this.x - otherVector.x;
  3756. result.y = this.y - otherVector.y;
  3757. result.z = this.z - otherVector.z;
  3758. result.w = this.w - otherVector.w;
  3759. return this;
  3760. };
  3761. /**
  3762. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3763. */
  3764. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3765. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3766. };
  3767. /**
  3768. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3769. * Returns the current Vector4.
  3770. */
  3771. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3772. result.x = this.x - x;
  3773. result.y = this.y - y;
  3774. result.z = this.z - z;
  3775. result.w = this.w - w;
  3776. return this;
  3777. };
  3778. /**
  3779. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3780. */
  3781. Vector4.prototype.negate = function () {
  3782. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3783. };
  3784. /**
  3785. * Multiplies the current Vector4 coordinates by scale (float).
  3786. * Returns the updated Vector4.
  3787. */
  3788. Vector4.prototype.scaleInPlace = function (scale) {
  3789. this.x *= scale;
  3790. this.y *= scale;
  3791. this.z *= scale;
  3792. this.w *= scale;
  3793. return this;
  3794. };
  3795. /**
  3796. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3797. */
  3798. Vector4.prototype.scale = function (scale) {
  3799. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3800. };
  3801. /**
  3802. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3803. * Returns the current Vector4.
  3804. */
  3805. Vector4.prototype.scaleToRef = function (scale, result) {
  3806. result.x = this.x * scale;
  3807. result.y = this.y * scale;
  3808. result.z = this.z * scale;
  3809. result.w = this.w * scale;
  3810. return this;
  3811. };
  3812. /**
  3813. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3814. */
  3815. Vector4.prototype.equals = function (otherVector) {
  3816. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3817. };
  3818. /**
  3819. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3820. */
  3821. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3822. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3823. return otherVector
  3824. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3825. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3826. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3827. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3828. };
  3829. /**
  3830. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3831. */
  3832. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3833. return this.x === x && this.y === y && this.z === z && this.w === w;
  3834. };
  3835. /**
  3836. * Multiplies in place the current Vector4 by the passed one.
  3837. * Returns the updated Vector4.
  3838. */
  3839. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3840. this.x *= otherVector.x;
  3841. this.y *= otherVector.y;
  3842. this.z *= otherVector.z;
  3843. this.w *= otherVector.w;
  3844. return this;
  3845. };
  3846. /**
  3847. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3848. */
  3849. Vector4.prototype.multiply = function (otherVector) {
  3850. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3851. };
  3852. /**
  3853. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3854. * Returns the current Vector4.
  3855. */
  3856. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3857. result.x = this.x * otherVector.x;
  3858. result.y = this.y * otherVector.y;
  3859. result.z = this.z * otherVector.z;
  3860. result.w = this.w * otherVector.w;
  3861. return this;
  3862. };
  3863. /**
  3864. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3865. */
  3866. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3867. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3868. };
  3869. /**
  3870. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3871. */
  3872. Vector4.prototype.divide = function (otherVector) {
  3873. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3874. };
  3875. /**
  3876. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3877. * Returns the current Vector4.
  3878. */
  3879. Vector4.prototype.divideToRef = function (otherVector, result) {
  3880. result.x = this.x / otherVector.x;
  3881. result.y = this.y / otherVector.y;
  3882. result.z = this.z / otherVector.z;
  3883. result.w = this.w / otherVector.w;
  3884. return this;
  3885. };
  3886. /**
  3887. * Divides the current Vector3 coordinates by the passed ones.
  3888. * @returns the updated Vector3.
  3889. */
  3890. Vector4.prototype.divideInPlace = function (otherVector) {
  3891. return this.divideToRef(otherVector, this);
  3892. };
  3893. /**
  3894. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3895. * @param other defines the second operand
  3896. * @returns the current updated Vector4
  3897. */
  3898. Vector4.prototype.minimizeInPlace = function (other) {
  3899. if (other.x < this.x)
  3900. this.x = other.x;
  3901. if (other.y < this.y)
  3902. this.y = other.y;
  3903. if (other.z < this.z)
  3904. this.z = other.z;
  3905. if (other.w < this.w)
  3906. this.w = other.w;
  3907. return this;
  3908. };
  3909. /**
  3910. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3911. * @param other defines the second operand
  3912. * @returns the current updated Vector4
  3913. */
  3914. Vector4.prototype.maximizeInPlace = function (other) {
  3915. if (other.x > this.x)
  3916. this.x = other.x;
  3917. if (other.y > this.y)
  3918. this.y = other.y;
  3919. if (other.z > this.z)
  3920. this.z = other.z;
  3921. if (other.w > this.w)
  3922. this.w = other.w;
  3923. return this;
  3924. };
  3925. // Properties
  3926. /**
  3927. * Returns the Vector4 length (float).
  3928. */
  3929. Vector4.prototype.length = function () {
  3930. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3931. };
  3932. /**
  3933. * Returns the Vector4 squared length (float).
  3934. */
  3935. Vector4.prototype.lengthSquared = function () {
  3936. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3937. };
  3938. // Methods
  3939. /**
  3940. * Normalizes in place the Vector4.
  3941. * Returns the updated Vector4.
  3942. */
  3943. Vector4.prototype.normalize = function () {
  3944. var len = this.length();
  3945. if (len === 0)
  3946. return this;
  3947. var num = 1.0 / len;
  3948. this.x *= num;
  3949. this.y *= num;
  3950. this.z *= num;
  3951. this.w *= num;
  3952. return this;
  3953. };
  3954. /**
  3955. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3956. */
  3957. Vector4.prototype.toVector3 = function () {
  3958. return new Vector3(this.x, this.y, this.z);
  3959. };
  3960. /**
  3961. * Returns a new Vector4 copied from the current one.
  3962. */
  3963. Vector4.prototype.clone = function () {
  3964. return new Vector4(this.x, this.y, this.z, this.w);
  3965. };
  3966. /**
  3967. * Updates the current Vector4 with the passed one coordinates.
  3968. * Returns the updated Vector4.
  3969. */
  3970. Vector4.prototype.copyFrom = function (source) {
  3971. this.x = source.x;
  3972. this.y = source.y;
  3973. this.z = source.z;
  3974. this.w = source.w;
  3975. return this;
  3976. };
  3977. /**
  3978. * Updates the current Vector4 coordinates with the passed floats.
  3979. * Returns the updated Vector4.
  3980. */
  3981. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3982. this.x = x;
  3983. this.y = y;
  3984. this.z = z;
  3985. this.w = w;
  3986. return this;
  3987. };
  3988. /**
  3989. * Updates the current Vector4 coordinates with the passed floats.
  3990. * Returns the updated Vector4.
  3991. */
  3992. Vector4.prototype.set = function (x, y, z, w) {
  3993. return this.copyFromFloats(x, y, z, w);
  3994. };
  3995. // Statics
  3996. /**
  3997. * Returns a new Vector4 set from the starting index of the passed array.
  3998. */
  3999. Vector4.FromArray = function (array, offset) {
  4000. if (!offset) {
  4001. offset = 0;
  4002. }
  4003. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4004. };
  4005. /**
  4006. * Updates the passed vector "result" from the starting index of the passed array.
  4007. */
  4008. Vector4.FromArrayToRef = function (array, offset, result) {
  4009. result.x = array[offset];
  4010. result.y = array[offset + 1];
  4011. result.z = array[offset + 2];
  4012. result.w = array[offset + 3];
  4013. };
  4014. /**
  4015. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4016. */
  4017. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4018. Vector4.FromArrayToRef(array, offset, result);
  4019. };
  4020. /**
  4021. * Updates the passed vector "result" coordinates from the passed floats.
  4022. */
  4023. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4024. result.x = x;
  4025. result.y = y;
  4026. result.z = z;
  4027. result.w = w;
  4028. };
  4029. /**
  4030. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4031. */
  4032. Vector4.Zero = function () {
  4033. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4034. };
  4035. /**
  4036. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4037. */
  4038. Vector4.One = function () {
  4039. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4040. };
  4041. /**
  4042. * Returns a new normalized Vector4 from the passed one.
  4043. */
  4044. Vector4.Normalize = function (vector) {
  4045. var result = Vector4.Zero();
  4046. Vector4.NormalizeToRef(vector, result);
  4047. return result;
  4048. };
  4049. /**
  4050. * Updates the passed vector "result" from the normalization of the passed one.
  4051. */
  4052. Vector4.NormalizeToRef = function (vector, result) {
  4053. result.copyFrom(vector);
  4054. result.normalize();
  4055. };
  4056. Vector4.Minimize = function (left, right) {
  4057. var min = left.clone();
  4058. min.minimizeInPlace(right);
  4059. return min;
  4060. };
  4061. Vector4.Maximize = function (left, right) {
  4062. var max = left.clone();
  4063. max.maximizeInPlace(right);
  4064. return max;
  4065. };
  4066. /**
  4067. * Returns the distance (float) between the vectors "value1" and "value2".
  4068. */
  4069. Vector4.Distance = function (value1, value2) {
  4070. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4071. };
  4072. /**
  4073. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4074. */
  4075. Vector4.DistanceSquared = function (value1, value2) {
  4076. var x = value1.x - value2.x;
  4077. var y = value1.y - value2.y;
  4078. var z = value1.z - value2.z;
  4079. var w = value1.w - value2.w;
  4080. return (x * x) + (y * y) + (z * z) + (w * w);
  4081. };
  4082. /**
  4083. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4084. */
  4085. Vector4.Center = function (value1, value2) {
  4086. var center = value1.add(value2);
  4087. center.scaleInPlace(0.5);
  4088. return center;
  4089. };
  4090. /**
  4091. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4092. * This methods computes transformed normalized direction vectors only.
  4093. */
  4094. Vector4.TransformNormal = function (vector, transformation) {
  4095. var result = Vector4.Zero();
  4096. Vector4.TransformNormalToRef(vector, transformation, result);
  4097. return result;
  4098. };
  4099. /**
  4100. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4101. * This methods computes transformed normalized direction vectors only.
  4102. */
  4103. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4104. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4105. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4106. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4107. result.x = x;
  4108. result.y = y;
  4109. result.z = z;
  4110. result.w = vector.w;
  4111. };
  4112. /**
  4113. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4114. * This methods computes transformed normalized direction vectors only.
  4115. */
  4116. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4117. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4118. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4119. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4120. result.w = w;
  4121. };
  4122. return Vector4;
  4123. }());
  4124. BABYLON.Vector4 = Vector4;
  4125. var Size = /** @class */ (function () {
  4126. /**
  4127. * Creates a Size object from the passed width and height (floats).
  4128. */
  4129. function Size(width, height) {
  4130. this.width = width;
  4131. this.height = height;
  4132. }
  4133. // Returns a string with the Size width and height.
  4134. Size.prototype.toString = function () {
  4135. return "{W: " + this.width + ", H: " + this.height + "}";
  4136. };
  4137. /**
  4138. * Returns the string "Size"
  4139. */
  4140. Size.prototype.getClassName = function () {
  4141. return "Size";
  4142. };
  4143. /**
  4144. * Returns the Size hash code.
  4145. */
  4146. Size.prototype.getHashCode = function () {
  4147. var hash = this.width || 0;
  4148. hash = (hash * 397) ^ (this.height || 0);
  4149. return hash;
  4150. };
  4151. /**
  4152. * Updates the current size from the passed one.
  4153. * Returns the updated Size.
  4154. */
  4155. Size.prototype.copyFrom = function (src) {
  4156. this.width = src.width;
  4157. this.height = src.height;
  4158. };
  4159. /**
  4160. * Updates in place the current Size from the passed floats.
  4161. * Returns the updated Size.
  4162. */
  4163. Size.prototype.copyFromFloats = function (width, height) {
  4164. this.width = width;
  4165. this.height = height;
  4166. return this;
  4167. };
  4168. /**
  4169. * Updates in place the current Size from the passed floats.
  4170. * Returns the updated Size.
  4171. */
  4172. Size.prototype.set = function (width, height) {
  4173. return this.copyFromFloats(width, height);
  4174. };
  4175. /**
  4176. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4177. */
  4178. Size.prototype.multiplyByFloats = function (w, h) {
  4179. return new Size(this.width * w, this.height * h);
  4180. };
  4181. /**
  4182. * Returns a new Size copied from the passed one.
  4183. */
  4184. Size.prototype.clone = function () {
  4185. return new Size(this.width, this.height);
  4186. };
  4187. /**
  4188. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4189. */
  4190. Size.prototype.equals = function (other) {
  4191. if (!other) {
  4192. return false;
  4193. }
  4194. return (this.width === other.width) && (this.height === other.height);
  4195. };
  4196. Object.defineProperty(Size.prototype, "surface", {
  4197. /**
  4198. * Returns the surface of the Size : width * height (float).
  4199. */
  4200. get: function () {
  4201. return this.width * this.height;
  4202. },
  4203. enumerable: true,
  4204. configurable: true
  4205. });
  4206. /**
  4207. * Returns a new Size set to (0.0, 0.0)
  4208. */
  4209. Size.Zero = function () {
  4210. return new Size(0.0, 0.0);
  4211. };
  4212. /**
  4213. * Returns a new Size set as the addition result of the current Size and the passed one.
  4214. */
  4215. Size.prototype.add = function (otherSize) {
  4216. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4217. return r;
  4218. };
  4219. /**
  4220. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4221. */
  4222. Size.prototype.subtract = function (otherSize) {
  4223. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4224. return r;
  4225. };
  4226. /**
  4227. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4228. */
  4229. Size.Lerp = function (start, end, amount) {
  4230. var w = start.width + ((end.width - start.width) * amount);
  4231. var h = start.height + ((end.height - start.height) * amount);
  4232. return new Size(w, h);
  4233. };
  4234. return Size;
  4235. }());
  4236. BABYLON.Size = Size;
  4237. var Quaternion = /** @class */ (function () {
  4238. /**
  4239. * Creates a new Quaternion from the passed floats.
  4240. */
  4241. function Quaternion(x, y, z, w) {
  4242. if (x === void 0) { x = 0.0; }
  4243. if (y === void 0) { y = 0.0; }
  4244. if (z === void 0) { z = 0.0; }
  4245. if (w === void 0) { w = 1.0; }
  4246. this.x = x;
  4247. this.y = y;
  4248. this.z = z;
  4249. this.w = w;
  4250. }
  4251. /**
  4252. * Returns a string with the Quaternion coordinates.
  4253. */
  4254. Quaternion.prototype.toString = function () {
  4255. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4256. };
  4257. /**
  4258. * Returns the string "Quaternion".
  4259. */
  4260. Quaternion.prototype.getClassName = function () {
  4261. return "Quaternion";
  4262. };
  4263. /**
  4264. * Returns the Quaternion hash code.
  4265. */
  4266. Quaternion.prototype.getHashCode = function () {
  4267. var hash = this.x || 0;
  4268. hash = (hash * 397) ^ (this.y || 0);
  4269. hash = (hash * 397) ^ (this.z || 0);
  4270. hash = (hash * 397) ^ (this.w || 0);
  4271. return hash;
  4272. };
  4273. /**
  4274. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4275. */
  4276. Quaternion.prototype.asArray = function () {
  4277. return [this.x, this.y, this.z, this.w];
  4278. };
  4279. /**
  4280. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4281. */
  4282. Quaternion.prototype.equals = function (otherQuaternion) {
  4283. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4284. };
  4285. /**
  4286. * Returns a new Quaternion copied from the current one.
  4287. */
  4288. Quaternion.prototype.clone = function () {
  4289. return new Quaternion(this.x, this.y, this.z, this.w);
  4290. };
  4291. /**
  4292. * Updates the current Quaternion from the passed one coordinates.
  4293. * Returns the updated Quaterion.
  4294. */
  4295. Quaternion.prototype.copyFrom = function (other) {
  4296. this.x = other.x;
  4297. this.y = other.y;
  4298. this.z = other.z;
  4299. this.w = other.w;
  4300. return this;
  4301. };
  4302. /**
  4303. * Updates the current Quaternion from the passed float coordinates.
  4304. * Returns the updated Quaterion.
  4305. */
  4306. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4307. this.x = x;
  4308. this.y = y;
  4309. this.z = z;
  4310. this.w = w;
  4311. return this;
  4312. };
  4313. /**
  4314. * Updates the current Quaternion from the passed float coordinates.
  4315. * Returns the updated Quaterion.
  4316. */
  4317. Quaternion.prototype.set = function (x, y, z, w) {
  4318. return this.copyFromFloats(x, y, z, w);
  4319. };
  4320. /**
  4321. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4322. */
  4323. Quaternion.prototype.add = function (other) {
  4324. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4325. };
  4326. /**
  4327. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4328. */
  4329. Quaternion.prototype.subtract = function (other) {
  4330. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4331. };
  4332. /**
  4333. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4334. */
  4335. Quaternion.prototype.scale = function (value) {
  4336. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4337. };
  4338. /**
  4339. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4340. */
  4341. Quaternion.prototype.multiply = function (q1) {
  4342. var result = new Quaternion(0, 0, 0, 1.0);
  4343. this.multiplyToRef(q1, result);
  4344. return result;
  4345. };
  4346. /**
  4347. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4348. * Returns the current Quaternion.
  4349. */
  4350. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4351. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4352. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4353. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4354. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4355. result.copyFromFloats(x, y, z, w);
  4356. return this;
  4357. };
  4358. /**
  4359. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4360. * Returns the updated Quaternion.
  4361. */
  4362. Quaternion.prototype.multiplyInPlace = function (q1) {
  4363. this.multiplyToRef(q1, this);
  4364. return this;
  4365. };
  4366. /**
  4367. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4368. * Returns the current Quaternion.
  4369. */
  4370. Quaternion.prototype.conjugateToRef = function (ref) {
  4371. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4372. return this;
  4373. };
  4374. /**
  4375. * Conjugates in place the current Quaternion.
  4376. * Returns the updated Quaternion.
  4377. */
  4378. Quaternion.prototype.conjugateInPlace = function () {
  4379. this.x *= -1;
  4380. this.y *= -1;
  4381. this.z *= -1;
  4382. return this;
  4383. };
  4384. /**
  4385. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4386. */
  4387. Quaternion.prototype.conjugate = function () {
  4388. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4389. return result;
  4390. };
  4391. /**
  4392. * Returns the Quaternion length (float).
  4393. */
  4394. Quaternion.prototype.length = function () {
  4395. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4396. };
  4397. /**
  4398. * Normalize in place the current Quaternion.
  4399. * Returns the updated Quaternion.
  4400. */
  4401. Quaternion.prototype.normalize = function () {
  4402. var length = 1.0 / this.length();
  4403. this.x *= length;
  4404. this.y *= length;
  4405. this.z *= length;
  4406. this.w *= length;
  4407. return this;
  4408. };
  4409. /**
  4410. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4411. */
  4412. Quaternion.prototype.toEulerAngles = function (order) {
  4413. if (order === void 0) { order = "YZX"; }
  4414. var result = Vector3.Zero();
  4415. this.toEulerAnglesToRef(result, order);
  4416. return result;
  4417. };
  4418. /**
  4419. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4420. * Returns the current Quaternion.
  4421. */
  4422. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4423. if (order === void 0) { order = "YZX"; }
  4424. var qz = this.z;
  4425. var qx = this.x;
  4426. var qy = this.y;
  4427. var qw = this.w;
  4428. var sqw = qw * qw;
  4429. var sqz = qz * qz;
  4430. var sqx = qx * qx;
  4431. var sqy = qy * qy;
  4432. var zAxisY = qy * qz - qx * qw;
  4433. var limit = .4999999;
  4434. if (zAxisY < -limit) {
  4435. result.y = 2 * Math.atan2(qy, qw);
  4436. result.x = Math.PI / 2;
  4437. result.z = 0;
  4438. }
  4439. else if (zAxisY > limit) {
  4440. result.y = 2 * Math.atan2(qy, qw);
  4441. result.x = -Math.PI / 2;
  4442. result.z = 0;
  4443. }
  4444. else {
  4445. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4446. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4447. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4448. }
  4449. return this;
  4450. };
  4451. /**
  4452. * Updates the passed rotation matrix with the current Quaternion values.
  4453. * Returns the current Quaternion.
  4454. */
  4455. Quaternion.prototype.toRotationMatrix = function (result) {
  4456. var xx = this.x * this.x;
  4457. var yy = this.y * this.y;
  4458. var zz = this.z * this.z;
  4459. var xy = this.x * this.y;
  4460. var zw = this.z * this.w;
  4461. var zx = this.z * this.x;
  4462. var yw = this.y * this.w;
  4463. var yz = this.y * this.z;
  4464. var xw = this.x * this.w;
  4465. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4466. result.m[1] = 2.0 * (xy + zw);
  4467. result.m[2] = 2.0 * (zx - yw);
  4468. result.m[3] = 0;
  4469. result.m[4] = 2.0 * (xy - zw);
  4470. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4471. result.m[6] = 2.0 * (yz + xw);
  4472. result.m[7] = 0;
  4473. result.m[8] = 2.0 * (zx + yw);
  4474. result.m[9] = 2.0 * (yz - xw);
  4475. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4476. result.m[11] = 0;
  4477. result.m[12] = 0;
  4478. result.m[13] = 0;
  4479. result.m[14] = 0;
  4480. result.m[15] = 1.0;
  4481. result._markAsUpdated();
  4482. return this;
  4483. };
  4484. /**
  4485. * Updates the current Quaternion from the passed rotation matrix values.
  4486. * Returns the updated Quaternion.
  4487. */
  4488. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4489. Quaternion.FromRotationMatrixToRef(matrix, this);
  4490. return this;
  4491. };
  4492. // Statics
  4493. /**
  4494. * Returns a new Quaternion set from the passed rotation matrix values.
  4495. */
  4496. Quaternion.FromRotationMatrix = function (matrix) {
  4497. var result = new Quaternion();
  4498. Quaternion.FromRotationMatrixToRef(matrix, result);
  4499. return result;
  4500. };
  4501. /**
  4502. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4503. */
  4504. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4505. var data = matrix.m;
  4506. var m11 = data[0], m12 = data[4], m13 = data[8];
  4507. var m21 = data[1], m22 = data[5], m23 = data[9];
  4508. var m31 = data[2], m32 = data[6], m33 = data[10];
  4509. var trace = m11 + m22 + m33;
  4510. var s;
  4511. if (trace > 0) {
  4512. s = 0.5 / Math.sqrt(trace + 1.0);
  4513. result.w = 0.25 / s;
  4514. result.x = (m32 - m23) * s;
  4515. result.y = (m13 - m31) * s;
  4516. result.z = (m21 - m12) * s;
  4517. }
  4518. else if (m11 > m22 && m11 > m33) {
  4519. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4520. result.w = (m32 - m23) / s;
  4521. result.x = 0.25 * s;
  4522. result.y = (m12 + m21) / s;
  4523. result.z = (m13 + m31) / s;
  4524. }
  4525. else if (m22 > m33) {
  4526. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4527. result.w = (m13 - m31) / s;
  4528. result.x = (m12 + m21) / s;
  4529. result.y = 0.25 * s;
  4530. result.z = (m23 + m32) / s;
  4531. }
  4532. else {
  4533. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4534. result.w = (m21 - m12) / s;
  4535. result.x = (m13 + m31) / s;
  4536. result.y = (m23 + m32) / s;
  4537. result.z = 0.25 * s;
  4538. }
  4539. };
  4540. /**
  4541. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4542. */
  4543. Quaternion.Zero = function () {
  4544. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4545. };
  4546. /**
  4547. * Returns a new Quaternion as the inverted current Quaternion.
  4548. */
  4549. Quaternion.Inverse = function (q) {
  4550. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4551. };
  4552. /**
  4553. * Returns the identity Quaternion.
  4554. */
  4555. Quaternion.Identity = function () {
  4556. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4557. };
  4558. Quaternion.IsIdentity = function (quaternion) {
  4559. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4560. };
  4561. /**
  4562. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4563. */
  4564. Quaternion.RotationAxis = function (axis, angle) {
  4565. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4566. };
  4567. /**
  4568. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4569. */
  4570. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4571. var sin = Math.sin(angle / 2);
  4572. axis.normalize();
  4573. result.w = Math.cos(angle / 2);
  4574. result.x = axis.x * sin;
  4575. result.y = axis.y * sin;
  4576. result.z = axis.z * sin;
  4577. return result;
  4578. };
  4579. /**
  4580. * Retuns a new Quaternion set from the starting index of the passed array.
  4581. */
  4582. Quaternion.FromArray = function (array, offset) {
  4583. if (!offset) {
  4584. offset = 0;
  4585. }
  4586. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4587. };
  4588. /**
  4589. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4590. */
  4591. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4592. var q = new Quaternion();
  4593. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4594. return q;
  4595. };
  4596. /**
  4597. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4598. */
  4599. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4600. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4601. var halfRoll = roll * 0.5;
  4602. var halfPitch = pitch * 0.5;
  4603. var halfYaw = yaw * 0.5;
  4604. var sinRoll = Math.sin(halfRoll);
  4605. var cosRoll = Math.cos(halfRoll);
  4606. var sinPitch = Math.sin(halfPitch);
  4607. var cosPitch = Math.cos(halfPitch);
  4608. var sinYaw = Math.sin(halfYaw);
  4609. var cosYaw = Math.cos(halfYaw);
  4610. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4611. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4612. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4613. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4614. };
  4615. /**
  4616. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4617. */
  4618. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4619. var result = new Quaternion();
  4620. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4621. return result;
  4622. };
  4623. /**
  4624. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4625. */
  4626. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4627. // Produces a quaternion from Euler angles in the z-x-z orientation
  4628. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4629. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4630. var halfBeta = beta * 0.5;
  4631. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4632. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4633. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4634. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4635. };
  4636. /**
  4637. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4638. * cf to Vector3.RotationFromAxis() documentation.
  4639. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4640. */
  4641. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4642. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4643. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4644. return quat;
  4645. };
  4646. /**
  4647. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4648. * cf to Vector3.RotationFromAxis() documentation.
  4649. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4650. */
  4651. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4652. var rotMat = MathTmp.Matrix[0];
  4653. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4654. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4655. };
  4656. Quaternion.Slerp = function (left, right, amount) {
  4657. var result = Quaternion.Identity();
  4658. Quaternion.SlerpToRef(left, right, amount, result);
  4659. return result;
  4660. };
  4661. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4662. var num2;
  4663. var num3;
  4664. var num = amount;
  4665. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4666. var flag = false;
  4667. if (num4 < 0) {
  4668. flag = true;
  4669. num4 = -num4;
  4670. }
  4671. if (num4 > 0.999999) {
  4672. num3 = 1 - num;
  4673. num2 = flag ? -num : num;
  4674. }
  4675. else {
  4676. var num5 = Math.acos(num4);
  4677. var num6 = (1.0 / Math.sin(num5));
  4678. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4679. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4680. }
  4681. result.x = (num3 * left.x) + (num2 * right.x);
  4682. result.y = (num3 * left.y) + (num2 * right.y);
  4683. result.z = (num3 * left.z) + (num2 * right.z);
  4684. result.w = (num3 * left.w) + (num2 * right.w);
  4685. };
  4686. /**
  4687. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4688. */
  4689. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4690. var squared = amount * amount;
  4691. var cubed = amount * squared;
  4692. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4693. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4694. var part3 = (cubed - (2.0 * squared)) + amount;
  4695. var part4 = cubed - squared;
  4696. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4697. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4698. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4699. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4700. return new Quaternion(x, y, z, w);
  4701. };
  4702. return Quaternion;
  4703. }());
  4704. BABYLON.Quaternion = Quaternion;
  4705. var Matrix = /** @class */ (function () {
  4706. function Matrix() {
  4707. this._isIdentity = false;
  4708. this._isIdentityDirty = true;
  4709. this.m = new Float32Array(16);
  4710. this._markAsUpdated();
  4711. }
  4712. Matrix.prototype._markAsUpdated = function () {
  4713. this.updateFlag = Matrix._updateFlagSeed++;
  4714. this._isIdentityDirty = true;
  4715. };
  4716. // Properties
  4717. /**
  4718. * Boolean : True is the matrix is the identity matrix
  4719. */
  4720. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4721. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4722. if (this._isIdentityDirty) {
  4723. this._isIdentityDirty = false;
  4724. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4725. this._isIdentity = false;
  4726. }
  4727. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4728. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4729. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4730. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4731. this._isIdentity = false;
  4732. }
  4733. else {
  4734. this._isIdentity = true;
  4735. }
  4736. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4737. this._isIdentity = false;
  4738. }
  4739. }
  4740. return this._isIdentity;
  4741. };
  4742. /**
  4743. * Returns the matrix determinant (float).
  4744. */
  4745. Matrix.prototype.determinant = function () {
  4746. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4747. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4748. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4749. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4750. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4751. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4752. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4753. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4754. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4755. };
  4756. // Methods
  4757. /**
  4758. * Returns the matrix underlying array.
  4759. */
  4760. Matrix.prototype.toArray = function () {
  4761. return this.m;
  4762. };
  4763. /**
  4764. * Returns the matrix underlying array.
  4765. */
  4766. Matrix.prototype.asArray = function () {
  4767. return this.toArray();
  4768. };
  4769. /**
  4770. * Inverts in place the Matrix.
  4771. * Returns the Matrix inverted.
  4772. */
  4773. Matrix.prototype.invert = function () {
  4774. this.invertToRef(this);
  4775. return this;
  4776. };
  4777. /**
  4778. * Sets all the matrix elements to zero.
  4779. * Returns the Matrix.
  4780. */
  4781. Matrix.prototype.reset = function () {
  4782. for (var index = 0; index < 16; index++) {
  4783. this.m[index] = 0.0;
  4784. }
  4785. this._markAsUpdated();
  4786. return this;
  4787. };
  4788. /**
  4789. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4790. */
  4791. Matrix.prototype.add = function (other) {
  4792. var result = new Matrix();
  4793. this.addToRef(other, result);
  4794. return result;
  4795. };
  4796. /**
  4797. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4798. * Returns the Matrix.
  4799. */
  4800. Matrix.prototype.addToRef = function (other, result) {
  4801. for (var index = 0; index < 16; index++) {
  4802. result.m[index] = this.m[index] + other.m[index];
  4803. }
  4804. result._markAsUpdated();
  4805. return this;
  4806. };
  4807. /**
  4808. * Adds in place the passed matrix to the current Matrix.
  4809. * Returns the updated Matrix.
  4810. */
  4811. Matrix.prototype.addToSelf = function (other) {
  4812. for (var index = 0; index < 16; index++) {
  4813. this.m[index] += other.m[index];
  4814. }
  4815. this._markAsUpdated();
  4816. return this;
  4817. };
  4818. /**
  4819. * Sets the passed matrix with the current inverted Matrix.
  4820. * Returns the unmodified current Matrix.
  4821. */
  4822. Matrix.prototype.invertToRef = function (other) {
  4823. var l1 = this.m[0];
  4824. var l2 = this.m[1];
  4825. var l3 = this.m[2];
  4826. var l4 = this.m[3];
  4827. var l5 = this.m[4];
  4828. var l6 = this.m[5];
  4829. var l7 = this.m[6];
  4830. var l8 = this.m[7];
  4831. var l9 = this.m[8];
  4832. var l10 = this.m[9];
  4833. var l11 = this.m[10];
  4834. var l12 = this.m[11];
  4835. var l13 = this.m[12];
  4836. var l14 = this.m[13];
  4837. var l15 = this.m[14];
  4838. var l16 = this.m[15];
  4839. var l17 = (l11 * l16) - (l12 * l15);
  4840. var l18 = (l10 * l16) - (l12 * l14);
  4841. var l19 = (l10 * l15) - (l11 * l14);
  4842. var l20 = (l9 * l16) - (l12 * l13);
  4843. var l21 = (l9 * l15) - (l11 * l13);
  4844. var l22 = (l9 * l14) - (l10 * l13);
  4845. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4846. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4847. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4848. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4849. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4850. var l28 = (l7 * l16) - (l8 * l15);
  4851. var l29 = (l6 * l16) - (l8 * l14);
  4852. var l30 = (l6 * l15) - (l7 * l14);
  4853. var l31 = (l5 * l16) - (l8 * l13);
  4854. var l32 = (l5 * l15) - (l7 * l13);
  4855. var l33 = (l5 * l14) - (l6 * l13);
  4856. var l34 = (l7 * l12) - (l8 * l11);
  4857. var l35 = (l6 * l12) - (l8 * l10);
  4858. var l36 = (l6 * l11) - (l7 * l10);
  4859. var l37 = (l5 * l12) - (l8 * l9);
  4860. var l38 = (l5 * l11) - (l7 * l9);
  4861. var l39 = (l5 * l10) - (l6 * l9);
  4862. other.m[0] = l23 * l27;
  4863. other.m[4] = l24 * l27;
  4864. other.m[8] = l25 * l27;
  4865. other.m[12] = l26 * l27;
  4866. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4867. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4868. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4869. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4870. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4871. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4872. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4873. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4874. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4875. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4876. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4877. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4878. other._markAsUpdated();
  4879. return this;
  4880. };
  4881. /**
  4882. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4883. * Returns the updated Matrix.
  4884. */
  4885. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4886. this.m[12] = x;
  4887. this.m[13] = y;
  4888. this.m[14] = z;
  4889. this._markAsUpdated();
  4890. return this;
  4891. };
  4892. /**
  4893. * Inserts the translation vector in the current Matrix.
  4894. * Returns the updated Matrix.
  4895. */
  4896. Matrix.prototype.setTranslation = function (vector3) {
  4897. this.m[12] = vector3.x;
  4898. this.m[13] = vector3.y;
  4899. this.m[14] = vector3.z;
  4900. this._markAsUpdated();
  4901. return this;
  4902. };
  4903. /**
  4904. * Returns a new Vector3 as the extracted translation from the Matrix.
  4905. */
  4906. Matrix.prototype.getTranslation = function () {
  4907. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4908. };
  4909. /**
  4910. * Fill a Vector3 with the extracted translation from the Matrix.
  4911. */
  4912. Matrix.prototype.getTranslationToRef = function (result) {
  4913. result.x = this.m[12];
  4914. result.y = this.m[13];
  4915. result.z = this.m[14];
  4916. return this;
  4917. };
  4918. /**
  4919. * Remove rotation and scaling part from the Matrix.
  4920. * Returns the updated Matrix.
  4921. */
  4922. Matrix.prototype.removeRotationAndScaling = function () {
  4923. this.setRowFromFloats(0, 1, 0, 0, 0);
  4924. this.setRowFromFloats(1, 0, 1, 0, 0);
  4925. this.setRowFromFloats(2, 0, 0, 1, 0);
  4926. return this;
  4927. };
  4928. /**
  4929. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4930. */
  4931. Matrix.prototype.multiply = function (other) {
  4932. var result = new Matrix();
  4933. this.multiplyToRef(other, result);
  4934. return result;
  4935. };
  4936. /**
  4937. * Updates the current Matrix from the passed one values.
  4938. * Returns the updated Matrix.
  4939. */
  4940. Matrix.prototype.copyFrom = function (other) {
  4941. for (var index = 0; index < 16; index++) {
  4942. this.m[index] = other.m[index];
  4943. }
  4944. this._markAsUpdated();
  4945. return this;
  4946. };
  4947. /**
  4948. * Populates the passed array from the starting index with the Matrix values.
  4949. * Returns the Matrix.
  4950. */
  4951. Matrix.prototype.copyToArray = function (array, offset) {
  4952. if (offset === void 0) { offset = 0; }
  4953. for (var index = 0; index < 16; index++) {
  4954. array[offset + index] = this.m[index];
  4955. }
  4956. return this;
  4957. };
  4958. /**
  4959. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4960. */
  4961. Matrix.prototype.multiplyToRef = function (other, result) {
  4962. this.multiplyToArray(other, result.m, 0);
  4963. result._markAsUpdated();
  4964. return this;
  4965. };
  4966. /**
  4967. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4968. */
  4969. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4970. var tm0 = this.m[0];
  4971. var tm1 = this.m[1];
  4972. var tm2 = this.m[2];
  4973. var tm3 = this.m[3];
  4974. var tm4 = this.m[4];
  4975. var tm5 = this.m[5];
  4976. var tm6 = this.m[6];
  4977. var tm7 = this.m[7];
  4978. var tm8 = this.m[8];
  4979. var tm9 = this.m[9];
  4980. var tm10 = this.m[10];
  4981. var tm11 = this.m[11];
  4982. var tm12 = this.m[12];
  4983. var tm13 = this.m[13];
  4984. var tm14 = this.m[14];
  4985. var tm15 = this.m[15];
  4986. var om0 = other.m[0];
  4987. var om1 = other.m[1];
  4988. var om2 = other.m[2];
  4989. var om3 = other.m[3];
  4990. var om4 = other.m[4];
  4991. var om5 = other.m[5];
  4992. var om6 = other.m[6];
  4993. var om7 = other.m[7];
  4994. var om8 = other.m[8];
  4995. var om9 = other.m[9];
  4996. var om10 = other.m[10];
  4997. var om11 = other.m[11];
  4998. var om12 = other.m[12];
  4999. var om13 = other.m[13];
  5000. var om14 = other.m[14];
  5001. var om15 = other.m[15];
  5002. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5003. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5004. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5005. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5006. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5007. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5008. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5009. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5010. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5011. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5012. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5013. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5014. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5015. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5016. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5017. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5018. return this;
  5019. };
  5020. /**
  5021. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5022. */
  5023. Matrix.prototype.equals = function (value) {
  5024. return value &&
  5025. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5026. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5027. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5028. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5029. };
  5030. /**
  5031. * Returns a new Matrix from the current Matrix.
  5032. */
  5033. Matrix.prototype.clone = function () {
  5034. 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]);
  5035. };
  5036. /**
  5037. * Returns the string "Matrix"
  5038. */
  5039. Matrix.prototype.getClassName = function () {
  5040. return "Matrix";
  5041. };
  5042. /**
  5043. * Returns the Matrix hash code.
  5044. */
  5045. Matrix.prototype.getHashCode = function () {
  5046. var hash = this.m[0] || 0;
  5047. for (var i = 1; i < 16; i++) {
  5048. hash = (hash * 397) ^ (this.m[i] || 0);
  5049. }
  5050. return hash;
  5051. };
  5052. /**
  5053. * Decomposes the current Matrix into :
  5054. * - a scale vector3 passed as a reference to update,
  5055. * - a rotation quaternion passed as a reference to update,
  5056. * - a translation vector3 passed as a reference to update.
  5057. * Returns the true if operation was successful.
  5058. */
  5059. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5060. translation.x = this.m[12];
  5061. translation.y = this.m[13];
  5062. translation.z = this.m[14];
  5063. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5064. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5065. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5066. if (this.determinant() <= 0) {
  5067. scale.y *= -1;
  5068. }
  5069. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5070. rotation.x = 0;
  5071. rotation.y = 0;
  5072. rotation.z = 0;
  5073. rotation.w = 1;
  5074. return false;
  5075. }
  5076. 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]);
  5077. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5078. return true;
  5079. };
  5080. /**
  5081. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5082. * @param ref matrix to store the result
  5083. */
  5084. Matrix.prototype.toNormalMatrix = function (ref) {
  5085. this.invertToRef(ref);
  5086. ref.transpose();
  5087. var m = ref.m;
  5088. 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);
  5089. };
  5090. /**
  5091. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5092. */
  5093. Matrix.prototype.getRotationMatrix = function () {
  5094. var result = Matrix.Identity();
  5095. this.getRotationMatrixToRef(result);
  5096. return result;
  5097. };
  5098. /**
  5099. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5100. * Returns the current Matrix.
  5101. */
  5102. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5103. var m = this.m;
  5104. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5105. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5106. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5107. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5108. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5109. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5110. 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);
  5111. return this;
  5112. };
  5113. // Statics
  5114. /**
  5115. * Returns a new Matrix set from the starting index of the passed array.
  5116. */
  5117. Matrix.FromArray = function (array, offset) {
  5118. var result = new Matrix();
  5119. if (!offset) {
  5120. offset = 0;
  5121. }
  5122. Matrix.FromArrayToRef(array, offset, result);
  5123. return result;
  5124. };
  5125. /**
  5126. * Sets the passed "result" matrix from the starting index of the passed array.
  5127. */
  5128. Matrix.FromArrayToRef = function (array, offset, result) {
  5129. for (var index = 0; index < 16; index++) {
  5130. result.m[index] = array[index + offset];
  5131. }
  5132. result._markAsUpdated();
  5133. };
  5134. /**
  5135. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5136. */
  5137. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5138. for (var index = 0; index < 16; index++) {
  5139. result.m[index] = array[index + offset] * scale;
  5140. }
  5141. result._markAsUpdated();
  5142. };
  5143. /**
  5144. * Sets the passed matrix "result" with the 16 passed floats.
  5145. */
  5146. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5147. result.m[0] = initialM11;
  5148. result.m[1] = initialM12;
  5149. result.m[2] = initialM13;
  5150. result.m[3] = initialM14;
  5151. result.m[4] = initialM21;
  5152. result.m[5] = initialM22;
  5153. result.m[6] = initialM23;
  5154. result.m[7] = initialM24;
  5155. result.m[8] = initialM31;
  5156. result.m[9] = initialM32;
  5157. result.m[10] = initialM33;
  5158. result.m[11] = initialM34;
  5159. result.m[12] = initialM41;
  5160. result.m[13] = initialM42;
  5161. result.m[14] = initialM43;
  5162. result.m[15] = initialM44;
  5163. result._markAsUpdated();
  5164. };
  5165. /**
  5166. * Returns the index-th row of the current matrix as a new Vector4.
  5167. */
  5168. Matrix.prototype.getRow = function (index) {
  5169. if (index < 0 || index > 3) {
  5170. return null;
  5171. }
  5172. var i = index * 4;
  5173. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5174. };
  5175. /**
  5176. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5177. * Returns the updated Matrix.
  5178. */
  5179. Matrix.prototype.setRow = function (index, row) {
  5180. if (index < 0 || index > 3) {
  5181. return this;
  5182. }
  5183. var i = index * 4;
  5184. this.m[i + 0] = row.x;
  5185. this.m[i + 1] = row.y;
  5186. this.m[i + 2] = row.z;
  5187. this.m[i + 3] = row.w;
  5188. this._markAsUpdated();
  5189. return this;
  5190. };
  5191. /**
  5192. * Compute the transpose of the matrix.
  5193. * Returns a new Matrix.
  5194. */
  5195. Matrix.prototype.transpose = function () {
  5196. return Matrix.Transpose(this);
  5197. };
  5198. /**
  5199. * Compute the transpose of the matrix.
  5200. * Returns the current matrix.
  5201. */
  5202. Matrix.prototype.transposeToRef = function (result) {
  5203. Matrix.TransposeToRef(this, result);
  5204. return this;
  5205. };
  5206. /**
  5207. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5208. * Returns the updated Matrix.
  5209. */
  5210. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5211. if (index < 0 || index > 3) {
  5212. return this;
  5213. }
  5214. var i = index * 4;
  5215. this.m[i + 0] = x;
  5216. this.m[i + 1] = y;
  5217. this.m[i + 2] = z;
  5218. this.m[i + 3] = w;
  5219. this._markAsUpdated();
  5220. return this;
  5221. };
  5222. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5223. /**
  5224. * Static identity matrix to be used as readonly matrix
  5225. * Must not be updated.
  5226. */
  5227. get: function () {
  5228. return Matrix._identityReadOnly;
  5229. },
  5230. enumerable: true,
  5231. configurable: true
  5232. });
  5233. /**
  5234. * Returns a new Matrix set from the 16 passed floats.
  5235. */
  5236. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5237. var result = new Matrix();
  5238. result.m[0] = initialM11;
  5239. result.m[1] = initialM12;
  5240. result.m[2] = initialM13;
  5241. result.m[3] = initialM14;
  5242. result.m[4] = initialM21;
  5243. result.m[5] = initialM22;
  5244. result.m[6] = initialM23;
  5245. result.m[7] = initialM24;
  5246. result.m[8] = initialM31;
  5247. result.m[9] = initialM32;
  5248. result.m[10] = initialM33;
  5249. result.m[11] = initialM34;
  5250. result.m[12] = initialM41;
  5251. result.m[13] = initialM42;
  5252. result.m[14] = initialM43;
  5253. result.m[15] = initialM44;
  5254. return result;
  5255. };
  5256. /**
  5257. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5258. */
  5259. Matrix.Compose = function (scale, rotation, translation) {
  5260. var result = Matrix.Identity();
  5261. Matrix.ComposeToRef(scale, rotation, translation, result);
  5262. return result;
  5263. };
  5264. /**
  5265. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5266. */
  5267. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5268. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5269. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5270. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5271. result.setTranslation(translation);
  5272. };
  5273. /**
  5274. * Returns a new indentity Matrix.
  5275. */
  5276. Matrix.Identity = function () {
  5277. 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);
  5278. };
  5279. /**
  5280. * Sets the passed "result" as an identity matrix.
  5281. */
  5282. Matrix.IdentityToRef = function (result) {
  5283. 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);
  5284. };
  5285. /**
  5286. * Returns a new zero Matrix.
  5287. */
  5288. Matrix.Zero = function () {
  5289. 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);
  5290. };
  5291. /**
  5292. * Returns a new rotation matrix for "angle" radians around the X axis.
  5293. */
  5294. Matrix.RotationX = function (angle) {
  5295. var result = new Matrix();
  5296. Matrix.RotationXToRef(angle, result);
  5297. return result;
  5298. };
  5299. /**
  5300. * Returns a new Matrix as the passed inverted one.
  5301. */
  5302. Matrix.Invert = function (source) {
  5303. var result = new Matrix();
  5304. source.invertToRef(result);
  5305. return result;
  5306. };
  5307. /**
  5308. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5309. */
  5310. Matrix.RotationXToRef = function (angle, result) {
  5311. var s = Math.sin(angle);
  5312. var c = Math.cos(angle);
  5313. result.m[0] = 1.0;
  5314. result.m[15] = 1.0;
  5315. result.m[5] = c;
  5316. result.m[10] = c;
  5317. result.m[9] = -s;
  5318. result.m[6] = s;
  5319. result.m[1] = 0.0;
  5320. result.m[2] = 0.0;
  5321. result.m[3] = 0.0;
  5322. result.m[4] = 0.0;
  5323. result.m[7] = 0.0;
  5324. result.m[8] = 0.0;
  5325. result.m[11] = 0.0;
  5326. result.m[12] = 0.0;
  5327. result.m[13] = 0.0;
  5328. result.m[14] = 0.0;
  5329. result._markAsUpdated();
  5330. };
  5331. /**
  5332. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5333. */
  5334. Matrix.RotationY = function (angle) {
  5335. var result = new Matrix();
  5336. Matrix.RotationYToRef(angle, result);
  5337. return result;
  5338. };
  5339. /**
  5340. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5341. */
  5342. Matrix.RotationYToRef = function (angle, result) {
  5343. var s = Math.sin(angle);
  5344. var c = Math.cos(angle);
  5345. result.m[5] = 1.0;
  5346. result.m[15] = 1.0;
  5347. result.m[0] = c;
  5348. result.m[2] = -s;
  5349. result.m[8] = s;
  5350. result.m[10] = c;
  5351. result.m[1] = 0.0;
  5352. result.m[3] = 0.0;
  5353. result.m[4] = 0.0;
  5354. result.m[6] = 0.0;
  5355. result.m[7] = 0.0;
  5356. result.m[9] = 0.0;
  5357. result.m[11] = 0.0;
  5358. result.m[12] = 0.0;
  5359. result.m[13] = 0.0;
  5360. result.m[14] = 0.0;
  5361. result._markAsUpdated();
  5362. };
  5363. /**
  5364. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5365. */
  5366. Matrix.RotationZ = function (angle) {
  5367. var result = new Matrix();
  5368. Matrix.RotationZToRef(angle, result);
  5369. return result;
  5370. };
  5371. /**
  5372. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5373. */
  5374. Matrix.RotationZToRef = function (angle, result) {
  5375. var s = Math.sin(angle);
  5376. var c = Math.cos(angle);
  5377. result.m[10] = 1.0;
  5378. result.m[15] = 1.0;
  5379. result.m[0] = c;
  5380. result.m[1] = s;
  5381. result.m[4] = -s;
  5382. result.m[5] = c;
  5383. result.m[2] = 0.0;
  5384. result.m[3] = 0.0;
  5385. result.m[6] = 0.0;
  5386. result.m[7] = 0.0;
  5387. result.m[8] = 0.0;
  5388. result.m[9] = 0.0;
  5389. result.m[11] = 0.0;
  5390. result.m[12] = 0.0;
  5391. result.m[13] = 0.0;
  5392. result.m[14] = 0.0;
  5393. result._markAsUpdated();
  5394. };
  5395. /**
  5396. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5397. */
  5398. Matrix.RotationAxis = function (axis, angle) {
  5399. var result = Matrix.Zero();
  5400. Matrix.RotationAxisToRef(axis, angle, result);
  5401. return result;
  5402. };
  5403. /**
  5404. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5405. */
  5406. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5407. var s = Math.sin(-angle);
  5408. var c = Math.cos(-angle);
  5409. var c1 = 1 - c;
  5410. axis.normalize();
  5411. result.m[0] = (axis.x * axis.x) * c1 + c;
  5412. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5413. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5414. result.m[3] = 0.0;
  5415. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5416. result.m[5] = (axis.y * axis.y) * c1 + c;
  5417. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5418. result.m[7] = 0.0;
  5419. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5420. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5421. result.m[10] = (axis.z * axis.z) * c1 + c;
  5422. result.m[11] = 0.0;
  5423. result.m[15] = 1.0;
  5424. result._markAsUpdated();
  5425. };
  5426. /**
  5427. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5428. */
  5429. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5430. var result = new Matrix();
  5431. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5432. return result;
  5433. };
  5434. /**
  5435. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5436. */
  5437. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5438. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5439. this._tempQuaternion.toRotationMatrix(result);
  5440. };
  5441. /**
  5442. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5443. */
  5444. Matrix.Scaling = function (x, y, z) {
  5445. var result = Matrix.Zero();
  5446. Matrix.ScalingToRef(x, y, z, result);
  5447. return result;
  5448. };
  5449. /**
  5450. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5451. */
  5452. Matrix.ScalingToRef = function (x, y, z, result) {
  5453. result.m[0] = x;
  5454. result.m[1] = 0.0;
  5455. result.m[2] = 0.0;
  5456. result.m[3] = 0.0;
  5457. result.m[4] = 0.0;
  5458. result.m[5] = y;
  5459. result.m[6] = 0.0;
  5460. result.m[7] = 0.0;
  5461. result.m[8] = 0.0;
  5462. result.m[9] = 0.0;
  5463. result.m[10] = z;
  5464. result.m[11] = 0.0;
  5465. result.m[12] = 0.0;
  5466. result.m[13] = 0.0;
  5467. result.m[14] = 0.0;
  5468. result.m[15] = 1.0;
  5469. result._markAsUpdated();
  5470. };
  5471. /**
  5472. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5473. */
  5474. Matrix.Translation = function (x, y, z) {
  5475. var result = Matrix.Identity();
  5476. Matrix.TranslationToRef(x, y, z, result);
  5477. return result;
  5478. };
  5479. /**
  5480. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5481. */
  5482. Matrix.TranslationToRef = function (x, y, z, result) {
  5483. 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);
  5484. };
  5485. /**
  5486. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5487. */
  5488. Matrix.Lerp = function (startValue, endValue, gradient) {
  5489. var result = Matrix.Zero();
  5490. for (var index = 0; index < 16; index++) {
  5491. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5492. }
  5493. result._markAsUpdated();
  5494. return result;
  5495. };
  5496. /**
  5497. * Returns a new Matrix whose values are computed by :
  5498. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5499. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5500. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5501. */
  5502. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5503. var startScale = new Vector3(0, 0, 0);
  5504. var startRotation = new Quaternion();
  5505. var startTranslation = new Vector3(0, 0, 0);
  5506. startValue.decompose(startScale, startRotation, startTranslation);
  5507. var endScale = new Vector3(0, 0, 0);
  5508. var endRotation = new Quaternion();
  5509. var endTranslation = new Vector3(0, 0, 0);
  5510. endValue.decompose(endScale, endRotation, endTranslation);
  5511. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5512. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5513. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5514. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5515. };
  5516. /**
  5517. * 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".
  5518. * This methods works for a Left-Handed system.
  5519. */
  5520. Matrix.LookAtLH = function (eye, target, up) {
  5521. var result = Matrix.Zero();
  5522. Matrix.LookAtLHToRef(eye, target, up, result);
  5523. return result;
  5524. };
  5525. /**
  5526. * 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".
  5527. * This methods works for a Left-Handed system.
  5528. */
  5529. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5530. // Z axis
  5531. target.subtractToRef(eye, this._zAxis);
  5532. this._zAxis.normalize();
  5533. // X axis
  5534. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5535. if (this._xAxis.lengthSquared() === 0) {
  5536. this._xAxis.x = 1.0;
  5537. }
  5538. else {
  5539. this._xAxis.normalize();
  5540. }
  5541. // Y axis
  5542. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5543. this._yAxis.normalize();
  5544. // Eye angles
  5545. var ex = -Vector3.Dot(this._xAxis, eye);
  5546. var ey = -Vector3.Dot(this._yAxis, eye);
  5547. var ez = -Vector3.Dot(this._zAxis, eye);
  5548. 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);
  5549. };
  5550. /**
  5551. * 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".
  5552. * This methods works for a Right-Handed system.
  5553. */
  5554. Matrix.LookAtRH = function (eye, target, up) {
  5555. var result = Matrix.Zero();
  5556. Matrix.LookAtRHToRef(eye, target, up, result);
  5557. return result;
  5558. };
  5559. /**
  5560. * 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".
  5561. * This methods works for a Left-Handed system.
  5562. */
  5563. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5564. // Z axis
  5565. eye.subtractToRef(target, this._zAxis);
  5566. this._zAxis.normalize();
  5567. // X axis
  5568. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5569. if (this._xAxis.lengthSquared() === 0) {
  5570. this._xAxis.x = 1.0;
  5571. }
  5572. else {
  5573. this._xAxis.normalize();
  5574. }
  5575. // Y axis
  5576. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5577. this._yAxis.normalize();
  5578. // Eye angles
  5579. var ex = -Vector3.Dot(this._xAxis, eye);
  5580. var ey = -Vector3.Dot(this._yAxis, eye);
  5581. var ez = -Vector3.Dot(this._zAxis, eye);
  5582. 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);
  5583. };
  5584. /**
  5585. * 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.
  5586. */
  5587. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5588. var matrix = Matrix.Zero();
  5589. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5590. return matrix;
  5591. };
  5592. /**
  5593. * 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.
  5594. */
  5595. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5596. var n = znear;
  5597. var f = zfar;
  5598. var a = 2.0 / width;
  5599. var b = 2.0 / height;
  5600. var c = 2.0 / (f - n);
  5601. var d = -(f + n) / (f - n);
  5602. 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);
  5603. };
  5604. /**
  5605. * 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.
  5606. */
  5607. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5608. var matrix = Matrix.Zero();
  5609. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5610. return matrix;
  5611. };
  5612. /**
  5613. * 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.
  5614. */
  5615. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5616. var n = znear;
  5617. var f = zfar;
  5618. var a = 2.0 / (right - left);
  5619. var b = 2.0 / (top - bottom);
  5620. var c = 2.0 / (f - n);
  5621. var d = -(f + n) / (f - n);
  5622. var i0 = (left + right) / (left - right);
  5623. var i1 = (top + bottom) / (bottom - top);
  5624. 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);
  5625. };
  5626. /**
  5627. * 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.
  5628. */
  5629. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5630. var matrix = Matrix.Zero();
  5631. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5632. return matrix;
  5633. };
  5634. /**
  5635. * 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.
  5636. */
  5637. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5638. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5639. result.m[10] *= -1.0;
  5640. };
  5641. /**
  5642. * 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.
  5643. */
  5644. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5645. var matrix = Matrix.Zero();
  5646. var n = znear;
  5647. var f = zfar;
  5648. var a = 2.0 * n / width;
  5649. var b = 2.0 * n / height;
  5650. var c = (f + n) / (f - n);
  5651. var d = -2.0 * f * n / (f - n);
  5652. 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);
  5653. return matrix;
  5654. };
  5655. /**
  5656. * 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.
  5657. */
  5658. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5659. var matrix = Matrix.Zero();
  5660. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5661. return matrix;
  5662. };
  5663. /**
  5664. * 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.
  5665. */
  5666. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5667. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5668. var n = znear;
  5669. var f = zfar;
  5670. var t = 1.0 / (Math.tan(fov * 0.5));
  5671. var a = isVerticalFovFixed ? (t / aspect) : t;
  5672. var b = isVerticalFovFixed ? t : (t * aspect);
  5673. var c = (f + n) / (f - n);
  5674. var d = -2.0 * f * n / (f - n);
  5675. 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);
  5676. };
  5677. /**
  5678. * 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.
  5679. */
  5680. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5681. var matrix = Matrix.Zero();
  5682. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5683. return matrix;
  5684. };
  5685. /**
  5686. * 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.
  5687. */
  5688. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5689. //alternatively this could be expressed as:
  5690. // m = PerspectiveFovLHToRef
  5691. // m[10] *= -1.0;
  5692. // m[11] *= -1.0;
  5693. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5694. var n = znear;
  5695. var f = zfar;
  5696. var t = 1.0 / (Math.tan(fov * 0.5));
  5697. var a = isVerticalFovFixed ? (t / aspect) : t;
  5698. var b = isVerticalFovFixed ? t : (t * aspect);
  5699. var c = -(f + n) / (f - n);
  5700. var d = -2 * f * n / (f - n);
  5701. 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);
  5702. };
  5703. /**
  5704. * 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.
  5705. */
  5706. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5707. if (rightHanded === void 0) { rightHanded = false; }
  5708. var rightHandedFactor = rightHanded ? -1 : 1;
  5709. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5710. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5711. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5712. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5713. var xScale = 2.0 / (leftTan + rightTan);
  5714. var yScale = 2.0 / (upTan + downTan);
  5715. result.m[0] = xScale;
  5716. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5717. result.m[5] = yScale;
  5718. result.m[6] = result.m[7] = 0.0;
  5719. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5720. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5721. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5722. result.m[10] = -zfar / (znear - zfar);
  5723. result.m[11] = 1.0 * rightHandedFactor;
  5724. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5725. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5726. // result.m[14] = (znear * zfar) / (znear - zfar);
  5727. result._markAsUpdated();
  5728. };
  5729. /**
  5730. * Returns the final transformation matrix : world * view * projection * viewport
  5731. */
  5732. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5733. var cw = viewport.width;
  5734. var ch = viewport.height;
  5735. var cx = viewport.x;
  5736. var cy = viewport.y;
  5737. 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);
  5738. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5739. };
  5740. /**
  5741. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5742. */
  5743. Matrix.GetAsMatrix2x2 = function (matrix) {
  5744. return new Float32Array([
  5745. matrix.m[0], matrix.m[1],
  5746. matrix.m[4], matrix.m[5]
  5747. ]);
  5748. };
  5749. /**
  5750. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5751. */
  5752. Matrix.GetAsMatrix3x3 = function (matrix) {
  5753. return new Float32Array([
  5754. matrix.m[0], matrix.m[1], matrix.m[2],
  5755. matrix.m[4], matrix.m[5], matrix.m[6],
  5756. matrix.m[8], matrix.m[9], matrix.m[10]
  5757. ]);
  5758. };
  5759. /**
  5760. * Compute the transpose of the passed Matrix.
  5761. * Returns a new Matrix.
  5762. */
  5763. Matrix.Transpose = function (matrix) {
  5764. var result = new Matrix();
  5765. Matrix.TransposeToRef(matrix, result);
  5766. return result;
  5767. };
  5768. /**
  5769. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5770. */
  5771. Matrix.TransposeToRef = function (matrix, result) {
  5772. result.m[0] = matrix.m[0];
  5773. result.m[1] = matrix.m[4];
  5774. result.m[2] = matrix.m[8];
  5775. result.m[3] = matrix.m[12];
  5776. result.m[4] = matrix.m[1];
  5777. result.m[5] = matrix.m[5];
  5778. result.m[6] = matrix.m[9];
  5779. result.m[7] = matrix.m[13];
  5780. result.m[8] = matrix.m[2];
  5781. result.m[9] = matrix.m[6];
  5782. result.m[10] = matrix.m[10];
  5783. result.m[11] = matrix.m[14];
  5784. result.m[12] = matrix.m[3];
  5785. result.m[13] = matrix.m[7];
  5786. result.m[14] = matrix.m[11];
  5787. result.m[15] = matrix.m[15];
  5788. };
  5789. /**
  5790. * Returns a new Matrix as the reflection matrix across the passed plane.
  5791. */
  5792. Matrix.Reflection = function (plane) {
  5793. var matrix = new Matrix();
  5794. Matrix.ReflectionToRef(plane, matrix);
  5795. return matrix;
  5796. };
  5797. /**
  5798. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5799. */
  5800. Matrix.ReflectionToRef = function (plane, result) {
  5801. plane.normalize();
  5802. var x = plane.normal.x;
  5803. var y = plane.normal.y;
  5804. var z = plane.normal.z;
  5805. var temp = -2 * x;
  5806. var temp2 = -2 * y;
  5807. var temp3 = -2 * z;
  5808. result.m[0] = (temp * x) + 1;
  5809. result.m[1] = temp2 * x;
  5810. result.m[2] = temp3 * x;
  5811. result.m[3] = 0.0;
  5812. result.m[4] = temp * y;
  5813. result.m[5] = (temp2 * y) + 1;
  5814. result.m[6] = temp3 * y;
  5815. result.m[7] = 0.0;
  5816. result.m[8] = temp * z;
  5817. result.m[9] = temp2 * z;
  5818. result.m[10] = (temp3 * z) + 1;
  5819. result.m[11] = 0.0;
  5820. result.m[12] = temp * plane.d;
  5821. result.m[13] = temp2 * plane.d;
  5822. result.m[14] = temp3 * plane.d;
  5823. result.m[15] = 1.0;
  5824. result._markAsUpdated();
  5825. };
  5826. /**
  5827. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5828. */
  5829. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5830. result.m[0] = xaxis.x;
  5831. result.m[1] = xaxis.y;
  5832. result.m[2] = xaxis.z;
  5833. result.m[3] = 0.0;
  5834. result.m[4] = yaxis.x;
  5835. result.m[5] = yaxis.y;
  5836. result.m[6] = yaxis.z;
  5837. result.m[7] = 0.0;
  5838. result.m[8] = zaxis.x;
  5839. result.m[9] = zaxis.y;
  5840. result.m[10] = zaxis.z;
  5841. result.m[11] = 0.0;
  5842. result.m[12] = 0.0;
  5843. result.m[13] = 0.0;
  5844. result.m[14] = 0.0;
  5845. result.m[15] = 1.0;
  5846. result._markAsUpdated();
  5847. };
  5848. /**
  5849. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5850. */
  5851. Matrix.FromQuaternionToRef = function (quat, result) {
  5852. var xx = quat.x * quat.x;
  5853. var yy = quat.y * quat.y;
  5854. var zz = quat.z * quat.z;
  5855. var xy = quat.x * quat.y;
  5856. var zw = quat.z * quat.w;
  5857. var zx = quat.z * quat.x;
  5858. var yw = quat.y * quat.w;
  5859. var yz = quat.y * quat.z;
  5860. var xw = quat.x * quat.w;
  5861. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5862. result.m[1] = 2.0 * (xy + zw);
  5863. result.m[2] = 2.0 * (zx - yw);
  5864. result.m[3] = 0.0;
  5865. result.m[4] = 2.0 * (xy - zw);
  5866. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5867. result.m[6] = 2.0 * (yz + xw);
  5868. result.m[7] = 0.0;
  5869. result.m[8] = 2.0 * (zx + yw);
  5870. result.m[9] = 2.0 * (yz - xw);
  5871. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5872. result.m[11] = 0.0;
  5873. result.m[12] = 0.0;
  5874. result.m[13] = 0.0;
  5875. result.m[14] = 0.0;
  5876. result.m[15] = 1.0;
  5877. result._markAsUpdated();
  5878. };
  5879. Matrix._tempQuaternion = new Quaternion();
  5880. Matrix._xAxis = Vector3.Zero();
  5881. Matrix._yAxis = Vector3.Zero();
  5882. Matrix._zAxis = Vector3.Zero();
  5883. Matrix._updateFlagSeed = 0;
  5884. Matrix._identityReadOnly = Matrix.Identity();
  5885. return Matrix;
  5886. }());
  5887. BABYLON.Matrix = Matrix;
  5888. var Plane = /** @class */ (function () {
  5889. /**
  5890. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5891. */
  5892. function Plane(a, b, c, d) {
  5893. this.normal = new Vector3(a, b, c);
  5894. this.d = d;
  5895. }
  5896. /**
  5897. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5898. */
  5899. Plane.prototype.asArray = function () {
  5900. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5901. };
  5902. // Methods
  5903. /**
  5904. * Returns a new plane copied from the current Plane.
  5905. */
  5906. Plane.prototype.clone = function () {
  5907. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5908. };
  5909. /**
  5910. * Returns the string "Plane".
  5911. */
  5912. Plane.prototype.getClassName = function () {
  5913. return "Plane";
  5914. };
  5915. /**
  5916. * Returns the Plane hash code.
  5917. */
  5918. Plane.prototype.getHashCode = function () {
  5919. var hash = this.normal.getHashCode();
  5920. hash = (hash * 397) ^ (this.d || 0);
  5921. return hash;
  5922. };
  5923. /**
  5924. * Normalize the current Plane in place.
  5925. * Returns the updated Plane.
  5926. */
  5927. Plane.prototype.normalize = function () {
  5928. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5929. var magnitude = 0.0;
  5930. if (norm !== 0) {
  5931. magnitude = 1.0 / norm;
  5932. }
  5933. this.normal.x *= magnitude;
  5934. this.normal.y *= magnitude;
  5935. this.normal.z *= magnitude;
  5936. this.d *= magnitude;
  5937. return this;
  5938. };
  5939. /**
  5940. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5941. */
  5942. Plane.prototype.transform = function (transformation) {
  5943. var transposedMatrix = Matrix.Transpose(transformation);
  5944. var x = this.normal.x;
  5945. var y = this.normal.y;
  5946. var z = this.normal.z;
  5947. var d = this.d;
  5948. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5949. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5950. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5951. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5952. return new Plane(normalX, normalY, normalZ, finalD);
  5953. };
  5954. /**
  5955. * Returns the dot product (float) of the point coordinates and the plane normal.
  5956. */
  5957. Plane.prototype.dotCoordinate = function (point) {
  5958. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5959. };
  5960. /**
  5961. * Updates the current Plane from the plane defined by the three passed points.
  5962. * Returns the updated Plane.
  5963. */
  5964. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5965. var x1 = point2.x - point1.x;
  5966. var y1 = point2.y - point1.y;
  5967. var z1 = point2.z - point1.z;
  5968. var x2 = point3.x - point1.x;
  5969. var y2 = point3.y - point1.y;
  5970. var z2 = point3.z - point1.z;
  5971. var yz = (y1 * z2) - (z1 * y2);
  5972. var xz = (z1 * x2) - (x1 * z2);
  5973. var xy = (x1 * y2) - (y1 * x2);
  5974. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5975. var invPyth;
  5976. if (pyth !== 0) {
  5977. invPyth = 1.0 / pyth;
  5978. }
  5979. else {
  5980. invPyth = 0.0;
  5981. }
  5982. this.normal.x = yz * invPyth;
  5983. this.normal.y = xz * invPyth;
  5984. this.normal.z = xy * invPyth;
  5985. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5986. return this;
  5987. };
  5988. /**
  5989. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5990. */
  5991. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5992. var dot = Vector3.Dot(this.normal, direction);
  5993. return (dot <= epsilon);
  5994. };
  5995. /**
  5996. * Returns the signed distance (float) from the passed point to the Plane.
  5997. */
  5998. Plane.prototype.signedDistanceTo = function (point) {
  5999. return Vector3.Dot(point, this.normal) + this.d;
  6000. };
  6001. // Statics
  6002. /**
  6003. * Returns a new Plane from the passed array.
  6004. */
  6005. Plane.FromArray = function (array) {
  6006. return new Plane(array[0], array[1], array[2], array[3]);
  6007. };
  6008. /**
  6009. * Returns a new Plane defined by the three passed points.
  6010. */
  6011. Plane.FromPoints = function (point1, point2, point3) {
  6012. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6013. result.copyFromPoints(point1, point2, point3);
  6014. return result;
  6015. };
  6016. /**
  6017. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6018. * Note : the vector "normal" is updated because normalized.
  6019. */
  6020. Plane.FromPositionAndNormal = function (origin, normal) {
  6021. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6022. normal.normalize();
  6023. result.normal = normal;
  6024. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6025. return result;
  6026. };
  6027. /**
  6028. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6029. */
  6030. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6031. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6032. return Vector3.Dot(point, normal) + d;
  6033. };
  6034. return Plane;
  6035. }());
  6036. BABYLON.Plane = Plane;
  6037. var Viewport = /** @class */ (function () {
  6038. /**
  6039. * Creates a Viewport object located at (x, y) and sized (width, height).
  6040. */
  6041. function Viewport(x, y, width, height) {
  6042. this.x = x;
  6043. this.y = y;
  6044. this.width = width;
  6045. this.height = height;
  6046. }
  6047. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6048. if (renderWidthOrEngine.getRenderWidth) {
  6049. var engine = renderWidthOrEngine;
  6050. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6051. }
  6052. var renderWidth = renderWidthOrEngine;
  6053. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6054. };
  6055. /**
  6056. * Returns a new Viewport copied from the current one.
  6057. */
  6058. Viewport.prototype.clone = function () {
  6059. return new Viewport(this.x, this.y, this.width, this.height);
  6060. };
  6061. return Viewport;
  6062. }());
  6063. BABYLON.Viewport = Viewport;
  6064. var Frustum = /** @class */ (function () {
  6065. function Frustum() {
  6066. }
  6067. /**
  6068. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6069. */
  6070. Frustum.GetPlanes = function (transform) {
  6071. var frustumPlanes = [];
  6072. for (var index = 0; index < 6; index++) {
  6073. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6074. }
  6075. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6076. return frustumPlanes;
  6077. };
  6078. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6079. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6080. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6081. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6082. frustumPlane.d = transform.m[15] + transform.m[14];
  6083. frustumPlane.normalize();
  6084. };
  6085. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6086. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6087. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6088. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6089. frustumPlane.d = transform.m[15] - transform.m[14];
  6090. frustumPlane.normalize();
  6091. };
  6092. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6093. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6094. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6095. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6096. frustumPlane.d = transform.m[15] + transform.m[12];
  6097. frustumPlane.normalize();
  6098. };
  6099. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6100. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6101. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6102. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6103. frustumPlane.d = transform.m[15] - transform.m[12];
  6104. frustumPlane.normalize();
  6105. };
  6106. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6107. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6108. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6109. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6110. frustumPlane.d = transform.m[15] - transform.m[13];
  6111. frustumPlane.normalize();
  6112. };
  6113. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6114. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6115. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6116. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6117. frustumPlane.d = transform.m[15] + transform.m[13];
  6118. frustumPlane.normalize();
  6119. };
  6120. /**
  6121. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6122. */
  6123. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6124. // Near
  6125. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6126. // Far
  6127. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6128. // Left
  6129. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6130. // Right
  6131. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6132. // Top
  6133. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6134. // Bottom
  6135. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6136. };
  6137. return Frustum;
  6138. }());
  6139. BABYLON.Frustum = Frustum;
  6140. var Space;
  6141. (function (Space) {
  6142. Space[Space["LOCAL"] = 0] = "LOCAL";
  6143. Space[Space["WORLD"] = 1] = "WORLD";
  6144. Space[Space["BONE"] = 2] = "BONE";
  6145. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6146. var Axis = /** @class */ (function () {
  6147. function Axis() {
  6148. }
  6149. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6150. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6151. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6152. return Axis;
  6153. }());
  6154. BABYLON.Axis = Axis;
  6155. ;
  6156. var BezierCurve = /** @class */ (function () {
  6157. function BezierCurve() {
  6158. }
  6159. /**
  6160. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6161. */
  6162. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6163. // Extract X (which is equal to time here)
  6164. var f0 = 1 - 3 * x2 + 3 * x1;
  6165. var f1 = 3 * x2 - 6 * x1;
  6166. var f2 = 3 * x1;
  6167. var refinedT = t;
  6168. for (var i = 0; i < 5; i++) {
  6169. var refinedT2 = refinedT * refinedT;
  6170. var refinedT3 = refinedT2 * refinedT;
  6171. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6172. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6173. refinedT -= (x - t) * slope;
  6174. refinedT = Math.min(1, Math.max(0, refinedT));
  6175. }
  6176. // Resolve cubic bezier for the given x
  6177. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6178. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6179. Math.pow(refinedT, 3);
  6180. };
  6181. return BezierCurve;
  6182. }());
  6183. BABYLON.BezierCurve = BezierCurve;
  6184. var Orientation;
  6185. (function (Orientation) {
  6186. Orientation[Orientation["CW"] = 0] = "CW";
  6187. Orientation[Orientation["CCW"] = 1] = "CCW";
  6188. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6189. var Angle = /** @class */ (function () {
  6190. /**
  6191. * Creates an Angle object of "radians" radians (float).
  6192. */
  6193. function Angle(radians) {
  6194. var _this = this;
  6195. /**
  6196. * Returns the Angle value in degrees (float).
  6197. */
  6198. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6199. /**
  6200. * Returns the Angle value in radians (float).
  6201. */
  6202. this.radians = function () { return _this._radians; };
  6203. this._radians = radians;
  6204. if (this._radians < 0.0)
  6205. this._radians += (2.0 * Math.PI);
  6206. }
  6207. /**
  6208. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6209. */
  6210. Angle.BetweenTwoPoints = function (a, b) {
  6211. var delta = b.subtract(a);
  6212. var theta = Math.atan2(delta.y, delta.x);
  6213. return new Angle(theta);
  6214. };
  6215. /**
  6216. * Returns a new Angle object from the passed float in radians.
  6217. */
  6218. Angle.FromRadians = function (radians) {
  6219. return new Angle(radians);
  6220. };
  6221. /**
  6222. * Returns a new Angle object from the passed float in degrees.
  6223. */
  6224. Angle.FromDegrees = function (degrees) {
  6225. return new Angle(degrees * Math.PI / 180.0);
  6226. };
  6227. return Angle;
  6228. }());
  6229. BABYLON.Angle = Angle;
  6230. var Arc2 = /** @class */ (function () {
  6231. /**
  6232. * Creates an Arc object from the three passed points : start, middle and end.
  6233. */
  6234. function Arc2(startPoint, midPoint, endPoint) {
  6235. this.startPoint = startPoint;
  6236. this.midPoint = midPoint;
  6237. this.endPoint = endPoint;
  6238. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6239. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6240. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6241. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6242. 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);
  6243. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6244. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6245. var a1 = this.startAngle.degrees();
  6246. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6247. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6248. // angles correction
  6249. if (a2 - a1 > +180.0)
  6250. a2 -= 360.0;
  6251. if (a2 - a1 < -180.0)
  6252. a2 += 360.0;
  6253. if (a3 - a2 > +180.0)
  6254. a3 -= 360.0;
  6255. if (a3 - a2 < -180.0)
  6256. a3 += 360.0;
  6257. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6258. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6259. }
  6260. return Arc2;
  6261. }());
  6262. BABYLON.Arc2 = Arc2;
  6263. var Path2 = /** @class */ (function () {
  6264. /**
  6265. * Creates a Path2 object from the starting 2D coordinates x and y.
  6266. */
  6267. function Path2(x, y) {
  6268. this._points = new Array();
  6269. this._length = 0.0;
  6270. this.closed = false;
  6271. this._points.push(new Vector2(x, y));
  6272. }
  6273. /**
  6274. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6275. * Returns the updated Path2.
  6276. */
  6277. Path2.prototype.addLineTo = function (x, y) {
  6278. if (this.closed) {
  6279. return this;
  6280. }
  6281. var newPoint = new Vector2(x, y);
  6282. var previousPoint = this._points[this._points.length - 1];
  6283. this._points.push(newPoint);
  6284. this._length += newPoint.subtract(previousPoint).length();
  6285. return this;
  6286. };
  6287. /**
  6288. * 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.
  6289. * Returns the updated Path2.
  6290. */
  6291. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6292. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6293. if (this.closed) {
  6294. return this;
  6295. }
  6296. var startPoint = this._points[this._points.length - 1];
  6297. var midPoint = new Vector2(midX, midY);
  6298. var endPoint = new Vector2(endX, endY);
  6299. var arc = new Arc2(startPoint, midPoint, endPoint);
  6300. var increment = arc.angle.radians() / numberOfSegments;
  6301. if (arc.orientation === Orientation.CW)
  6302. increment *= -1;
  6303. var currentAngle = arc.startAngle.radians() + increment;
  6304. for (var i = 0; i < numberOfSegments; i++) {
  6305. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6306. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6307. this.addLineTo(x, y);
  6308. currentAngle += increment;
  6309. }
  6310. return this;
  6311. };
  6312. /**
  6313. * Closes the Path2.
  6314. * Returns the Path2.
  6315. */
  6316. Path2.prototype.close = function () {
  6317. this.closed = true;
  6318. return this;
  6319. };
  6320. /**
  6321. * Returns the Path2 total length (float).
  6322. */
  6323. Path2.prototype.length = function () {
  6324. var result = this._length;
  6325. if (!this.closed) {
  6326. var lastPoint = this._points[this._points.length - 1];
  6327. var firstPoint = this._points[0];
  6328. result += (firstPoint.subtract(lastPoint).length());
  6329. }
  6330. return result;
  6331. };
  6332. /**
  6333. * Returns the Path2 internal array of points.
  6334. */
  6335. Path2.prototype.getPoints = function () {
  6336. return this._points;
  6337. };
  6338. /**
  6339. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6340. */
  6341. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6342. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6343. return Vector2.Zero();
  6344. }
  6345. var lengthPosition = normalizedLengthPosition * this.length();
  6346. var previousOffset = 0;
  6347. for (var i = 0; i < this._points.length; i++) {
  6348. var j = (i + 1) % this._points.length;
  6349. var a = this._points[i];
  6350. var b = this._points[j];
  6351. var bToA = b.subtract(a);
  6352. var nextOffset = (bToA.length() + previousOffset);
  6353. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6354. var dir = bToA.normalize();
  6355. var localOffset = lengthPosition - previousOffset;
  6356. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6357. }
  6358. previousOffset = nextOffset;
  6359. }
  6360. return Vector2.Zero();
  6361. };
  6362. /**
  6363. * Returns a new Path2 starting at the coordinates (x, y).
  6364. */
  6365. Path2.StartingAt = function (x, y) {
  6366. return new Path2(x, y);
  6367. };
  6368. return Path2;
  6369. }());
  6370. BABYLON.Path2 = Path2;
  6371. var Path3D = /** @class */ (function () {
  6372. /**
  6373. * new Path3D(path, normal, raw)
  6374. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6375. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6376. * path : an array of Vector3, the curve axis of the Path3D
  6377. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6378. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6379. */
  6380. function Path3D(path, firstNormal, raw) {
  6381. if (firstNormal === void 0) { firstNormal = null; }
  6382. this.path = path;
  6383. this._curve = new Array();
  6384. this._distances = new Array();
  6385. this._tangents = new Array();
  6386. this._normals = new Array();
  6387. this._binormals = new Array();
  6388. for (var p = 0; p < path.length; p++) {
  6389. this._curve[p] = path[p].clone(); // hard copy
  6390. }
  6391. this._raw = raw || false;
  6392. this._compute(firstNormal);
  6393. }
  6394. /**
  6395. * Returns the Path3D array of successive Vector3 designing its curve.
  6396. */
  6397. Path3D.prototype.getCurve = function () {
  6398. return this._curve;
  6399. };
  6400. /**
  6401. * Returns an array populated with tangent vectors on each Path3D curve point.
  6402. */
  6403. Path3D.prototype.getTangents = function () {
  6404. return this._tangents;
  6405. };
  6406. /**
  6407. * Returns an array populated with normal vectors on each Path3D curve point.
  6408. */
  6409. Path3D.prototype.getNormals = function () {
  6410. return this._normals;
  6411. };
  6412. /**
  6413. * Returns an array populated with binormal vectors on each Path3D curve point.
  6414. */
  6415. Path3D.prototype.getBinormals = function () {
  6416. return this._binormals;
  6417. };
  6418. /**
  6419. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6420. */
  6421. Path3D.prototype.getDistances = function () {
  6422. return this._distances;
  6423. };
  6424. /**
  6425. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6426. * Returns the same object updated.
  6427. */
  6428. Path3D.prototype.update = function (path, firstNormal) {
  6429. if (firstNormal === void 0) { firstNormal = null; }
  6430. for (var p = 0; p < path.length; p++) {
  6431. this._curve[p].x = path[p].x;
  6432. this._curve[p].y = path[p].y;
  6433. this._curve[p].z = path[p].z;
  6434. }
  6435. this._compute(firstNormal);
  6436. return this;
  6437. };
  6438. // private function compute() : computes tangents, normals and binormals
  6439. Path3D.prototype._compute = function (firstNormal) {
  6440. var l = this._curve.length;
  6441. // first and last tangents
  6442. this._tangents[0] = this._getFirstNonNullVector(0);
  6443. if (!this._raw) {
  6444. this._tangents[0].normalize();
  6445. }
  6446. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6447. if (!this._raw) {
  6448. this._tangents[l - 1].normalize();
  6449. }
  6450. // normals and binormals at first point : arbitrary vector with _normalVector()
  6451. var tg0 = this._tangents[0];
  6452. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6453. this._normals[0] = pp0;
  6454. if (!this._raw) {
  6455. this._normals[0].normalize();
  6456. }
  6457. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6458. if (!this._raw) {
  6459. this._binormals[0].normalize();
  6460. }
  6461. this._distances[0] = 0.0;
  6462. // normals and binormals : next points
  6463. var prev; // previous vector (segment)
  6464. var cur; // current vector (segment)
  6465. var curTang; // current tangent
  6466. // previous normal
  6467. var prevBinor; // previous binormal
  6468. for (var i = 1; i < l; i++) {
  6469. // tangents
  6470. prev = this._getLastNonNullVector(i);
  6471. if (i < l - 1) {
  6472. cur = this._getFirstNonNullVector(i);
  6473. this._tangents[i] = prev.add(cur);
  6474. this._tangents[i].normalize();
  6475. }
  6476. this._distances[i] = this._distances[i - 1] + prev.length();
  6477. // normals and binormals
  6478. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6479. curTang = this._tangents[i];
  6480. prevBinor = this._binormals[i - 1];
  6481. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6482. if (!this._raw) {
  6483. this._normals[i].normalize();
  6484. }
  6485. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6486. if (!this._raw) {
  6487. this._binormals[i].normalize();
  6488. }
  6489. }
  6490. };
  6491. // private function getFirstNonNullVector(index)
  6492. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6493. Path3D.prototype._getFirstNonNullVector = function (index) {
  6494. var i = 1;
  6495. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6496. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6497. i++;
  6498. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6499. }
  6500. return nNVector;
  6501. };
  6502. // private function getLastNonNullVector(index)
  6503. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6504. Path3D.prototype._getLastNonNullVector = function (index) {
  6505. var i = 1;
  6506. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6507. while (nLVector.length() === 0 && index > i + 1) {
  6508. i++;
  6509. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6510. }
  6511. return nLVector;
  6512. };
  6513. // private function normalVector(v0, vt, va) :
  6514. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6515. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6516. Path3D.prototype._normalVector = function (v0, vt, va) {
  6517. var normal0;
  6518. var tgl = vt.length();
  6519. if (tgl === 0.0) {
  6520. tgl = 1.0;
  6521. }
  6522. if (va === undefined || va === null) {
  6523. var point;
  6524. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6525. point = new Vector3(0.0, -1.0, 0.0);
  6526. }
  6527. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6528. point = new Vector3(1.0, 0.0, 0.0);
  6529. }
  6530. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6531. point = new Vector3(0.0, 0.0, 1.0);
  6532. }
  6533. else {
  6534. point = Vector3.Zero();
  6535. }
  6536. normal0 = Vector3.Cross(vt, point);
  6537. }
  6538. else {
  6539. normal0 = Vector3.Cross(vt, va);
  6540. Vector3.CrossToRef(normal0, vt, normal0);
  6541. }
  6542. normal0.normalize();
  6543. return normal0;
  6544. };
  6545. return Path3D;
  6546. }());
  6547. BABYLON.Path3D = Path3D;
  6548. var Curve3 = /** @class */ (function () {
  6549. /**
  6550. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6551. * A Curve3 is designed from a series of successive Vector3.
  6552. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6553. */
  6554. function Curve3(points) {
  6555. this._length = 0.0;
  6556. this._points = points;
  6557. this._length = this._computeLength(points);
  6558. }
  6559. /**
  6560. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6561. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6562. * @param v1 (Vector3) the control point
  6563. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6564. * @param nbPoints (integer) the wanted number of points in the curve
  6565. */
  6566. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6567. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6568. var bez = new Array();
  6569. var equation = function (t, val0, val1, val2) {
  6570. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6571. return res;
  6572. };
  6573. for (var i = 0; i <= nbPoints; i++) {
  6574. 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)));
  6575. }
  6576. return new Curve3(bez);
  6577. };
  6578. /**
  6579. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6580. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6581. * @param v1 (Vector3) the first control point
  6582. * @param v2 (Vector3) the second control point
  6583. * @param v3 (Vector3) the end point of the Cubic Bezier
  6584. * @param nbPoints (integer) the wanted number of points in the curve
  6585. */
  6586. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6587. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6588. var bez = new Array();
  6589. var equation = function (t, val0, val1, val2, val3) {
  6590. 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;
  6591. return res;
  6592. };
  6593. for (var i = 0; i <= nbPoints; i++) {
  6594. 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)));
  6595. }
  6596. return new Curve3(bez);
  6597. };
  6598. /**
  6599. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6600. * @param p1 (Vector3) the origin point of the Hermite Spline
  6601. * @param t1 (Vector3) the tangent vector at the origin point
  6602. * @param p2 (Vector3) the end point of the Hermite Spline
  6603. * @param t2 (Vector3) the tangent vector at the end point
  6604. * @param nbPoints (integer) the wanted number of points in the curve
  6605. */
  6606. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6607. var hermite = new Array();
  6608. var step = 1.0 / nbPoints;
  6609. for (var i = 0; i <= nbPoints; i++) {
  6610. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6611. }
  6612. return new Curve3(hermite);
  6613. };
  6614. /**
  6615. * Returns a Curve3 object along a CatmullRom Spline curve :
  6616. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6617. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6618. */
  6619. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6620. var totalPoints = new Array();
  6621. totalPoints.push(points[0].clone());
  6622. Array.prototype.push.apply(totalPoints, points);
  6623. totalPoints.push(points[points.length - 1].clone());
  6624. var catmullRom = new Array();
  6625. var step = 1.0 / nbPoints;
  6626. var amount = 0.0;
  6627. for (var i = 0; i < totalPoints.length - 3; i++) {
  6628. amount = 0;
  6629. for (var c = 0; c < nbPoints; c++) {
  6630. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6631. amount += step;
  6632. }
  6633. }
  6634. i--;
  6635. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6636. return new Curve3(catmullRom);
  6637. };
  6638. /**
  6639. * Returns the Curve3 stored array of successive Vector3
  6640. */
  6641. Curve3.prototype.getPoints = function () {
  6642. return this._points;
  6643. };
  6644. /**
  6645. * Returns the computed length (float) of the curve.
  6646. */
  6647. Curve3.prototype.length = function () {
  6648. return this._length;
  6649. };
  6650. /**
  6651. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6652. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6653. * curveA and curveB keep unchanged.
  6654. */
  6655. Curve3.prototype.continue = function (curve) {
  6656. var lastPoint = this._points[this._points.length - 1];
  6657. var continuedPoints = this._points.slice();
  6658. var curvePoints = curve.getPoints();
  6659. for (var i = 1; i < curvePoints.length; i++) {
  6660. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6661. }
  6662. var continuedCurve = new Curve3(continuedPoints);
  6663. return continuedCurve;
  6664. };
  6665. Curve3.prototype._computeLength = function (path) {
  6666. var l = 0;
  6667. for (var i = 1; i < path.length; i++) {
  6668. l += (path[i].subtract(path[i - 1])).length();
  6669. }
  6670. return l;
  6671. };
  6672. return Curve3;
  6673. }());
  6674. BABYLON.Curve3 = Curve3;
  6675. // Vertex formats
  6676. var PositionNormalVertex = /** @class */ (function () {
  6677. function PositionNormalVertex(position, normal) {
  6678. if (position === void 0) { position = Vector3.Zero(); }
  6679. if (normal === void 0) { normal = Vector3.Up(); }
  6680. this.position = position;
  6681. this.normal = normal;
  6682. }
  6683. PositionNormalVertex.prototype.clone = function () {
  6684. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6685. };
  6686. return PositionNormalVertex;
  6687. }());
  6688. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6689. var PositionNormalTextureVertex = /** @class */ (function () {
  6690. function PositionNormalTextureVertex(position, normal, uv) {
  6691. if (position === void 0) { position = Vector3.Zero(); }
  6692. if (normal === void 0) { normal = Vector3.Up(); }
  6693. if (uv === void 0) { uv = Vector2.Zero(); }
  6694. this.position = position;
  6695. this.normal = normal;
  6696. this.uv = uv;
  6697. }
  6698. PositionNormalTextureVertex.prototype.clone = function () {
  6699. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6700. };
  6701. return PositionNormalTextureVertex;
  6702. }());
  6703. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6704. // Temporary pre-allocated objects for engine internal use
  6705. // usage in any internal function :
  6706. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6707. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6708. var Tmp = /** @class */ (function () {
  6709. function Tmp() {
  6710. }
  6711. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6712. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6713. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6714. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6715. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6716. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6717. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6718. Matrix.Zero(), Matrix.Zero(),
  6719. Matrix.Zero(), Matrix.Zero(),
  6720. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6721. return Tmp;
  6722. }());
  6723. BABYLON.Tmp = Tmp;
  6724. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6725. var MathTmp = /** @class */ (function () {
  6726. function MathTmp() {
  6727. }
  6728. MathTmp.Vector3 = [Vector3.Zero()];
  6729. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6730. MathTmp.Quaternion = [Quaternion.Zero()];
  6731. return MathTmp;
  6732. }());
  6733. })(BABYLON || (BABYLON = {}));
  6734. //# sourceMappingURL=babylon.math.js.map
  6735. var BABYLON;
  6736. (function (BABYLON) {
  6737. var Scalar = /** @class */ (function () {
  6738. function Scalar() {
  6739. }
  6740. /**
  6741. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6742. */
  6743. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6744. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6745. var num = a - b;
  6746. return -epsilon <= num && num <= epsilon;
  6747. };
  6748. /**
  6749. * Returns a string : the upper case translation of the number i to hexadecimal.
  6750. */
  6751. Scalar.ToHex = function (i) {
  6752. var str = i.toString(16);
  6753. if (i <= 15) {
  6754. return ("0" + str).toUpperCase();
  6755. }
  6756. return str.toUpperCase();
  6757. };
  6758. /**
  6759. * Returns -1 if value is negative and +1 is value is positive.
  6760. * Returns the value itself if it's equal to zero.
  6761. */
  6762. Scalar.Sign = function (value) {
  6763. value = +value; // convert to a number
  6764. if (value === 0 || isNaN(value))
  6765. return value;
  6766. return value > 0 ? 1 : -1;
  6767. };
  6768. /**
  6769. * Returns the value itself if it's between min and max.
  6770. * Returns min if the value is lower than min.
  6771. * Returns max if the value is greater than max.
  6772. */
  6773. Scalar.Clamp = function (value, min, max) {
  6774. if (min === void 0) { min = 0; }
  6775. if (max === void 0) { max = 1; }
  6776. return Math.min(max, Math.max(min, value));
  6777. };
  6778. /**
  6779. * Returns the log2 of value.
  6780. */
  6781. Scalar.Log2 = function (value) {
  6782. return Math.log(value) * Math.LOG2E;
  6783. };
  6784. /**
  6785. * Loops the value, so that it is never larger than length and never smaller than 0.
  6786. *
  6787. * This is similar to the modulo operator but it works with floating point numbers.
  6788. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6789. * With t = 5 and length = 2.5, the result would be 0.0.
  6790. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6791. */
  6792. Scalar.Repeat = function (value, length) {
  6793. return value - Math.floor(value / length) * length;
  6794. };
  6795. /**
  6796. * Normalize the value between 0.0 and 1.0 using min and max values
  6797. */
  6798. Scalar.Normalize = function (value, min, max) {
  6799. return (value - min) / (max - min);
  6800. };
  6801. /**
  6802. * Denormalize the value from 0.0 and 1.0 using min and max values
  6803. */
  6804. Scalar.Denormalize = function (normalized, min, max) {
  6805. return (normalized * (max - min) + min);
  6806. };
  6807. /**
  6808. * Calculates the shortest difference between two given angles given in degrees.
  6809. */
  6810. Scalar.DeltaAngle = function (current, target) {
  6811. var num = Scalar.Repeat(target - current, 360.0);
  6812. if (num > 180.0) {
  6813. num -= 360.0;
  6814. }
  6815. return num;
  6816. };
  6817. /**
  6818. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6819. *
  6820. * The returned value will move back and forth between 0 and length
  6821. */
  6822. Scalar.PingPong = function (tx, length) {
  6823. var t = Scalar.Repeat(tx, length * 2.0);
  6824. return length - Math.abs(t - length);
  6825. };
  6826. /**
  6827. * Interpolates between min and max with smoothing at the limits.
  6828. *
  6829. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6830. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6831. */
  6832. Scalar.SmoothStep = function (from, to, tx) {
  6833. var t = Scalar.Clamp(tx);
  6834. t = -2.0 * t * t * t + 3.0 * t * t;
  6835. return to * t + from * (1.0 - t);
  6836. };
  6837. /**
  6838. * Moves a value current towards target.
  6839. *
  6840. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6841. * Negative values of maxDelta pushes the value away from target.
  6842. */
  6843. Scalar.MoveTowards = function (current, target, maxDelta) {
  6844. var result = 0;
  6845. if (Math.abs(target - current) <= maxDelta) {
  6846. result = target;
  6847. }
  6848. else {
  6849. result = current + Scalar.Sign(target - current) * maxDelta;
  6850. }
  6851. return result;
  6852. };
  6853. /**
  6854. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6855. *
  6856. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6857. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6858. */
  6859. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6860. var num = Scalar.DeltaAngle(current, target);
  6861. var result = 0;
  6862. if (-maxDelta < num && num < maxDelta) {
  6863. result = target;
  6864. }
  6865. else {
  6866. target = current + num;
  6867. result = Scalar.MoveTowards(current, target, maxDelta);
  6868. }
  6869. return result;
  6870. };
  6871. /**
  6872. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6873. */
  6874. Scalar.Lerp = function (start, end, amount) {
  6875. return start + ((end - start) * amount);
  6876. };
  6877. /**
  6878. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6879. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6880. */
  6881. Scalar.LerpAngle = function (start, end, amount) {
  6882. var num = Scalar.Repeat(end - start, 360.0);
  6883. if (num > 180.0) {
  6884. num -= 360.0;
  6885. }
  6886. return start + num * Scalar.Clamp(amount);
  6887. };
  6888. /**
  6889. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6890. */
  6891. Scalar.InverseLerp = function (a, b, value) {
  6892. var result = 0;
  6893. if (a != b) {
  6894. result = Scalar.Clamp((value - a) / (b - a));
  6895. }
  6896. else {
  6897. result = 0.0;
  6898. }
  6899. return result;
  6900. };
  6901. /**
  6902. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6903. */
  6904. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6905. var squared = amount * amount;
  6906. var cubed = amount * squared;
  6907. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6908. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6909. var part3 = (cubed - (2.0 * squared)) + amount;
  6910. var part4 = cubed - squared;
  6911. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6912. };
  6913. /**
  6914. * Returns a random float number between and min and max values
  6915. */
  6916. Scalar.RandomRange = function (min, max) {
  6917. if (min === max)
  6918. return min;
  6919. return ((Math.random() * (max - min)) + min);
  6920. };
  6921. /**
  6922. * This function returns percentage of a number in a given range.
  6923. *
  6924. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6925. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6926. */
  6927. Scalar.RangeToPercent = function (number, min, max) {
  6928. return ((number - min) / (max - min));
  6929. };
  6930. /**
  6931. * This function returns number that corresponds to the percentage in a given range.
  6932. *
  6933. * PercentToRange(0.34,0,100) will return 34.
  6934. */
  6935. Scalar.PercentToRange = function (percent, min, max) {
  6936. return ((max - min) * percent + min);
  6937. };
  6938. /**
  6939. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6940. * @param angle The angle to normalize in radian.
  6941. * @return The converted angle.
  6942. */
  6943. Scalar.NormalizeRadians = function (angle) {
  6944. // More precise but slower version kept for reference.
  6945. // angle = angle % Tools.TwoPi;
  6946. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6947. //if (angle > Math.PI) {
  6948. // angle -= Tools.TwoPi;
  6949. //}
  6950. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6951. return angle;
  6952. };
  6953. /**
  6954. * Two pi constants convenient for computation.
  6955. */
  6956. Scalar.TwoPi = Math.PI * 2;
  6957. return Scalar;
  6958. }());
  6959. BABYLON.Scalar = Scalar;
  6960. })(BABYLON || (BABYLON = {}));
  6961. //# sourceMappingURL=babylon.math.scalar.js.map
  6962. //# sourceMappingURL=babylon.mixins.js.map
  6963. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6964. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6965. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6966. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6967. //# sourceMappingURL=babylon.webgl2.js.map
  6968. var BABYLON;
  6969. (function (BABYLON) {
  6970. var __decoratorInitialStore = {};
  6971. var __mergedStore = {};
  6972. var _copySource = function (creationFunction, source, instanciate) {
  6973. var destination = creationFunction();
  6974. // Tags
  6975. if (BABYLON.Tags) {
  6976. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6977. }
  6978. var classStore = getMergedStore(destination);
  6979. // Properties
  6980. for (var property in classStore) {
  6981. var propertyDescriptor = classStore[property];
  6982. var sourceProperty = source[property];
  6983. var propertyType = propertyDescriptor.type;
  6984. if (sourceProperty !== undefined && sourceProperty !== null) {
  6985. switch (propertyType) {
  6986. case 0: // Value
  6987. case 6:// Mesh reference
  6988. destination[property] = sourceProperty;
  6989. break;
  6990. case 1:// Texture
  6991. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6992. break;
  6993. case 2: // Color3
  6994. case 3: // FresnelParameters
  6995. case 4: // Vector2
  6996. case 5: // Vector3
  6997. case 7: // Color Curves
  6998. case 10:// Quaternion
  6999. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7000. break;
  7001. }
  7002. }
  7003. }
  7004. return destination;
  7005. };
  7006. function getDirectStore(target) {
  7007. var classKey = target.getClassName();
  7008. if (!__decoratorInitialStore[classKey]) {
  7009. __decoratorInitialStore[classKey] = {};
  7010. }
  7011. return __decoratorInitialStore[classKey];
  7012. }
  7013. /**
  7014. * Return the list of properties flagged as serializable
  7015. * @param target: host object
  7016. */
  7017. function getMergedStore(target) {
  7018. var classKey = target.getClassName();
  7019. if (__mergedStore[classKey]) {
  7020. return __mergedStore[classKey];
  7021. }
  7022. __mergedStore[classKey] = {};
  7023. var store = __mergedStore[classKey];
  7024. var currentTarget = target;
  7025. var currentKey = classKey;
  7026. while (currentKey) {
  7027. var initialStore = __decoratorInitialStore[currentKey];
  7028. for (var property in initialStore) {
  7029. store[property] = initialStore[property];
  7030. }
  7031. var parent_1 = void 0;
  7032. var done = false;
  7033. do {
  7034. parent_1 = Object.getPrototypeOf(currentTarget);
  7035. if (!parent_1.getClassName) {
  7036. done = true;
  7037. break;
  7038. }
  7039. if (parent_1.getClassName() !== currentKey) {
  7040. break;
  7041. }
  7042. currentTarget = parent_1;
  7043. } while (parent_1);
  7044. if (done) {
  7045. break;
  7046. }
  7047. currentKey = parent_1.getClassName();
  7048. currentTarget = parent_1;
  7049. }
  7050. return store;
  7051. }
  7052. function generateSerializableMember(type, sourceName) {
  7053. return function (target, propertyKey) {
  7054. var classStore = getDirectStore(target);
  7055. if (!classStore[propertyKey]) {
  7056. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7057. }
  7058. };
  7059. }
  7060. function generateExpandMember(setCallback, targetKey) {
  7061. if (targetKey === void 0) { targetKey = null; }
  7062. return function (target, propertyKey) {
  7063. var key = targetKey || ("_" + propertyKey);
  7064. Object.defineProperty(target, propertyKey, {
  7065. get: function () {
  7066. return this[key];
  7067. },
  7068. set: function (value) {
  7069. if (this[key] === value) {
  7070. return;
  7071. }
  7072. this[key] = value;
  7073. target[setCallback].apply(this);
  7074. },
  7075. enumerable: true,
  7076. configurable: true
  7077. });
  7078. };
  7079. }
  7080. function expandToProperty(callback, targetKey) {
  7081. if (targetKey === void 0) { targetKey = null; }
  7082. return generateExpandMember(callback, targetKey);
  7083. }
  7084. BABYLON.expandToProperty = expandToProperty;
  7085. function serialize(sourceName) {
  7086. return generateSerializableMember(0, sourceName); // value member
  7087. }
  7088. BABYLON.serialize = serialize;
  7089. function serializeAsTexture(sourceName) {
  7090. return generateSerializableMember(1, sourceName); // texture member
  7091. }
  7092. BABYLON.serializeAsTexture = serializeAsTexture;
  7093. function serializeAsColor3(sourceName) {
  7094. return generateSerializableMember(2, sourceName); // color3 member
  7095. }
  7096. BABYLON.serializeAsColor3 = serializeAsColor3;
  7097. function serializeAsFresnelParameters(sourceName) {
  7098. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7099. }
  7100. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7101. function serializeAsVector2(sourceName) {
  7102. return generateSerializableMember(4, sourceName); // vector2 member
  7103. }
  7104. BABYLON.serializeAsVector2 = serializeAsVector2;
  7105. function serializeAsVector3(sourceName) {
  7106. return generateSerializableMember(5, sourceName); // vector3 member
  7107. }
  7108. BABYLON.serializeAsVector3 = serializeAsVector3;
  7109. function serializeAsMeshReference(sourceName) {
  7110. return generateSerializableMember(6, sourceName); // mesh reference member
  7111. }
  7112. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7113. function serializeAsColorCurves(sourceName) {
  7114. return generateSerializableMember(7, sourceName); // color curves
  7115. }
  7116. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7117. function serializeAsColor4(sourceName) {
  7118. return generateSerializableMember(8, sourceName); // color 4
  7119. }
  7120. BABYLON.serializeAsColor4 = serializeAsColor4;
  7121. function serializeAsImageProcessingConfiguration(sourceName) {
  7122. return generateSerializableMember(9, sourceName); // image processing
  7123. }
  7124. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7125. function serializeAsQuaternion(sourceName) {
  7126. return generateSerializableMember(10, sourceName); // quaternion member
  7127. }
  7128. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7129. var SerializationHelper = /** @class */ (function () {
  7130. function SerializationHelper() {
  7131. }
  7132. SerializationHelper.Serialize = function (entity, serializationObject) {
  7133. if (!serializationObject) {
  7134. serializationObject = {};
  7135. }
  7136. // Tags
  7137. if (BABYLON.Tags) {
  7138. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7139. }
  7140. var serializedProperties = getMergedStore(entity);
  7141. // Properties
  7142. for (var property in serializedProperties) {
  7143. var propertyDescriptor = serializedProperties[property];
  7144. var targetPropertyName = propertyDescriptor.sourceName || property;
  7145. var propertyType = propertyDescriptor.type;
  7146. var sourceProperty = entity[property];
  7147. if (sourceProperty !== undefined && sourceProperty !== null) {
  7148. switch (propertyType) {
  7149. case 0:// Value
  7150. serializationObject[targetPropertyName] = sourceProperty;
  7151. break;
  7152. case 1:// Texture
  7153. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7154. break;
  7155. case 2:// Color3
  7156. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7157. break;
  7158. case 3:// FresnelParameters
  7159. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7160. break;
  7161. case 4:// Vector2
  7162. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7163. break;
  7164. case 5:// Vector3
  7165. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7166. break;
  7167. case 6:// Mesh reference
  7168. serializationObject[targetPropertyName] = sourceProperty.id;
  7169. break;
  7170. case 7:// Color Curves
  7171. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7172. break;
  7173. case 8:// Color 4
  7174. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7175. break;
  7176. case 9:// Image Processing
  7177. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7178. break;
  7179. }
  7180. }
  7181. }
  7182. return serializationObject;
  7183. };
  7184. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7185. if (rootUrl === void 0) { rootUrl = null; }
  7186. var destination = creationFunction();
  7187. if (!rootUrl) {
  7188. rootUrl = "";
  7189. }
  7190. // Tags
  7191. if (BABYLON.Tags) {
  7192. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7193. }
  7194. var classStore = getMergedStore(destination);
  7195. // Properties
  7196. for (var property in classStore) {
  7197. var propertyDescriptor = classStore[property];
  7198. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7199. var propertyType = propertyDescriptor.type;
  7200. if (sourceProperty !== undefined && sourceProperty !== null) {
  7201. var dest = destination;
  7202. switch (propertyType) {
  7203. case 0:// Value
  7204. dest[property] = sourceProperty;
  7205. break;
  7206. case 1:// Texture
  7207. if (scene) {
  7208. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7209. }
  7210. break;
  7211. case 2:// Color3
  7212. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7213. break;
  7214. case 3:// FresnelParameters
  7215. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7216. break;
  7217. case 4:// Vector2
  7218. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7219. break;
  7220. case 5:// Vector3
  7221. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7222. break;
  7223. case 6:// Mesh reference
  7224. if (scene) {
  7225. dest[property] = scene.getLastMeshByID(sourceProperty);
  7226. }
  7227. break;
  7228. case 7:// Color Curves
  7229. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7230. break;
  7231. case 8:// Color 4
  7232. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7233. break;
  7234. case 9:// Image Processing
  7235. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7236. break;
  7237. }
  7238. }
  7239. }
  7240. return destination;
  7241. };
  7242. SerializationHelper.Clone = function (creationFunction, source) {
  7243. return _copySource(creationFunction, source, false);
  7244. };
  7245. SerializationHelper.Instanciate = function (creationFunction, source) {
  7246. return _copySource(creationFunction, source, true);
  7247. };
  7248. return SerializationHelper;
  7249. }());
  7250. BABYLON.SerializationHelper = SerializationHelper;
  7251. })(BABYLON || (BABYLON = {}));
  7252. //# sourceMappingURL=babylon.decorators.js.map
  7253. var BABYLON;
  7254. (function (BABYLON) {
  7255. /**
  7256. * Wrapper class for promise with external resolve and reject.
  7257. */
  7258. var Deferred = /** @class */ (function () {
  7259. /**
  7260. * Constructor for this deferred object.
  7261. */
  7262. function Deferred() {
  7263. var _this = this;
  7264. this.promise = new Promise(function (resolve, reject) {
  7265. _this._resolve = resolve;
  7266. _this._reject = reject;
  7267. });
  7268. }
  7269. Object.defineProperty(Deferred.prototype, "resolve", {
  7270. /**
  7271. * The resolve method of the promise associated with this deferred object.
  7272. */
  7273. get: function () {
  7274. return this._resolve;
  7275. },
  7276. enumerable: true,
  7277. configurable: true
  7278. });
  7279. Object.defineProperty(Deferred.prototype, "reject", {
  7280. /**
  7281. * The reject method of the promise associated with this deferred object.
  7282. */
  7283. get: function () {
  7284. return this._reject;
  7285. },
  7286. enumerable: true,
  7287. configurable: true
  7288. });
  7289. return Deferred;
  7290. }());
  7291. BABYLON.Deferred = Deferred;
  7292. })(BABYLON || (BABYLON = {}));
  7293. //# sourceMappingURL=babylon.deferred.js.map
  7294. var BABYLON;
  7295. (function (BABYLON) {
  7296. /**
  7297. * A class serves as a medium between the observable and its observers
  7298. */
  7299. var EventState = /** @class */ (function () {
  7300. /**
  7301. * Create a new EventState
  7302. * @param mask defines the mask associated with this state
  7303. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7304. * @param target defines the original target of the state
  7305. * @param currentTarget defines the current target of the state
  7306. */
  7307. function EventState(mask, skipNextObservers, target, currentTarget) {
  7308. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7309. this.initalize(mask, skipNextObservers, target, currentTarget);
  7310. }
  7311. /**
  7312. * Initialize the current event state
  7313. * @param mask defines the mask associated with this state
  7314. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7315. * @param target defines the original target of the state
  7316. * @param currentTarget defines the current target of the state
  7317. * @returns the current event state
  7318. */
  7319. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7320. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7321. this.mask = mask;
  7322. this.skipNextObservers = skipNextObservers;
  7323. this.target = target;
  7324. this.currentTarget = currentTarget;
  7325. return this;
  7326. };
  7327. return EventState;
  7328. }());
  7329. BABYLON.EventState = EventState;
  7330. /**
  7331. * Represent an Observer registered to a given Observable object.
  7332. */
  7333. var Observer = /** @class */ (function () {
  7334. /**
  7335. * Creates a new observer
  7336. * @param callback defines the callback to call when the observer is notified
  7337. * @param mask defines the mask of the observer (used to filter notifications)
  7338. * @param scope defines the current scope used to restore the JS context
  7339. */
  7340. function Observer(
  7341. /**
  7342. * Defines the callback to call when the observer is notified
  7343. */
  7344. callback,
  7345. /**
  7346. * Defines the mask of the observer (used to filter notifications)
  7347. */
  7348. mask,
  7349. /**
  7350. * Defines the current scope used to restore the JS context
  7351. */
  7352. scope) {
  7353. if (scope === void 0) { scope = null; }
  7354. this.callback = callback;
  7355. this.mask = mask;
  7356. this.scope = scope;
  7357. /** @ignore */
  7358. this._willBeUnregistered = false;
  7359. /**
  7360. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7361. */
  7362. this.unregisterOnNextCall = false;
  7363. }
  7364. return Observer;
  7365. }());
  7366. BABYLON.Observer = Observer;
  7367. /**
  7368. * Represent a list of observers registered to multiple Observables object.
  7369. */
  7370. var MultiObserver = /** @class */ (function () {
  7371. function MultiObserver() {
  7372. }
  7373. /**
  7374. * Release associated resources
  7375. */
  7376. MultiObserver.prototype.dispose = function () {
  7377. if (this._observers && this._observables) {
  7378. for (var index = 0; index < this._observers.length; index++) {
  7379. this._observables[index].remove(this._observers[index]);
  7380. }
  7381. }
  7382. this._observers = null;
  7383. this._observables = null;
  7384. };
  7385. /**
  7386. * Raise a callback when one of the observable will notify
  7387. * @param observables defines a list of observables to watch
  7388. * @param callback defines the callback to call on notification
  7389. * @param mask defines the mask used to filter notifications
  7390. * @param scope defines the current scope used to restore the JS context
  7391. * @returns the new MultiObserver
  7392. */
  7393. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7394. if (mask === void 0) { mask = -1; }
  7395. if (scope === void 0) { scope = null; }
  7396. var result = new MultiObserver();
  7397. result._observers = new Array();
  7398. result._observables = observables;
  7399. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7400. var observable = observables_1[_i];
  7401. var observer = observable.add(callback, mask, false, scope);
  7402. if (observer) {
  7403. result._observers.push(observer);
  7404. }
  7405. }
  7406. return result;
  7407. };
  7408. return MultiObserver;
  7409. }());
  7410. BABYLON.MultiObserver = MultiObserver;
  7411. /**
  7412. * The Observable class is a simple implementation of the Observable pattern.
  7413. * 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.
  7414. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7415. * 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).
  7416. * 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.
  7417. */
  7418. var Observable = /** @class */ (function () {
  7419. /**
  7420. * Creates a new observable
  7421. * @param onObserverAdded defines a callback to call when a new observer is added
  7422. */
  7423. function Observable(onObserverAdded) {
  7424. this._observers = new Array();
  7425. this._eventState = new EventState(0);
  7426. if (onObserverAdded) {
  7427. this._onObserverAdded = onObserverAdded;
  7428. }
  7429. }
  7430. /**
  7431. * Create a new Observer with the specified callback
  7432. * @param callback the callback that will be executed for that Observer
  7433. * @param mask the mask used to filter observers
  7434. * @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.
  7435. * @param scope optional scope for the callback to be called from
  7436. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7437. * @returns the new observer created for the callback
  7438. */
  7439. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7440. if (mask === void 0) { mask = -1; }
  7441. if (insertFirst === void 0) { insertFirst = false; }
  7442. if (scope === void 0) { scope = null; }
  7443. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7444. if (!callback) {
  7445. return null;
  7446. }
  7447. var observer = new Observer(callback, mask, scope);
  7448. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7449. if (insertFirst) {
  7450. this._observers.unshift(observer);
  7451. }
  7452. else {
  7453. this._observers.push(observer);
  7454. }
  7455. if (this._onObserverAdded) {
  7456. this._onObserverAdded(observer);
  7457. }
  7458. return observer;
  7459. };
  7460. /**
  7461. * Remove an Observer from the Observable object
  7462. * @param observer the instance of the Observer to remove
  7463. * @returns false if it doesn't belong to this Observable
  7464. */
  7465. Observable.prototype.remove = function (observer) {
  7466. if (!observer) {
  7467. return false;
  7468. }
  7469. var index = this._observers.indexOf(observer);
  7470. if (index !== -1) {
  7471. this._observers.splice(index, 1);
  7472. return true;
  7473. }
  7474. return false;
  7475. };
  7476. /**
  7477. * Remove a callback from the Observable object
  7478. * @param callback the callback to remove
  7479. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7480. * @returns false if it doesn't belong to this Observable
  7481. */
  7482. Observable.prototype.removeCallback = function (callback, scope) {
  7483. for (var index = 0; index < this._observers.length; index++) {
  7484. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7485. this._observers.splice(index, 1);
  7486. return true;
  7487. }
  7488. }
  7489. return false;
  7490. };
  7491. Observable.prototype._deferUnregister = function (observer) {
  7492. var _this = this;
  7493. observer.unregisterOnNextCall = false;
  7494. observer._willBeUnregistered = true;
  7495. BABYLON.Tools.SetImmediate(function () {
  7496. _this.remove(observer);
  7497. });
  7498. };
  7499. /**
  7500. * Notify all Observers by calling their respective callback with the given data
  7501. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7502. * @param eventData defines the data to send to all observers
  7503. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7504. * @param target defines the original target of the state
  7505. * @param currentTarget defines the current target of the state
  7506. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7507. */
  7508. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7509. if (mask === void 0) { mask = -1; }
  7510. if (!this._observers.length) {
  7511. return true;
  7512. }
  7513. var state = this._eventState;
  7514. state.mask = mask;
  7515. state.target = target;
  7516. state.currentTarget = currentTarget;
  7517. state.skipNextObservers = false;
  7518. state.lastReturnValue = eventData;
  7519. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7520. var obs = _a[_i];
  7521. if (obs._willBeUnregistered) {
  7522. continue;
  7523. }
  7524. if (obs.mask & mask) {
  7525. if (obs.scope) {
  7526. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7527. }
  7528. else {
  7529. state.lastReturnValue = obs.callback(eventData, state);
  7530. }
  7531. if (obs.unregisterOnNextCall) {
  7532. this._deferUnregister(obs);
  7533. }
  7534. }
  7535. if (state.skipNextObservers) {
  7536. return false;
  7537. }
  7538. }
  7539. return true;
  7540. };
  7541. /**
  7542. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7543. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7544. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7545. * and it is crucial that all callbacks will be executed.
  7546. * The order of the callbacks is kept, callbacks are not executed parallel.
  7547. *
  7548. * @param eventData The data to be sent to each callback
  7549. * @param mask is used to filter observers defaults to -1
  7550. * @param target defines the callback target (see EventState)
  7551. * @param currentTarget defines he current object in the bubbling phase
  7552. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7553. */
  7554. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7555. var _this = this;
  7556. if (mask === void 0) { mask = -1; }
  7557. // create an empty promise
  7558. var p = Promise.resolve(eventData);
  7559. // no observers? return this promise.
  7560. if (!this._observers.length) {
  7561. return p;
  7562. }
  7563. var state = this._eventState;
  7564. state.mask = mask;
  7565. state.target = target;
  7566. state.currentTarget = currentTarget;
  7567. state.skipNextObservers = false;
  7568. // execute one callback after another (not using Promise.all, the order is important)
  7569. this._observers.forEach(function (obs) {
  7570. if (state.skipNextObservers) {
  7571. return;
  7572. }
  7573. if (obs._willBeUnregistered) {
  7574. return;
  7575. }
  7576. if (obs.mask & mask) {
  7577. if (obs.scope) {
  7578. p = p.then(function (lastReturnedValue) {
  7579. state.lastReturnValue = lastReturnedValue;
  7580. return obs.callback.apply(obs.scope, [eventData, state]);
  7581. });
  7582. }
  7583. else {
  7584. p = p.then(function (lastReturnedValue) {
  7585. state.lastReturnValue = lastReturnedValue;
  7586. return obs.callback(eventData, state);
  7587. });
  7588. }
  7589. if (obs.unregisterOnNextCall) {
  7590. _this._deferUnregister(obs);
  7591. }
  7592. }
  7593. });
  7594. // return the eventData
  7595. return p.then(function () { return eventData; });
  7596. };
  7597. /**
  7598. * Notify a specific observer
  7599. * @param observer defines the observer to notify
  7600. * @param eventData defines the data to be sent to each callback
  7601. * @param mask is used to filter observers defaults to -1
  7602. */
  7603. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7604. if (mask === void 0) { mask = -1; }
  7605. var state = this._eventState;
  7606. state.mask = mask;
  7607. state.skipNextObservers = false;
  7608. observer.callback(eventData, state);
  7609. };
  7610. /**
  7611. * Gets a boolean indicating if the observable has at least one observer
  7612. * @returns true is the Observable has at least one Observer registered
  7613. */
  7614. Observable.prototype.hasObservers = function () {
  7615. return this._observers.length > 0;
  7616. };
  7617. /**
  7618. * Clear the list of observers
  7619. */
  7620. Observable.prototype.clear = function () {
  7621. this._observers = new Array();
  7622. this._onObserverAdded = null;
  7623. };
  7624. /**
  7625. * Clone the current observable
  7626. * @returns a new observable
  7627. */
  7628. Observable.prototype.clone = function () {
  7629. var result = new Observable();
  7630. result._observers = this._observers.slice(0);
  7631. return result;
  7632. };
  7633. /**
  7634. * Does this observable handles observer registered with a given mask
  7635. * @param mask defines the mask to be tested
  7636. * @return whether or not one observer registered with the given mask is handeled
  7637. **/
  7638. Observable.prototype.hasSpecificMask = function (mask) {
  7639. if (mask === void 0) { mask = -1; }
  7640. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7641. var obs = _a[_i];
  7642. if (obs.mask & mask || obs.mask === mask) {
  7643. return true;
  7644. }
  7645. }
  7646. return false;
  7647. };
  7648. return Observable;
  7649. }());
  7650. BABYLON.Observable = Observable;
  7651. })(BABYLON || (BABYLON = {}));
  7652. //# sourceMappingURL=babylon.observable.js.map
  7653. var BABYLON;
  7654. (function (BABYLON) {
  7655. var SmartArray = /** @class */ (function () {
  7656. function SmartArray(capacity) {
  7657. this.length = 0;
  7658. this.data = new Array(capacity);
  7659. this._id = SmartArray._GlobalId++;
  7660. }
  7661. SmartArray.prototype.push = function (value) {
  7662. this.data[this.length++] = value;
  7663. if (this.length > this.data.length) {
  7664. this.data.length *= 2;
  7665. }
  7666. };
  7667. SmartArray.prototype.forEach = function (func) {
  7668. for (var index = 0; index < this.length; index++) {
  7669. func(this.data[index]);
  7670. }
  7671. };
  7672. SmartArray.prototype.sort = function (compareFn) {
  7673. this.data.sort(compareFn);
  7674. };
  7675. SmartArray.prototype.reset = function () {
  7676. this.length = 0;
  7677. };
  7678. SmartArray.prototype.dispose = function () {
  7679. this.reset();
  7680. if (this.data) {
  7681. this.data.length = 0;
  7682. this.data = [];
  7683. }
  7684. };
  7685. SmartArray.prototype.concat = function (array) {
  7686. if (array.length === 0) {
  7687. return;
  7688. }
  7689. if (this.length + array.length > this.data.length) {
  7690. this.data.length = (this.length + array.length) * 2;
  7691. }
  7692. for (var index = 0; index < array.length; index++) {
  7693. this.data[this.length++] = (array.data || array)[index];
  7694. }
  7695. };
  7696. SmartArray.prototype.indexOf = function (value) {
  7697. var position = this.data.indexOf(value);
  7698. if (position >= this.length) {
  7699. return -1;
  7700. }
  7701. return position;
  7702. };
  7703. SmartArray.prototype.contains = function (value) {
  7704. return this.data.indexOf(value) !== -1;
  7705. };
  7706. // Statics
  7707. SmartArray._GlobalId = 0;
  7708. return SmartArray;
  7709. }());
  7710. BABYLON.SmartArray = SmartArray;
  7711. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7712. __extends(SmartArrayNoDuplicate, _super);
  7713. function SmartArrayNoDuplicate() {
  7714. var _this = _super !== null && _super.apply(this, arguments) || this;
  7715. _this._duplicateId = 0;
  7716. return _this;
  7717. }
  7718. SmartArrayNoDuplicate.prototype.push = function (value) {
  7719. _super.prototype.push.call(this, value);
  7720. if (!value.__smartArrayFlags) {
  7721. value.__smartArrayFlags = {};
  7722. }
  7723. value.__smartArrayFlags[this._id] = this._duplicateId;
  7724. };
  7725. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7726. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7727. return false;
  7728. }
  7729. this.push(value);
  7730. return true;
  7731. };
  7732. SmartArrayNoDuplicate.prototype.reset = function () {
  7733. _super.prototype.reset.call(this);
  7734. this._duplicateId++;
  7735. };
  7736. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7737. if (array.length === 0) {
  7738. return;
  7739. }
  7740. if (this.length + array.length > this.data.length) {
  7741. this.data.length = (this.length + array.length) * 2;
  7742. }
  7743. for (var index = 0; index < array.length; index++) {
  7744. var item = (array.data || array)[index];
  7745. this.pushNoDuplicate(item);
  7746. }
  7747. };
  7748. return SmartArrayNoDuplicate;
  7749. }(SmartArray));
  7750. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7751. })(BABYLON || (BABYLON = {}));
  7752. //# sourceMappingURL=babylon.smartArray.js.map
  7753. var BABYLON;
  7754. (function (BABYLON) {
  7755. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7756. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7757. var LoadFileError = /** @class */ (function (_super) {
  7758. __extends(LoadFileError, _super);
  7759. function LoadFileError(message, request) {
  7760. var _this = _super.call(this, message) || this;
  7761. _this.request = request;
  7762. _this.name = "LoadFileError";
  7763. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7764. return _this;
  7765. }
  7766. // Polyfill for Object.setPrototypeOf if necessary.
  7767. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7768. return LoadFileError;
  7769. }(Error));
  7770. BABYLON.LoadFileError = LoadFileError;
  7771. var RetryStrategy = /** @class */ (function () {
  7772. function RetryStrategy() {
  7773. }
  7774. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7775. if (maxRetries === void 0) { maxRetries = 3; }
  7776. if (baseInterval === void 0) { baseInterval = 500; }
  7777. return function (url, request, retryIndex) {
  7778. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7779. return -1;
  7780. }
  7781. return Math.pow(2, retryIndex) * baseInterval;
  7782. };
  7783. };
  7784. return RetryStrategy;
  7785. }());
  7786. BABYLON.RetryStrategy = RetryStrategy;
  7787. // Screenshots
  7788. var screenshotCanvas;
  7789. var cloneValue = function (source, destinationObject) {
  7790. if (!source)
  7791. return null;
  7792. if (source instanceof BABYLON.Mesh) {
  7793. return null;
  7794. }
  7795. if (source instanceof BABYLON.SubMesh) {
  7796. return source.clone(destinationObject);
  7797. }
  7798. else if (source.clone) {
  7799. return source.clone();
  7800. }
  7801. return null;
  7802. };
  7803. var Tools = /** @class */ (function () {
  7804. function Tools() {
  7805. }
  7806. /**
  7807. * Interpolates between a and b via alpha
  7808. * @param a The lower value (returned when alpha = 0)
  7809. * @param b The upper value (returned when alpha = 1)
  7810. * @param alpha The interpolation-factor
  7811. * @return The mixed value
  7812. */
  7813. Tools.Mix = function (a, b, alpha) {
  7814. return a * (1 - alpha) + b * alpha;
  7815. };
  7816. Tools.Instantiate = function (className) {
  7817. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7818. return Tools.RegisteredExternalClasses[className];
  7819. }
  7820. var arr = className.split(".");
  7821. var fn = (window || this);
  7822. for (var i = 0, len = arr.length; i < len; i++) {
  7823. fn = fn[arr[i]];
  7824. }
  7825. if (typeof fn !== "function") {
  7826. return null;
  7827. }
  7828. return fn;
  7829. };
  7830. /**
  7831. * Provides a slice function that will work even on IE
  7832. * @param data defines the array to slice
  7833. * @returns the new sliced array
  7834. */
  7835. Tools.Slice = function (data) {
  7836. if (data.slice) {
  7837. return data.slice();
  7838. }
  7839. return Array.prototype.slice.call(data);
  7840. };
  7841. Tools.SetImmediate = function (action) {
  7842. if (window.setImmediate) {
  7843. window.setImmediate(action);
  7844. }
  7845. else {
  7846. setTimeout(action, 1);
  7847. }
  7848. };
  7849. Tools.IsExponentOfTwo = function (value) {
  7850. var count = 1;
  7851. do {
  7852. count *= 2;
  7853. } while (count < value);
  7854. return count === value;
  7855. };
  7856. /**
  7857. * Find the next highest power of two.
  7858. * @param x Number to start search from.
  7859. * @return Next highest power of two.
  7860. */
  7861. Tools.CeilingPOT = function (x) {
  7862. x--;
  7863. x |= x >> 1;
  7864. x |= x >> 2;
  7865. x |= x >> 4;
  7866. x |= x >> 8;
  7867. x |= x >> 16;
  7868. x++;
  7869. return x;
  7870. };
  7871. /**
  7872. * Find the next lowest power of two.
  7873. * @param x Number to start search from.
  7874. * @return Next lowest power of two.
  7875. */
  7876. Tools.FloorPOT = function (x) {
  7877. x = x | (x >> 1);
  7878. x = x | (x >> 2);
  7879. x = x | (x >> 4);
  7880. x = x | (x >> 8);
  7881. x = x | (x >> 16);
  7882. return x - (x >> 1);
  7883. };
  7884. /**
  7885. * Find the nearest power of two.
  7886. * @param x Number to start search from.
  7887. * @return Next nearest power of two.
  7888. */
  7889. Tools.NearestPOT = function (x) {
  7890. var c = Tools.CeilingPOT(x);
  7891. var f = Tools.FloorPOT(x);
  7892. return (c - x) > (x - f) ? f : c;
  7893. };
  7894. Tools.GetExponentOfTwo = function (value, max, mode) {
  7895. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7896. var pot;
  7897. switch (mode) {
  7898. case BABYLON.Engine.SCALEMODE_FLOOR:
  7899. pot = Tools.FloorPOT(value);
  7900. break;
  7901. case BABYLON.Engine.SCALEMODE_NEAREST:
  7902. pot = Tools.NearestPOT(value);
  7903. break;
  7904. case BABYLON.Engine.SCALEMODE_CEILING:
  7905. default:
  7906. pot = Tools.CeilingPOT(value);
  7907. break;
  7908. }
  7909. return Math.min(pot, max);
  7910. };
  7911. Tools.GetFilename = function (path) {
  7912. var index = path.lastIndexOf("/");
  7913. if (index < 0)
  7914. return path;
  7915. return path.substring(index + 1);
  7916. };
  7917. /**
  7918. * Extracts the "folder" part of a path (everything before the filename).
  7919. * @param uri The URI to extract the info from
  7920. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7921. * @returns The "folder" part of the path
  7922. */
  7923. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7924. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7925. var index = uri.lastIndexOf("/");
  7926. if (index < 0) {
  7927. if (returnUnchangedIfNoSlash) {
  7928. return uri;
  7929. }
  7930. return "";
  7931. }
  7932. return uri.substring(0, index + 1);
  7933. };
  7934. Tools.GetDOMTextContent = function (element) {
  7935. var result = "";
  7936. var child = element.firstChild;
  7937. while (child) {
  7938. if (child.nodeType === 3) {
  7939. result += child.textContent;
  7940. }
  7941. child = child.nextSibling;
  7942. }
  7943. return result;
  7944. };
  7945. Tools.ToDegrees = function (angle) {
  7946. return angle * 180 / Math.PI;
  7947. };
  7948. Tools.ToRadians = function (angle) {
  7949. return angle * Math.PI / 180;
  7950. };
  7951. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7952. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7953. var output = "";
  7954. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7955. var i = 0;
  7956. var bytes = new Uint8Array(buffer);
  7957. while (i < bytes.length) {
  7958. chr1 = bytes[i++];
  7959. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7960. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7961. enc1 = chr1 >> 2;
  7962. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7963. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7964. enc4 = chr3 & 63;
  7965. if (isNaN(chr2)) {
  7966. enc3 = enc4 = 64;
  7967. }
  7968. else if (isNaN(chr3)) {
  7969. enc4 = 64;
  7970. }
  7971. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7972. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7973. }
  7974. return "data:image/png;base64," + output;
  7975. };
  7976. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7977. if (bias === void 0) { bias = null; }
  7978. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7979. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7980. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7981. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7982. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7983. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7984. }
  7985. if (bias) {
  7986. minimum.x -= minimum.x * bias.x + bias.y;
  7987. minimum.y -= minimum.y * bias.x + bias.y;
  7988. minimum.z -= minimum.z * bias.x + bias.y;
  7989. maximum.x += maximum.x * bias.x + bias.y;
  7990. maximum.y += maximum.y * bias.x + bias.y;
  7991. maximum.z += maximum.z * bias.x + bias.y;
  7992. }
  7993. return {
  7994. minimum: minimum,
  7995. maximum: maximum
  7996. };
  7997. };
  7998. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7999. if (bias === void 0) { bias = null; }
  8000. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8001. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8002. if (!stride) {
  8003. stride = 3;
  8004. }
  8005. for (var index = start; index < start + count; index++) {
  8006. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8007. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8008. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8009. }
  8010. if (bias) {
  8011. minimum.x -= minimum.x * bias.x + bias.y;
  8012. minimum.y -= minimum.y * bias.x + bias.y;
  8013. minimum.z -= minimum.z * bias.x + bias.y;
  8014. maximum.x += maximum.x * bias.x + bias.y;
  8015. maximum.y += maximum.y * bias.x + bias.y;
  8016. maximum.z += maximum.z * bias.x + bias.y;
  8017. }
  8018. return {
  8019. minimum: minimum,
  8020. maximum: maximum
  8021. };
  8022. };
  8023. Tools.Vector2ArrayFeeder = function (array) {
  8024. return function (index) {
  8025. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8026. var length = isFloatArray ? array.length / 2 : array.length;
  8027. if (index >= length) {
  8028. return null;
  8029. }
  8030. if (isFloatArray) {
  8031. var fa = array;
  8032. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8033. }
  8034. var a = array;
  8035. return a[index];
  8036. };
  8037. };
  8038. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8039. if (bias === void 0) { bias = null; }
  8040. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8041. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8042. var i = 0;
  8043. var cur = feeder(i++);
  8044. while (cur) {
  8045. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8046. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8047. cur = feeder(i++);
  8048. }
  8049. if (bias) {
  8050. minimum.x -= minimum.x * bias.x + bias.y;
  8051. minimum.y -= minimum.y * bias.x + bias.y;
  8052. maximum.x += maximum.x * bias.x + bias.y;
  8053. maximum.y += maximum.y * bias.x + bias.y;
  8054. }
  8055. return {
  8056. minimum: minimum,
  8057. maximum: maximum
  8058. };
  8059. };
  8060. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8061. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8062. return null;
  8063. return Array.isArray(obj) ? obj : [obj];
  8064. };
  8065. // Misc.
  8066. Tools.GetPointerPrefix = function () {
  8067. var eventPrefix = "pointer";
  8068. // Check if pointer events are supported
  8069. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8070. eventPrefix = "mouse";
  8071. }
  8072. return eventPrefix;
  8073. };
  8074. /**
  8075. * @param func - the function to be called
  8076. * @param requester - the object that will request the next frame. Falls back to window.
  8077. */
  8078. Tools.QueueNewFrame = function (func, requester) {
  8079. if (!Tools.IsWindowObjectExist()) {
  8080. return setTimeout(func, 16);
  8081. }
  8082. if (!requester) {
  8083. requester = window;
  8084. }
  8085. if (requester.requestAnimationFrame) {
  8086. return requester.requestAnimationFrame(func);
  8087. }
  8088. else if (requester.msRequestAnimationFrame) {
  8089. return requester.msRequestAnimationFrame(func);
  8090. }
  8091. else if (requester.webkitRequestAnimationFrame) {
  8092. return requester.webkitRequestAnimationFrame(func);
  8093. }
  8094. else if (requester.mozRequestAnimationFrame) {
  8095. return requester.mozRequestAnimationFrame(func);
  8096. }
  8097. else if (requester.oRequestAnimationFrame) {
  8098. return requester.oRequestAnimationFrame(func);
  8099. }
  8100. else {
  8101. return window.setTimeout(func, 16);
  8102. }
  8103. };
  8104. Tools.RequestFullscreen = function (element) {
  8105. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8106. if (!requestFunction)
  8107. return;
  8108. requestFunction.call(element);
  8109. };
  8110. Tools.ExitFullscreen = function () {
  8111. if (document.exitFullscreen) {
  8112. document.exitFullscreen();
  8113. }
  8114. else if (document.mozCancelFullScreen) {
  8115. document.mozCancelFullScreen();
  8116. }
  8117. else if (document.webkitCancelFullScreen) {
  8118. document.webkitCancelFullScreen();
  8119. }
  8120. else if (document.msCancelFullScreen) {
  8121. document.msCancelFullScreen();
  8122. }
  8123. };
  8124. Tools.SetCorsBehavior = function (url, element) {
  8125. if (url && url.indexOf("data:") === 0) {
  8126. return;
  8127. }
  8128. if (Tools.CorsBehavior) {
  8129. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8130. element.crossOrigin = Tools.CorsBehavior;
  8131. }
  8132. else {
  8133. var result = Tools.CorsBehavior(url);
  8134. if (result) {
  8135. element.crossOrigin = result;
  8136. }
  8137. }
  8138. }
  8139. };
  8140. // External files
  8141. Tools.CleanUrl = function (url) {
  8142. url = url.replace(/#/mg, "%23");
  8143. return url;
  8144. };
  8145. Tools.LoadImage = function (url, onLoad, onError, database) {
  8146. if (url instanceof ArrayBuffer) {
  8147. url = Tools.EncodeArrayBufferTobase64(url);
  8148. }
  8149. url = Tools.CleanUrl(url);
  8150. url = Tools.PreprocessUrl(url);
  8151. var img = new Image();
  8152. Tools.SetCorsBehavior(url, img);
  8153. var loadHandler = function () {
  8154. img.removeEventListener("load", loadHandler);
  8155. img.removeEventListener("error", errorHandler);
  8156. onLoad(img);
  8157. };
  8158. var errorHandler = function (err) {
  8159. img.removeEventListener("load", loadHandler);
  8160. img.removeEventListener("error", errorHandler);
  8161. Tools.Error("Error while trying to load image: " + url);
  8162. if (onError) {
  8163. onError("Error while trying to load image: " + url, err);
  8164. }
  8165. };
  8166. img.addEventListener("load", loadHandler);
  8167. img.addEventListener("error", errorHandler);
  8168. var noIndexedDB = function () {
  8169. img.src = url;
  8170. };
  8171. var loadFromIndexedDB = function () {
  8172. if (database) {
  8173. database.loadImageFromDB(url, img);
  8174. }
  8175. };
  8176. //ANY database to do!
  8177. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8178. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8179. }
  8180. else {
  8181. if (url.indexOf("file:") !== -1) {
  8182. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8183. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8184. try {
  8185. var blobURL;
  8186. try {
  8187. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8188. }
  8189. catch (ex) {
  8190. // Chrome doesn't support oneTimeOnly parameter
  8191. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8192. }
  8193. img.src = blobURL;
  8194. }
  8195. catch (e) {
  8196. img.src = "";
  8197. }
  8198. return img;
  8199. }
  8200. }
  8201. noIndexedDB();
  8202. }
  8203. return img;
  8204. };
  8205. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8206. url = Tools.CleanUrl(url);
  8207. url = Tools.PreprocessUrl(url);
  8208. // If file and file input are set
  8209. if (url.indexOf("file:") !== -1) {
  8210. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8211. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8212. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8213. }
  8214. }
  8215. var loadUrl = Tools.BaseUrl + url;
  8216. var aborted = false;
  8217. var fileRequest = {
  8218. onCompleteObservable: new BABYLON.Observable(),
  8219. abort: function () { return aborted = true; },
  8220. };
  8221. var requestFile = function () {
  8222. var request = new XMLHttpRequest();
  8223. var retryHandle = null;
  8224. fileRequest.abort = function () {
  8225. aborted = true;
  8226. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8227. request.abort();
  8228. }
  8229. if (retryHandle !== null) {
  8230. clearTimeout(retryHandle);
  8231. retryHandle = null;
  8232. }
  8233. };
  8234. var retryLoop = function (retryIndex) {
  8235. request.open('GET', loadUrl, true);
  8236. if (useArrayBuffer) {
  8237. request.responseType = "arraybuffer";
  8238. }
  8239. if (onProgress) {
  8240. request.addEventListener("progress", onProgress);
  8241. }
  8242. var onLoadEnd = function () {
  8243. request.removeEventListener("loadend", onLoadEnd);
  8244. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8245. fileRequest.onCompleteObservable.clear();
  8246. };
  8247. request.addEventListener("loadend", onLoadEnd);
  8248. var onReadyStateChange = function () {
  8249. if (aborted) {
  8250. return;
  8251. }
  8252. // In case of undefined state in some browsers.
  8253. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8254. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8255. request.removeEventListener("readystatechange", onReadyStateChange);
  8256. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8257. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8258. return;
  8259. }
  8260. var retryStrategy = Tools.DefaultRetryStrategy;
  8261. if (retryStrategy) {
  8262. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8263. if (waitTime !== -1) {
  8264. // Prevent the request from completing for retry.
  8265. request.removeEventListener("loadend", onLoadEnd);
  8266. request = new XMLHttpRequest();
  8267. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8268. return;
  8269. }
  8270. }
  8271. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8272. if (onError) {
  8273. onError(request, e);
  8274. }
  8275. else {
  8276. throw e;
  8277. }
  8278. }
  8279. };
  8280. request.addEventListener("readystatechange", onReadyStateChange);
  8281. request.send();
  8282. };
  8283. retryLoop(0);
  8284. };
  8285. // Caching all files
  8286. if (database && database.enableSceneOffline) {
  8287. var noIndexedDB_1 = function () {
  8288. if (!aborted) {
  8289. requestFile();
  8290. }
  8291. };
  8292. var loadFromIndexedDB = function () {
  8293. // TODO: database needs to support aborting and should return a IFileRequest
  8294. if (aborted) {
  8295. return;
  8296. }
  8297. if (database) {
  8298. database.loadFileFromDB(url, function (data) {
  8299. if (!aborted) {
  8300. onSuccess(data);
  8301. }
  8302. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8303. }, onProgress ? function (event) {
  8304. if (!aborted) {
  8305. onProgress(event);
  8306. }
  8307. } : undefined, noIndexedDB_1, useArrayBuffer);
  8308. }
  8309. };
  8310. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8311. }
  8312. else {
  8313. requestFile();
  8314. }
  8315. return fileRequest;
  8316. };
  8317. /**
  8318. * Load a script (identified by an url). When the url returns, the
  8319. * content of this file is added into a new script element, attached to the DOM (body element)
  8320. */
  8321. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8322. var head = document.getElementsByTagName('head')[0];
  8323. var script = document.createElement('script');
  8324. script.type = 'text/javascript';
  8325. script.src = scriptUrl;
  8326. script.onload = function () {
  8327. if (onSuccess) {
  8328. onSuccess();
  8329. }
  8330. };
  8331. script.onerror = function (e) {
  8332. if (onError) {
  8333. onError("Unable to load script", e);
  8334. }
  8335. };
  8336. head.appendChild(script);
  8337. };
  8338. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8339. var reader = new FileReader();
  8340. var request = {
  8341. onCompleteObservable: new BABYLON.Observable(),
  8342. abort: function () { return reader.abort(); },
  8343. };
  8344. reader.onloadend = function (e) {
  8345. request.onCompleteObservable.notifyObservers(request);
  8346. };
  8347. reader.onload = function (e) {
  8348. //target doesn't have result from ts 1.3
  8349. callback(e.target['result']);
  8350. };
  8351. reader.onprogress = progressCallback;
  8352. reader.readAsDataURL(fileToLoad);
  8353. return request;
  8354. };
  8355. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8356. var reader = new FileReader();
  8357. var request = {
  8358. onCompleteObservable: new BABYLON.Observable(),
  8359. abort: function () { return reader.abort(); },
  8360. };
  8361. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8362. reader.onerror = function (e) {
  8363. Tools.Log("Error while reading file: " + fileToLoad.name);
  8364. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8365. };
  8366. reader.onload = function (e) {
  8367. //target doesn't have result from ts 1.3
  8368. callback(e.target['result']);
  8369. };
  8370. if (progressCallBack) {
  8371. reader.onprogress = progressCallBack;
  8372. }
  8373. if (!useArrayBuffer) {
  8374. // Asynchronous read
  8375. reader.readAsText(fileToLoad);
  8376. }
  8377. else {
  8378. reader.readAsArrayBuffer(fileToLoad);
  8379. }
  8380. return request;
  8381. };
  8382. //returns a downloadable url to a file content.
  8383. Tools.FileAsURL = function (content) {
  8384. var fileBlob = new Blob([content]);
  8385. var url = window.URL || window.webkitURL;
  8386. var link = url.createObjectURL(fileBlob);
  8387. return link;
  8388. };
  8389. // Misc.
  8390. Tools.Format = function (value, decimals) {
  8391. if (decimals === void 0) { decimals = 2; }
  8392. return value.toFixed(decimals);
  8393. };
  8394. Tools.CheckExtends = function (v, min, max) {
  8395. if (v.x < min.x)
  8396. min.x = v.x;
  8397. if (v.y < min.y)
  8398. min.y = v.y;
  8399. if (v.z < min.z)
  8400. min.z = v.z;
  8401. if (v.x > max.x)
  8402. max.x = v.x;
  8403. if (v.y > max.y)
  8404. max.y = v.y;
  8405. if (v.z > max.z)
  8406. max.z = v.z;
  8407. };
  8408. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8409. for (var prop in source) {
  8410. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8411. continue;
  8412. }
  8413. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8414. continue;
  8415. }
  8416. var sourceValue = source[prop];
  8417. var typeOfSourceValue = typeof sourceValue;
  8418. if (typeOfSourceValue === "function") {
  8419. continue;
  8420. }
  8421. if (typeOfSourceValue === "object") {
  8422. if (sourceValue instanceof Array) {
  8423. destination[prop] = [];
  8424. if (sourceValue.length > 0) {
  8425. if (typeof sourceValue[0] == "object") {
  8426. for (var index = 0; index < sourceValue.length; index++) {
  8427. var clonedValue = cloneValue(sourceValue[index], destination);
  8428. if (destination[prop].indexOf(clonedValue) === -1) {
  8429. destination[prop].push(clonedValue);
  8430. }
  8431. }
  8432. }
  8433. else {
  8434. destination[prop] = sourceValue.slice(0);
  8435. }
  8436. }
  8437. }
  8438. else {
  8439. destination[prop] = cloneValue(sourceValue, destination);
  8440. }
  8441. }
  8442. else {
  8443. destination[prop] = sourceValue;
  8444. }
  8445. }
  8446. };
  8447. Tools.IsEmpty = function (obj) {
  8448. for (var i in obj) {
  8449. if (obj.hasOwnProperty(i)) {
  8450. return false;
  8451. }
  8452. }
  8453. return true;
  8454. };
  8455. Tools.RegisterTopRootEvents = function (events) {
  8456. for (var index = 0; index < events.length; index++) {
  8457. var event = events[index];
  8458. window.addEventListener(event.name, event.handler, false);
  8459. try {
  8460. if (window.parent) {
  8461. window.parent.addEventListener(event.name, event.handler, false);
  8462. }
  8463. }
  8464. catch (e) {
  8465. // Silently fails...
  8466. }
  8467. }
  8468. };
  8469. Tools.UnregisterTopRootEvents = function (events) {
  8470. for (var index = 0; index < events.length; index++) {
  8471. var event = events[index];
  8472. window.removeEventListener(event.name, event.handler);
  8473. try {
  8474. if (window.parent) {
  8475. window.parent.removeEventListener(event.name, event.handler);
  8476. }
  8477. }
  8478. catch (e) {
  8479. // Silently fails...
  8480. }
  8481. }
  8482. };
  8483. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8484. if (mimeType === void 0) { mimeType = "image/png"; }
  8485. // Read the contents of the framebuffer
  8486. var numberOfChannelsByLine = width * 4;
  8487. var halfHeight = height / 2;
  8488. //Reading datas from WebGL
  8489. var data = engine.readPixels(0, 0, width, height);
  8490. //To flip image on Y axis.
  8491. for (var i = 0; i < halfHeight; i++) {
  8492. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8493. var currentCell = j + i * numberOfChannelsByLine;
  8494. var targetLine = height - i - 1;
  8495. var targetCell = j + targetLine * numberOfChannelsByLine;
  8496. var temp = data[currentCell];
  8497. data[currentCell] = data[targetCell];
  8498. data[targetCell] = temp;
  8499. }
  8500. }
  8501. // Create a 2D canvas to store the result
  8502. if (!screenshotCanvas) {
  8503. screenshotCanvas = document.createElement('canvas');
  8504. }
  8505. screenshotCanvas.width = width;
  8506. screenshotCanvas.height = height;
  8507. var context = screenshotCanvas.getContext('2d');
  8508. if (context) {
  8509. // Copy the pixels to a 2D canvas
  8510. var imageData = context.createImageData(width, height);
  8511. var castData = (imageData.data);
  8512. castData.set(data);
  8513. context.putImageData(imageData, 0, 0);
  8514. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8515. }
  8516. };
  8517. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8518. if (mimeType === void 0) { mimeType = "image/png"; }
  8519. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8520. if (successCallback) {
  8521. successCallback(base64Image);
  8522. }
  8523. else {
  8524. // We need HTMLCanvasElement.toBlob for HD screenshots
  8525. if (!screenshotCanvas.toBlob) {
  8526. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8527. screenshotCanvas.toBlob = function (callback, type, quality) {
  8528. var _this = this;
  8529. setTimeout(function () {
  8530. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8531. for (var i = 0; i < len; i++) {
  8532. arr[i] = binStr.charCodeAt(i);
  8533. }
  8534. callback(new Blob([arr], { type: type || 'image/png' }));
  8535. });
  8536. };
  8537. }
  8538. screenshotCanvas.toBlob(function (blob) {
  8539. var url = URL.createObjectURL(blob);
  8540. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8541. if (("download" in document.createElement("a"))) {
  8542. var a = window.document.createElement("a");
  8543. a.href = url;
  8544. if (fileName) {
  8545. a.setAttribute("download", fileName);
  8546. }
  8547. else {
  8548. var date = new Date();
  8549. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8550. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8551. }
  8552. window.document.body.appendChild(a);
  8553. a.addEventListener("click", function () {
  8554. if (a.parentElement) {
  8555. a.parentElement.removeChild(a);
  8556. }
  8557. });
  8558. a.click();
  8559. }
  8560. else {
  8561. var newWindow = window.open("");
  8562. if (!newWindow)
  8563. return;
  8564. var img = newWindow.document.createElement("img");
  8565. img.onload = function () {
  8566. // no longer need to read the blob so it's revoked
  8567. URL.revokeObjectURL(url);
  8568. };
  8569. img.src = url;
  8570. newWindow.document.body.appendChild(img);
  8571. }
  8572. });
  8573. }
  8574. };
  8575. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8576. if (mimeType === void 0) { mimeType = "image/png"; }
  8577. var width;
  8578. var height;
  8579. // If a precision value is specified
  8580. if (size.precision) {
  8581. width = Math.round(engine.getRenderWidth() * size.precision);
  8582. height = Math.round(width / engine.getAspectRatio(camera));
  8583. }
  8584. else if (size.width && size.height) {
  8585. width = size.width;
  8586. height = size.height;
  8587. }
  8588. else if (size.width && !size.height) {
  8589. width = size.width;
  8590. height = Math.round(width / engine.getAspectRatio(camera));
  8591. }
  8592. else if (size.height && !size.width) {
  8593. height = size.height;
  8594. width = Math.round(height * engine.getAspectRatio(camera));
  8595. }
  8596. else if (!isNaN(size)) {
  8597. height = size;
  8598. width = size;
  8599. }
  8600. else {
  8601. Tools.Error("Invalid 'size' parameter !");
  8602. return;
  8603. }
  8604. if (!screenshotCanvas) {
  8605. screenshotCanvas = document.createElement('canvas');
  8606. }
  8607. screenshotCanvas.width = width;
  8608. screenshotCanvas.height = height;
  8609. var renderContext = screenshotCanvas.getContext("2d");
  8610. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8611. var newWidth = width;
  8612. var newHeight = newWidth / ratio;
  8613. if (newHeight > height) {
  8614. newHeight = height;
  8615. newWidth = newHeight * ratio;
  8616. }
  8617. var offsetX = Math.max(0, width - newWidth) / 2;
  8618. var offsetY = Math.max(0, height - newHeight) / 2;
  8619. var renderingCanvas = engine.getRenderingCanvas();
  8620. if (renderContext && renderingCanvas) {
  8621. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8622. }
  8623. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8624. };
  8625. /**
  8626. * Generates an image screenshot from the specified camera.
  8627. *
  8628. * @param engine The engine to use for rendering
  8629. * @param camera The camera to use for rendering
  8630. * @param size This parameter can be set to a single number or to an object with the
  8631. * following (optional) properties: precision, width, height. If a single number is passed,
  8632. * it will be used for both width and height. If an object is passed, the screenshot size
  8633. * will be derived from the parameters. The precision property is a multiplier allowing
  8634. * rendering at a higher or lower resolution.
  8635. * @param successCallback The callback receives a single parameter which contains the
  8636. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8637. * src parameter of an <img> to display it.
  8638. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8639. * Check your browser for supported MIME types.
  8640. * @param samples Texture samples (default: 1)
  8641. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8642. * @param fileName A name for for the downloaded file.
  8643. * @constructor
  8644. */
  8645. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8646. if (mimeType === void 0) { mimeType = "image/png"; }
  8647. if (samples === void 0) { samples = 1; }
  8648. if (antialiasing === void 0) { antialiasing = false; }
  8649. var width;
  8650. var height;
  8651. //If a precision value is specified
  8652. if (size.precision) {
  8653. width = Math.round(engine.getRenderWidth() * size.precision);
  8654. height = Math.round(width / engine.getAspectRatio(camera));
  8655. size = { width: width, height: height };
  8656. }
  8657. else if (size.width && size.height) {
  8658. width = size.width;
  8659. height = size.height;
  8660. }
  8661. else if (size.width && !size.height) {
  8662. width = size.width;
  8663. height = Math.round(width / engine.getAspectRatio(camera));
  8664. size = { width: width, height: height };
  8665. }
  8666. else if (size.height && !size.width) {
  8667. height = size.height;
  8668. width = Math.round(height * engine.getAspectRatio(camera));
  8669. size = { width: width, height: height };
  8670. }
  8671. else if (!isNaN(size)) {
  8672. height = size;
  8673. width = size;
  8674. }
  8675. else {
  8676. Tools.Error("Invalid 'size' parameter !");
  8677. return;
  8678. }
  8679. var scene = camera.getScene();
  8680. var previousCamera = null;
  8681. if (scene.activeCamera !== camera) {
  8682. previousCamera = scene.activeCamera;
  8683. scene.activeCamera = camera;
  8684. }
  8685. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8686. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8687. texture.renderList = null;
  8688. texture.samples = samples;
  8689. if (antialiasing) {
  8690. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8691. }
  8692. texture.onAfterRenderObservable.add(function () {
  8693. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8694. });
  8695. scene.incrementRenderId();
  8696. scene.resetCachedMaterial();
  8697. texture.render(true);
  8698. texture.dispose();
  8699. if (previousCamera) {
  8700. scene.activeCamera = previousCamera;
  8701. }
  8702. camera.getProjectionMatrix(true); // Force cache refresh;
  8703. };
  8704. // XHR response validator for local file scenario
  8705. Tools.ValidateXHRData = function (xhr, dataType) {
  8706. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8707. if (dataType === void 0) { dataType = 7; }
  8708. try {
  8709. if (dataType & 1) {
  8710. if (xhr.responseText && xhr.responseText.length > 0) {
  8711. return true;
  8712. }
  8713. else if (dataType === 1) {
  8714. return false;
  8715. }
  8716. }
  8717. if (dataType & 2) {
  8718. // Check header width and height since there is no "TGA" magic number
  8719. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8720. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8721. return true;
  8722. }
  8723. else if (dataType === 2) {
  8724. return false;
  8725. }
  8726. }
  8727. if (dataType & 4) {
  8728. // Check for the "DDS" magic number
  8729. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8730. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8731. return true;
  8732. }
  8733. else {
  8734. return false;
  8735. }
  8736. }
  8737. }
  8738. catch (e) {
  8739. // Global protection
  8740. }
  8741. return false;
  8742. };
  8743. /**
  8744. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8745. * Be aware Math.random() could cause collisions, but:
  8746. * "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"
  8747. */
  8748. Tools.RandomId = function () {
  8749. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8750. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8751. return v.toString(16);
  8752. });
  8753. };
  8754. /**
  8755. * Test if the given uri is a base64 string.
  8756. * @param uri The uri to test
  8757. * @return True if the uri is a base64 string or false otherwise.
  8758. */
  8759. Tools.IsBase64 = function (uri) {
  8760. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8761. };
  8762. /**
  8763. * Decode the given base64 uri.
  8764. * @param uri The uri to decode
  8765. * @return The decoded base64 data.
  8766. */
  8767. Tools.DecodeBase64 = function (uri) {
  8768. var decodedString = atob(uri.split(",")[1]);
  8769. var bufferLength = decodedString.length;
  8770. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8771. for (var i = 0; i < bufferLength; i++) {
  8772. bufferView[i] = decodedString.charCodeAt(i);
  8773. }
  8774. return bufferView.buffer;
  8775. };
  8776. Object.defineProperty(Tools, "NoneLogLevel", {
  8777. get: function () {
  8778. return Tools._NoneLogLevel;
  8779. },
  8780. enumerable: true,
  8781. configurable: true
  8782. });
  8783. Object.defineProperty(Tools, "MessageLogLevel", {
  8784. get: function () {
  8785. return Tools._MessageLogLevel;
  8786. },
  8787. enumerable: true,
  8788. configurable: true
  8789. });
  8790. Object.defineProperty(Tools, "WarningLogLevel", {
  8791. get: function () {
  8792. return Tools._WarningLogLevel;
  8793. },
  8794. enumerable: true,
  8795. configurable: true
  8796. });
  8797. Object.defineProperty(Tools, "ErrorLogLevel", {
  8798. get: function () {
  8799. return Tools._ErrorLogLevel;
  8800. },
  8801. enumerable: true,
  8802. configurable: true
  8803. });
  8804. Object.defineProperty(Tools, "AllLogLevel", {
  8805. get: function () {
  8806. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8807. },
  8808. enumerable: true,
  8809. configurable: true
  8810. });
  8811. Tools._AddLogEntry = function (entry) {
  8812. Tools._LogCache = entry + Tools._LogCache;
  8813. if (Tools.OnNewCacheEntry) {
  8814. Tools.OnNewCacheEntry(entry);
  8815. }
  8816. };
  8817. Tools._FormatMessage = function (message) {
  8818. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8819. var date = new Date();
  8820. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8821. };
  8822. Tools._LogDisabled = function (message) {
  8823. // nothing to do
  8824. };
  8825. Tools._LogEnabled = function (message) {
  8826. var formattedMessage = Tools._FormatMessage(message);
  8827. console.log("BJS - " + formattedMessage);
  8828. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8829. Tools._AddLogEntry(entry);
  8830. };
  8831. Tools._WarnDisabled = function (message) {
  8832. // nothing to do
  8833. };
  8834. Tools._WarnEnabled = function (message) {
  8835. var formattedMessage = Tools._FormatMessage(message);
  8836. console.warn("BJS - " + formattedMessage);
  8837. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8838. Tools._AddLogEntry(entry);
  8839. };
  8840. Tools._ErrorDisabled = function (message) {
  8841. // nothing to do
  8842. };
  8843. Tools._ErrorEnabled = function (message) {
  8844. Tools.errorsCount++;
  8845. var formattedMessage = Tools._FormatMessage(message);
  8846. console.error("BJS - " + formattedMessage);
  8847. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8848. Tools._AddLogEntry(entry);
  8849. };
  8850. Object.defineProperty(Tools, "LogCache", {
  8851. get: function () {
  8852. return Tools._LogCache;
  8853. },
  8854. enumerable: true,
  8855. configurable: true
  8856. });
  8857. Tools.ClearLogCache = function () {
  8858. Tools._LogCache = "";
  8859. Tools.errorsCount = 0;
  8860. };
  8861. Object.defineProperty(Tools, "LogLevels", {
  8862. set: function (level) {
  8863. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8864. Tools.Log = Tools._LogEnabled;
  8865. }
  8866. else {
  8867. Tools.Log = Tools._LogDisabled;
  8868. }
  8869. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8870. Tools.Warn = Tools._WarnEnabled;
  8871. }
  8872. else {
  8873. Tools.Warn = Tools._WarnDisabled;
  8874. }
  8875. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8876. Tools.Error = Tools._ErrorEnabled;
  8877. }
  8878. else {
  8879. Tools.Error = Tools._ErrorDisabled;
  8880. }
  8881. },
  8882. enumerable: true,
  8883. configurable: true
  8884. });
  8885. Tools.IsWindowObjectExist = function () {
  8886. return (typeof window) !== "undefined";
  8887. };
  8888. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8889. get: function () {
  8890. return Tools._PerformanceNoneLogLevel;
  8891. },
  8892. enumerable: true,
  8893. configurable: true
  8894. });
  8895. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8896. get: function () {
  8897. return Tools._PerformanceUserMarkLogLevel;
  8898. },
  8899. enumerable: true,
  8900. configurable: true
  8901. });
  8902. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8903. get: function () {
  8904. return Tools._PerformanceConsoleLogLevel;
  8905. },
  8906. enumerable: true,
  8907. configurable: true
  8908. });
  8909. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8910. set: function (level) {
  8911. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8912. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8913. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8914. return;
  8915. }
  8916. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8917. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8918. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8919. return;
  8920. }
  8921. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8922. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8923. },
  8924. enumerable: true,
  8925. configurable: true
  8926. });
  8927. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8928. };
  8929. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8930. };
  8931. Tools._StartUserMark = function (counterName, condition) {
  8932. if (condition === void 0) { condition = true; }
  8933. if (!Tools._performance) {
  8934. if (!Tools.IsWindowObjectExist()) {
  8935. return;
  8936. }
  8937. Tools._performance = window.performance;
  8938. }
  8939. if (!condition || !Tools._performance.mark) {
  8940. return;
  8941. }
  8942. Tools._performance.mark(counterName + "-Begin");
  8943. };
  8944. Tools._EndUserMark = function (counterName, condition) {
  8945. if (condition === void 0) { condition = true; }
  8946. if (!condition || !Tools._performance.mark) {
  8947. return;
  8948. }
  8949. Tools._performance.mark(counterName + "-End");
  8950. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8951. };
  8952. Tools._StartPerformanceConsole = function (counterName, condition) {
  8953. if (condition === void 0) { condition = true; }
  8954. if (!condition) {
  8955. return;
  8956. }
  8957. Tools._StartUserMark(counterName, condition);
  8958. if (console.time) {
  8959. console.time(counterName);
  8960. }
  8961. };
  8962. Tools._EndPerformanceConsole = function (counterName, condition) {
  8963. if (condition === void 0) { condition = true; }
  8964. if (!condition) {
  8965. return;
  8966. }
  8967. Tools._EndUserMark(counterName, condition);
  8968. if (console.time) {
  8969. console.timeEnd(counterName);
  8970. }
  8971. };
  8972. Object.defineProperty(Tools, "Now", {
  8973. get: function () {
  8974. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8975. return window.performance.now();
  8976. }
  8977. return new Date().getTime();
  8978. },
  8979. enumerable: true,
  8980. configurable: true
  8981. });
  8982. /**
  8983. * This method will return the name of the class used to create the instance of the given object.
  8984. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8985. * @param object the object to get the class name from
  8986. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8987. */
  8988. Tools.GetClassName = function (object, isType) {
  8989. if (isType === void 0) { isType = false; }
  8990. var name = null;
  8991. if (!isType && object.getClassName) {
  8992. name = object.getClassName();
  8993. }
  8994. else {
  8995. if (object instanceof Object) {
  8996. var classObj = isType ? object : Object.getPrototypeOf(object);
  8997. name = classObj.constructor["__bjsclassName__"];
  8998. }
  8999. if (!name) {
  9000. name = typeof object;
  9001. }
  9002. }
  9003. return name;
  9004. };
  9005. Tools.First = function (array, predicate) {
  9006. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9007. var el = array_1[_i];
  9008. if (predicate(el)) {
  9009. return el;
  9010. }
  9011. }
  9012. return null;
  9013. };
  9014. /**
  9015. * This method will return the name of the full name of the class, including its owning module (if any).
  9016. * 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).
  9017. * @param object the object to get the class name from
  9018. * @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.
  9019. */
  9020. Tools.getFullClassName = function (object, isType) {
  9021. if (isType === void 0) { isType = false; }
  9022. var className = null;
  9023. var moduleName = null;
  9024. if (!isType && object.getClassName) {
  9025. className = object.getClassName();
  9026. }
  9027. else {
  9028. if (object instanceof Object) {
  9029. var classObj = isType ? object : Object.getPrototypeOf(object);
  9030. className = classObj.constructor["__bjsclassName__"];
  9031. moduleName = classObj.constructor["__bjsmoduleName__"];
  9032. }
  9033. if (!className) {
  9034. className = typeof object;
  9035. }
  9036. }
  9037. if (!className) {
  9038. return null;
  9039. }
  9040. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9041. };
  9042. /**
  9043. * 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.
  9044. * @param array
  9045. */
  9046. Tools.arrayOrStringFeeder = function (array) {
  9047. return function (index) {
  9048. if (index >= array.length) {
  9049. return null;
  9050. }
  9051. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9052. if (val && val.getHashCode) {
  9053. val = val.getHashCode();
  9054. }
  9055. if (typeof val === "string") {
  9056. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9057. }
  9058. return val;
  9059. };
  9060. };
  9061. /**
  9062. * Compute the hashCode of a stream of number
  9063. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9064. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9065. * @return the hash code computed
  9066. */
  9067. Tools.hashCodeFromStream = function (feeder) {
  9068. // Based from here: http://stackoverflow.com/a/7616484/802124
  9069. var hash = 0;
  9070. var index = 0;
  9071. var chr = feeder(index++);
  9072. while (chr != null) {
  9073. hash = ((hash << 5) - hash) + chr;
  9074. hash |= 0; // Convert to 32bit integer
  9075. chr = feeder(index++);
  9076. }
  9077. return hash;
  9078. };
  9079. /**
  9080. * Returns a promise that resolves after the given amount of time.
  9081. * @param delay Number of milliseconds to delay
  9082. * @returns Promise that resolves after the given amount of time
  9083. */
  9084. Tools.DelayAsync = function (delay) {
  9085. return new Promise(function (resolve) {
  9086. setTimeout(function () {
  9087. resolve();
  9088. }, delay);
  9089. });
  9090. };
  9091. Tools.BaseUrl = "";
  9092. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9093. /**
  9094. * Default behaviour for cors in the application.
  9095. * It can be a string if the expected behavior is identical in the entire app.
  9096. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9097. */
  9098. Tools.CorsBehavior = "anonymous";
  9099. Tools.UseFallbackTexture = true;
  9100. /**
  9101. * Use this object to register external classes like custom textures or material
  9102. * to allow the laoders to instantiate them
  9103. */
  9104. Tools.RegisteredExternalClasses = {};
  9105. // Used in case of a texture loading problem
  9106. 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";
  9107. Tools.PreprocessUrl = function (url) {
  9108. return url;
  9109. };
  9110. // Logs
  9111. Tools._NoneLogLevel = 0;
  9112. Tools._MessageLogLevel = 1;
  9113. Tools._WarningLogLevel = 2;
  9114. Tools._ErrorLogLevel = 4;
  9115. Tools._LogCache = "";
  9116. Tools.errorsCount = 0;
  9117. Tools.Log = Tools._LogEnabled;
  9118. Tools.Warn = Tools._WarnEnabled;
  9119. Tools.Error = Tools._ErrorEnabled;
  9120. // Performances
  9121. Tools._PerformanceNoneLogLevel = 0;
  9122. Tools._PerformanceUserMarkLogLevel = 1;
  9123. Tools._PerformanceConsoleLogLevel = 2;
  9124. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9125. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9126. return Tools;
  9127. }());
  9128. BABYLON.Tools = Tools;
  9129. /**
  9130. * This class is used to track a performance counter which is number based.
  9131. * The user has access to many properties which give statistics of different nature
  9132. *
  9133. * The implementer can track two kinds of Performance Counter: time and count
  9134. * 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.
  9135. * 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.
  9136. */
  9137. var PerfCounter = /** @class */ (function () {
  9138. function PerfCounter() {
  9139. this._startMonitoringTime = 0;
  9140. this._min = 0;
  9141. this._max = 0;
  9142. this._average = 0;
  9143. this._lastSecAverage = 0;
  9144. this._current = 0;
  9145. this._totalValueCount = 0;
  9146. this._totalAccumulated = 0;
  9147. this._lastSecAccumulated = 0;
  9148. this._lastSecTime = 0;
  9149. this._lastSecValueCount = 0;
  9150. }
  9151. Object.defineProperty(PerfCounter.prototype, "min", {
  9152. /**
  9153. * Returns the smallest value ever
  9154. */
  9155. get: function () {
  9156. return this._min;
  9157. },
  9158. enumerable: true,
  9159. configurable: true
  9160. });
  9161. Object.defineProperty(PerfCounter.prototype, "max", {
  9162. /**
  9163. * Returns the biggest value ever
  9164. */
  9165. get: function () {
  9166. return this._max;
  9167. },
  9168. enumerable: true,
  9169. configurable: true
  9170. });
  9171. Object.defineProperty(PerfCounter.prototype, "average", {
  9172. /**
  9173. * Returns the average value since the performance counter is running
  9174. */
  9175. get: function () {
  9176. return this._average;
  9177. },
  9178. enumerable: true,
  9179. configurable: true
  9180. });
  9181. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9182. /**
  9183. * Returns the average value of the last second the counter was monitored
  9184. */
  9185. get: function () {
  9186. return this._lastSecAverage;
  9187. },
  9188. enumerable: true,
  9189. configurable: true
  9190. });
  9191. Object.defineProperty(PerfCounter.prototype, "current", {
  9192. /**
  9193. * Returns the current value
  9194. */
  9195. get: function () {
  9196. return this._current;
  9197. },
  9198. enumerable: true,
  9199. configurable: true
  9200. });
  9201. Object.defineProperty(PerfCounter.prototype, "total", {
  9202. get: function () {
  9203. return this._totalAccumulated;
  9204. },
  9205. enumerable: true,
  9206. configurable: true
  9207. });
  9208. Object.defineProperty(PerfCounter.prototype, "count", {
  9209. get: function () {
  9210. return this._totalValueCount;
  9211. },
  9212. enumerable: true,
  9213. configurable: true
  9214. });
  9215. /**
  9216. * Call this method to start monitoring a new frame.
  9217. * 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.
  9218. */
  9219. PerfCounter.prototype.fetchNewFrame = function () {
  9220. this._totalValueCount++;
  9221. this._current = 0;
  9222. this._lastSecValueCount++;
  9223. };
  9224. /**
  9225. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9226. * @param newCount the count value to add to the monitored count
  9227. * @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.
  9228. */
  9229. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9230. if (!PerfCounter.Enabled) {
  9231. return;
  9232. }
  9233. this._current += newCount;
  9234. if (fetchResult) {
  9235. this._fetchResult();
  9236. }
  9237. };
  9238. /**
  9239. * Start monitoring this performance counter
  9240. */
  9241. PerfCounter.prototype.beginMonitoring = function () {
  9242. if (!PerfCounter.Enabled) {
  9243. return;
  9244. }
  9245. this._startMonitoringTime = Tools.Now;
  9246. };
  9247. /**
  9248. * Compute the time lapsed since the previous beginMonitoring() call.
  9249. * @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
  9250. */
  9251. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9252. if (newFrame === void 0) { newFrame = true; }
  9253. if (!PerfCounter.Enabled) {
  9254. return;
  9255. }
  9256. if (newFrame) {
  9257. this.fetchNewFrame();
  9258. }
  9259. var currentTime = Tools.Now;
  9260. this._current = currentTime - this._startMonitoringTime;
  9261. if (newFrame) {
  9262. this._fetchResult();
  9263. }
  9264. };
  9265. PerfCounter.prototype._fetchResult = function () {
  9266. this._totalAccumulated += this._current;
  9267. this._lastSecAccumulated += this._current;
  9268. // Min/Max update
  9269. this._min = Math.min(this._min, this._current);
  9270. this._max = Math.max(this._max, this._current);
  9271. this._average = this._totalAccumulated / this._totalValueCount;
  9272. // Reset last sec?
  9273. var now = Tools.Now;
  9274. if ((now - this._lastSecTime) > 1000) {
  9275. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9276. this._lastSecTime = now;
  9277. this._lastSecAccumulated = 0;
  9278. this._lastSecValueCount = 0;
  9279. }
  9280. };
  9281. PerfCounter.Enabled = true;
  9282. return PerfCounter;
  9283. }());
  9284. BABYLON.PerfCounter = PerfCounter;
  9285. /**
  9286. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9287. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9288. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9289. * @param name The name of the class, case should be preserved
  9290. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9291. */
  9292. function className(name, module) {
  9293. return function (target) {
  9294. target["__bjsclassName__"] = name;
  9295. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9296. };
  9297. }
  9298. BABYLON.className = className;
  9299. /**
  9300. * An implementation of a loop for asynchronous functions.
  9301. */
  9302. var AsyncLoop = /** @class */ (function () {
  9303. /**
  9304. * Constroctor.
  9305. * @param iterations the number of iterations.
  9306. * @param _fn the function to run each iteration
  9307. * @param _successCallback the callback that will be called upon succesful execution
  9308. * @param offset starting offset.
  9309. */
  9310. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9311. if (offset === void 0) { offset = 0; }
  9312. this.iterations = iterations;
  9313. this._fn = _fn;
  9314. this._successCallback = _successCallback;
  9315. this.index = offset - 1;
  9316. this._done = false;
  9317. }
  9318. /**
  9319. * Execute the next iteration. Must be called after the last iteration was finished.
  9320. */
  9321. AsyncLoop.prototype.executeNext = function () {
  9322. if (!this._done) {
  9323. if (this.index + 1 < this.iterations) {
  9324. ++this.index;
  9325. this._fn(this);
  9326. }
  9327. else {
  9328. this.breakLoop();
  9329. }
  9330. }
  9331. };
  9332. /**
  9333. * Break the loop and run the success callback.
  9334. */
  9335. AsyncLoop.prototype.breakLoop = function () {
  9336. this._done = true;
  9337. this._successCallback();
  9338. };
  9339. /**
  9340. * Helper function
  9341. */
  9342. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9343. if (offset === void 0) { offset = 0; }
  9344. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9345. loop.executeNext();
  9346. return loop;
  9347. };
  9348. /**
  9349. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9350. * @param iterations total number of iterations
  9351. * @param syncedIterations number of synchronous iterations in each async iteration.
  9352. * @param fn the function to call each iteration.
  9353. * @param callback a success call back that will be called when iterating stops.
  9354. * @param breakFunction a break condition (optional)
  9355. * @param timeout timeout settings for the setTimeout function. default - 0.
  9356. * @constructor
  9357. */
  9358. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9359. if (timeout === void 0) { timeout = 0; }
  9360. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9361. if (breakFunction && breakFunction())
  9362. loop.breakLoop();
  9363. else {
  9364. setTimeout(function () {
  9365. for (var i = 0; i < syncedIterations; ++i) {
  9366. var iteration = (loop.index * syncedIterations) + i;
  9367. if (iteration >= iterations)
  9368. break;
  9369. fn(iteration);
  9370. if (breakFunction && breakFunction()) {
  9371. loop.breakLoop();
  9372. break;
  9373. }
  9374. }
  9375. loop.executeNext();
  9376. }, timeout);
  9377. }
  9378. }, callback);
  9379. };
  9380. return AsyncLoop;
  9381. }());
  9382. BABYLON.AsyncLoop = AsyncLoop;
  9383. })(BABYLON || (BABYLON = {}));
  9384. //# sourceMappingURL=babylon.tools.js.map
  9385. var BABYLON;
  9386. (function (BABYLON) {
  9387. var PromiseStates;
  9388. (function (PromiseStates) {
  9389. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9390. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9391. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9392. })(PromiseStates || (PromiseStates = {}));
  9393. var FulFillmentAgregator = /** @class */ (function () {
  9394. function FulFillmentAgregator() {
  9395. this.count = 0;
  9396. this.target = 0;
  9397. this.results = [];
  9398. }
  9399. return FulFillmentAgregator;
  9400. }());
  9401. var InternalPromise = /** @class */ (function () {
  9402. function InternalPromise(resolver) {
  9403. var _this = this;
  9404. this._state = PromiseStates.Pending;
  9405. this._children = new Array();
  9406. this._rejectWasConsumed = false;
  9407. if (!resolver) {
  9408. return;
  9409. }
  9410. try {
  9411. resolver(function (value) {
  9412. _this._resolve(value);
  9413. }, function (reason) {
  9414. _this._reject(reason);
  9415. });
  9416. }
  9417. catch (e) {
  9418. this._reject(e);
  9419. }
  9420. }
  9421. InternalPromise.prototype.catch = function (onRejected) {
  9422. return this.then(undefined, onRejected);
  9423. };
  9424. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9425. var _this = this;
  9426. var newPromise = new InternalPromise();
  9427. newPromise._onFulfilled = onFulfilled;
  9428. newPromise._onRejected = onRejected;
  9429. // Composition
  9430. this._children.push(newPromise);
  9431. if (this._state !== PromiseStates.Pending) {
  9432. BABYLON.Tools.SetImmediate(function () {
  9433. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9434. var returnedValue = newPromise._resolve(_this._result);
  9435. if (returnedValue !== undefined && returnedValue !== null) {
  9436. if (returnedValue._state !== undefined) {
  9437. var returnedPromise = returnedValue;
  9438. newPromise._children.push(returnedPromise);
  9439. newPromise = returnedPromise;
  9440. }
  9441. else {
  9442. newPromise._result = returnedValue;
  9443. }
  9444. }
  9445. }
  9446. else {
  9447. newPromise._reject(_this._reason);
  9448. }
  9449. });
  9450. }
  9451. return newPromise;
  9452. };
  9453. InternalPromise.prototype._moveChildren = function (children) {
  9454. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9455. if (this._state === PromiseStates.Fulfilled) {
  9456. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9457. var child = _b[_i];
  9458. child._resolve(this._result);
  9459. }
  9460. }
  9461. else if (this._state === PromiseStates.Rejected) {
  9462. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9463. var child = _d[_c];
  9464. child._reject(this._reason);
  9465. }
  9466. }
  9467. var _a;
  9468. };
  9469. InternalPromise.prototype._resolve = function (value) {
  9470. try {
  9471. this._state = PromiseStates.Fulfilled;
  9472. this._result = value;
  9473. var returnedValue = null;
  9474. if (this._onFulfilled) {
  9475. returnedValue = this._onFulfilled(value);
  9476. }
  9477. if (returnedValue !== undefined && returnedValue !== null) {
  9478. if (returnedValue._state !== undefined) {
  9479. // Transmit children
  9480. var returnedPromise = returnedValue;
  9481. returnedPromise._moveChildren(this._children);
  9482. }
  9483. else {
  9484. value = returnedValue;
  9485. }
  9486. }
  9487. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9488. var child = _a[_i];
  9489. child._resolve(value);
  9490. }
  9491. this._children.length = 0;
  9492. delete this._onFulfilled;
  9493. delete this._onRejected;
  9494. return returnedValue;
  9495. }
  9496. catch (e) {
  9497. this._reject(e, true);
  9498. }
  9499. return null;
  9500. };
  9501. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9502. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9503. this._state = PromiseStates.Rejected;
  9504. this._reason = reason;
  9505. if (this._onRejected && !onLocalThrow) {
  9506. try {
  9507. this._onRejected(reason);
  9508. this._rejectWasConsumed = true;
  9509. }
  9510. catch (e) {
  9511. reason = e;
  9512. }
  9513. }
  9514. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9515. var child = _a[_i];
  9516. if (this._rejectWasConsumed) {
  9517. child._resolve(null);
  9518. }
  9519. else {
  9520. child._reject(reason);
  9521. }
  9522. }
  9523. this._children.length = 0;
  9524. delete this._onFulfilled;
  9525. delete this._onRejected;
  9526. };
  9527. InternalPromise.resolve = function (value) {
  9528. var newPromise = new InternalPromise();
  9529. newPromise._resolve(value);
  9530. return newPromise;
  9531. };
  9532. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9533. promise.then(function (value) {
  9534. agregator.results[index] = value;
  9535. agregator.count++;
  9536. if (agregator.count === agregator.target) {
  9537. agregator.rootPromise._resolve(agregator.results);
  9538. }
  9539. return null;
  9540. }, function (reason) {
  9541. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9542. agregator.rootPromise._reject(reason);
  9543. }
  9544. });
  9545. };
  9546. InternalPromise.all = function (promises) {
  9547. var newPromise = new InternalPromise();
  9548. var agregator = new FulFillmentAgregator();
  9549. agregator.target = promises.length;
  9550. agregator.rootPromise = newPromise;
  9551. if (promises.length) {
  9552. for (var index = 0; index < promises.length; index++) {
  9553. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9554. }
  9555. }
  9556. else {
  9557. newPromise._resolve([]);
  9558. }
  9559. return newPromise;
  9560. };
  9561. InternalPromise.race = function (promises) {
  9562. var newPromise = new InternalPromise();
  9563. if (promises.length) {
  9564. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9565. var promise = promises_1[_i];
  9566. promise.then(function (value) {
  9567. if (newPromise) {
  9568. newPromise._resolve(value);
  9569. newPromise = null;
  9570. }
  9571. return null;
  9572. }, function (reason) {
  9573. if (newPromise) {
  9574. newPromise._reject(reason);
  9575. newPromise = null;
  9576. }
  9577. });
  9578. }
  9579. }
  9580. return newPromise;
  9581. };
  9582. return InternalPromise;
  9583. }());
  9584. /**
  9585. * Helper class that provides a small promise polyfill
  9586. */
  9587. var PromisePolyfill = /** @class */ (function () {
  9588. function PromisePolyfill() {
  9589. }
  9590. /**
  9591. * Static function used to check if the polyfill is required
  9592. * If this is the case then the function will inject the polyfill to window.Promise
  9593. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9594. */
  9595. PromisePolyfill.Apply = function (force) {
  9596. if (force === void 0) { force = false; }
  9597. if (force || typeof Promise === 'undefined') {
  9598. var root = window;
  9599. root.Promise = InternalPromise;
  9600. }
  9601. };
  9602. return PromisePolyfill;
  9603. }());
  9604. BABYLON.PromisePolyfill = PromisePolyfill;
  9605. })(BABYLON || (BABYLON = {}));
  9606. //# sourceMappingURL=babylon.promise.js.map
  9607. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9608. var BABYLON;
  9609. (function (BABYLON) {
  9610. /**
  9611. * Helper class to push actions to a pool of workers.
  9612. */
  9613. var WorkerPool = /** @class */ (function () {
  9614. /**
  9615. * Constructor
  9616. * @param workers Array of workers to use for actions
  9617. */
  9618. function WorkerPool(workers) {
  9619. this._pendingActions = new Array();
  9620. this._workerInfos = workers.map(function (worker) { return ({
  9621. worker: worker,
  9622. active: false
  9623. }); });
  9624. }
  9625. /**
  9626. * Terminates all workers and clears any pending actions.
  9627. */
  9628. WorkerPool.prototype.dispose = function () {
  9629. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9630. var workerInfo = _a[_i];
  9631. workerInfo.worker.terminate();
  9632. }
  9633. delete this._workerInfos;
  9634. delete this._pendingActions;
  9635. };
  9636. /**
  9637. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9638. * pended until a worker has completed its action.
  9639. * @param action The action to perform. Call onComplete when the action is complete.
  9640. */
  9641. WorkerPool.prototype.push = function (action) {
  9642. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9643. var workerInfo = _a[_i];
  9644. if (!workerInfo.active) {
  9645. this._execute(workerInfo, action);
  9646. return;
  9647. }
  9648. }
  9649. this._pendingActions.push(action);
  9650. };
  9651. WorkerPool.prototype._execute = function (workerInfo, action) {
  9652. var _this = this;
  9653. workerInfo.active = true;
  9654. action(workerInfo.worker, function () {
  9655. workerInfo.active = false;
  9656. var nextAction = _this._pendingActions.shift();
  9657. if (nextAction) {
  9658. _this._execute(workerInfo, nextAction);
  9659. }
  9660. });
  9661. };
  9662. return WorkerPool;
  9663. }());
  9664. BABYLON.WorkerPool = WorkerPool;
  9665. })(BABYLON || (BABYLON = {}));
  9666. //# sourceMappingURL=babylon.workerPool.js.map
  9667. var BABYLON;
  9668. (function (BABYLON) {
  9669. var _AlphaState = /** @class */ (function () {
  9670. /**
  9671. * Initializes the state.
  9672. */
  9673. function _AlphaState() {
  9674. this._isAlphaBlendDirty = false;
  9675. this._isBlendFunctionParametersDirty = false;
  9676. this._isBlendEquationParametersDirty = false;
  9677. this._isBlendConstantsDirty = false;
  9678. this._alphaBlend = false;
  9679. this._blendFunctionParameters = new Array(4);
  9680. this._blendEquationParameters = new Array(2);
  9681. this._blendConstants = new Array(4);
  9682. this.reset();
  9683. }
  9684. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9685. get: function () {
  9686. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9687. },
  9688. enumerable: true,
  9689. configurable: true
  9690. });
  9691. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9692. get: function () {
  9693. return this._alphaBlend;
  9694. },
  9695. set: function (value) {
  9696. if (this._alphaBlend === value) {
  9697. return;
  9698. }
  9699. this._alphaBlend = value;
  9700. this._isAlphaBlendDirty = true;
  9701. },
  9702. enumerable: true,
  9703. configurable: true
  9704. });
  9705. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9706. if (this._blendConstants[0] === r &&
  9707. this._blendConstants[1] === g &&
  9708. this._blendConstants[2] === b &&
  9709. this._blendConstants[3] === a) {
  9710. return;
  9711. }
  9712. this._blendConstants[0] = r;
  9713. this._blendConstants[1] = g;
  9714. this._blendConstants[2] = b;
  9715. this._blendConstants[3] = a;
  9716. this._isBlendConstantsDirty = true;
  9717. };
  9718. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9719. if (this._blendFunctionParameters[0] === value0 &&
  9720. this._blendFunctionParameters[1] === value1 &&
  9721. this._blendFunctionParameters[2] === value2 &&
  9722. this._blendFunctionParameters[3] === value3) {
  9723. return;
  9724. }
  9725. this._blendFunctionParameters[0] = value0;
  9726. this._blendFunctionParameters[1] = value1;
  9727. this._blendFunctionParameters[2] = value2;
  9728. this._blendFunctionParameters[3] = value3;
  9729. this._isBlendFunctionParametersDirty = true;
  9730. };
  9731. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9732. if (this._blendEquationParameters[0] === rgb &&
  9733. this._blendEquationParameters[1] === alpha) {
  9734. return;
  9735. }
  9736. this._blendEquationParameters[0] = rgb;
  9737. this._blendEquationParameters[1] = alpha;
  9738. this._isBlendEquationParametersDirty = true;
  9739. };
  9740. _AlphaState.prototype.reset = function () {
  9741. this._alphaBlend = false;
  9742. this._blendFunctionParameters[0] = null;
  9743. this._blendFunctionParameters[1] = null;
  9744. this._blendFunctionParameters[2] = null;
  9745. this._blendFunctionParameters[3] = null;
  9746. this._blendEquationParameters[0] = null;
  9747. this._blendEquationParameters[1] = null;
  9748. this._blendConstants[0] = null;
  9749. this._blendConstants[1] = null;
  9750. this._blendConstants[2] = null;
  9751. this._blendConstants[3] = null;
  9752. this._isAlphaBlendDirty = true;
  9753. this._isBlendFunctionParametersDirty = false;
  9754. this._isBlendEquationParametersDirty = false;
  9755. this._isBlendConstantsDirty = false;
  9756. };
  9757. _AlphaState.prototype.apply = function (gl) {
  9758. if (!this.isDirty) {
  9759. return;
  9760. }
  9761. // Alpha blend
  9762. if (this._isAlphaBlendDirty) {
  9763. if (this._alphaBlend) {
  9764. gl.enable(gl.BLEND);
  9765. }
  9766. else {
  9767. gl.disable(gl.BLEND);
  9768. }
  9769. this._isAlphaBlendDirty = false;
  9770. }
  9771. // Alpha function
  9772. if (this._isBlendFunctionParametersDirty) {
  9773. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9774. this._isBlendFunctionParametersDirty = false;
  9775. }
  9776. // Alpha equation
  9777. if (this._isBlendEquationParametersDirty) {
  9778. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9779. this._isBlendEquationParametersDirty = false;
  9780. }
  9781. // Constants
  9782. if (this._isBlendConstantsDirty) {
  9783. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9784. this._isBlendConstantsDirty = false;
  9785. }
  9786. };
  9787. return _AlphaState;
  9788. }());
  9789. BABYLON._AlphaState = _AlphaState;
  9790. })(BABYLON || (BABYLON = {}));
  9791. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9792. var BABYLON;
  9793. (function (BABYLON) {
  9794. var _DepthCullingState = /** @class */ (function () {
  9795. /**
  9796. * Initializes the state.
  9797. */
  9798. function _DepthCullingState() {
  9799. this._isDepthTestDirty = false;
  9800. this._isDepthMaskDirty = false;
  9801. this._isDepthFuncDirty = false;
  9802. this._isCullFaceDirty = false;
  9803. this._isCullDirty = false;
  9804. this._isZOffsetDirty = false;
  9805. this._isFrontFaceDirty = false;
  9806. this.reset();
  9807. }
  9808. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9809. get: function () {
  9810. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9811. },
  9812. enumerable: true,
  9813. configurable: true
  9814. });
  9815. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9816. get: function () {
  9817. return this._zOffset;
  9818. },
  9819. set: function (value) {
  9820. if (this._zOffset === value) {
  9821. return;
  9822. }
  9823. this._zOffset = value;
  9824. this._isZOffsetDirty = true;
  9825. },
  9826. enumerable: true,
  9827. configurable: true
  9828. });
  9829. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9830. get: function () {
  9831. return this._cullFace;
  9832. },
  9833. set: function (value) {
  9834. if (this._cullFace === value) {
  9835. return;
  9836. }
  9837. this._cullFace = value;
  9838. this._isCullFaceDirty = true;
  9839. },
  9840. enumerable: true,
  9841. configurable: true
  9842. });
  9843. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9844. get: function () {
  9845. return this._cull;
  9846. },
  9847. set: function (value) {
  9848. if (this._cull === value) {
  9849. return;
  9850. }
  9851. this._cull = value;
  9852. this._isCullDirty = true;
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9858. get: function () {
  9859. return this._depthFunc;
  9860. },
  9861. set: function (value) {
  9862. if (this._depthFunc === value) {
  9863. return;
  9864. }
  9865. this._depthFunc = value;
  9866. this._isDepthFuncDirty = true;
  9867. },
  9868. enumerable: true,
  9869. configurable: true
  9870. });
  9871. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9872. get: function () {
  9873. return this._depthMask;
  9874. },
  9875. set: function (value) {
  9876. if (this._depthMask === value) {
  9877. return;
  9878. }
  9879. this._depthMask = value;
  9880. this._isDepthMaskDirty = true;
  9881. },
  9882. enumerable: true,
  9883. configurable: true
  9884. });
  9885. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9886. get: function () {
  9887. return this._depthTest;
  9888. },
  9889. set: function (value) {
  9890. if (this._depthTest === value) {
  9891. return;
  9892. }
  9893. this._depthTest = value;
  9894. this._isDepthTestDirty = true;
  9895. },
  9896. enumerable: true,
  9897. configurable: true
  9898. });
  9899. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9900. get: function () {
  9901. return this._frontFace;
  9902. },
  9903. set: function (value) {
  9904. if (this._frontFace === value) {
  9905. return;
  9906. }
  9907. this._frontFace = value;
  9908. this._isFrontFaceDirty = true;
  9909. },
  9910. enumerable: true,
  9911. configurable: true
  9912. });
  9913. _DepthCullingState.prototype.reset = function () {
  9914. this._depthMask = true;
  9915. this._depthTest = true;
  9916. this._depthFunc = null;
  9917. this._cullFace = null;
  9918. this._cull = null;
  9919. this._zOffset = 0;
  9920. this._frontFace = null;
  9921. this._isDepthTestDirty = true;
  9922. this._isDepthMaskDirty = true;
  9923. this._isDepthFuncDirty = false;
  9924. this._isCullFaceDirty = false;
  9925. this._isCullDirty = false;
  9926. this._isZOffsetDirty = false;
  9927. this._isFrontFaceDirty = false;
  9928. };
  9929. _DepthCullingState.prototype.apply = function (gl) {
  9930. if (!this.isDirty) {
  9931. return;
  9932. }
  9933. // Cull
  9934. if (this._isCullDirty) {
  9935. if (this.cull) {
  9936. gl.enable(gl.CULL_FACE);
  9937. }
  9938. else {
  9939. gl.disable(gl.CULL_FACE);
  9940. }
  9941. this._isCullDirty = false;
  9942. }
  9943. // Cull face
  9944. if (this._isCullFaceDirty) {
  9945. gl.cullFace(this.cullFace);
  9946. this._isCullFaceDirty = false;
  9947. }
  9948. // Depth mask
  9949. if (this._isDepthMaskDirty) {
  9950. gl.depthMask(this.depthMask);
  9951. this._isDepthMaskDirty = false;
  9952. }
  9953. // Depth test
  9954. if (this._isDepthTestDirty) {
  9955. if (this.depthTest) {
  9956. gl.enable(gl.DEPTH_TEST);
  9957. }
  9958. else {
  9959. gl.disable(gl.DEPTH_TEST);
  9960. }
  9961. this._isDepthTestDirty = false;
  9962. }
  9963. // Depth func
  9964. if (this._isDepthFuncDirty) {
  9965. gl.depthFunc(this.depthFunc);
  9966. this._isDepthFuncDirty = false;
  9967. }
  9968. // zOffset
  9969. if (this._isZOffsetDirty) {
  9970. if (this.zOffset) {
  9971. gl.enable(gl.POLYGON_OFFSET_FILL);
  9972. gl.polygonOffset(this.zOffset, 0);
  9973. }
  9974. else {
  9975. gl.disable(gl.POLYGON_OFFSET_FILL);
  9976. }
  9977. this._isZOffsetDirty = false;
  9978. }
  9979. // Front face
  9980. if (this._isFrontFaceDirty) {
  9981. gl.frontFace(this.frontFace);
  9982. this._isFrontFaceDirty = false;
  9983. }
  9984. };
  9985. return _DepthCullingState;
  9986. }());
  9987. BABYLON._DepthCullingState = _DepthCullingState;
  9988. })(BABYLON || (BABYLON = {}));
  9989. //# sourceMappingURL=babylon.depthCullingState.js.map
  9990. var BABYLON;
  9991. (function (BABYLON) {
  9992. var _StencilState = /** @class */ (function () {
  9993. function _StencilState() {
  9994. this._isStencilTestDirty = false;
  9995. this._isStencilMaskDirty = false;
  9996. this._isStencilFuncDirty = false;
  9997. this._isStencilOpDirty = false;
  9998. this.reset();
  9999. }
  10000. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10001. get: function () {
  10002. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10003. },
  10004. enumerable: true,
  10005. configurable: true
  10006. });
  10007. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10008. get: function () {
  10009. return this._stencilFunc;
  10010. },
  10011. set: function (value) {
  10012. if (this._stencilFunc === value) {
  10013. return;
  10014. }
  10015. this._stencilFunc = value;
  10016. this._isStencilFuncDirty = true;
  10017. },
  10018. enumerable: true,
  10019. configurable: true
  10020. });
  10021. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10022. get: function () {
  10023. return this._stencilFuncRef;
  10024. },
  10025. set: function (value) {
  10026. if (this._stencilFuncRef === value) {
  10027. return;
  10028. }
  10029. this._stencilFuncRef = value;
  10030. this._isStencilFuncDirty = true;
  10031. },
  10032. enumerable: true,
  10033. configurable: true
  10034. });
  10035. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10036. get: function () {
  10037. return this._stencilFuncMask;
  10038. },
  10039. set: function (value) {
  10040. if (this._stencilFuncMask === value) {
  10041. return;
  10042. }
  10043. this._stencilFuncMask = value;
  10044. this._isStencilFuncDirty = true;
  10045. },
  10046. enumerable: true,
  10047. configurable: true
  10048. });
  10049. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10050. get: function () {
  10051. return this._stencilOpStencilFail;
  10052. },
  10053. set: function (value) {
  10054. if (this._stencilOpStencilFail === value) {
  10055. return;
  10056. }
  10057. this._stencilOpStencilFail = value;
  10058. this._isStencilOpDirty = true;
  10059. },
  10060. enumerable: true,
  10061. configurable: true
  10062. });
  10063. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10064. get: function () {
  10065. return this._stencilOpDepthFail;
  10066. },
  10067. set: function (value) {
  10068. if (this._stencilOpDepthFail === value) {
  10069. return;
  10070. }
  10071. this._stencilOpDepthFail = value;
  10072. this._isStencilOpDirty = true;
  10073. },
  10074. enumerable: true,
  10075. configurable: true
  10076. });
  10077. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10078. get: function () {
  10079. return this._stencilOpStencilDepthPass;
  10080. },
  10081. set: function (value) {
  10082. if (this._stencilOpStencilDepthPass === value) {
  10083. return;
  10084. }
  10085. this._stencilOpStencilDepthPass = value;
  10086. this._isStencilOpDirty = true;
  10087. },
  10088. enumerable: true,
  10089. configurable: true
  10090. });
  10091. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10092. get: function () {
  10093. return this._stencilMask;
  10094. },
  10095. set: function (value) {
  10096. if (this._stencilMask === value) {
  10097. return;
  10098. }
  10099. this._stencilMask = value;
  10100. this._isStencilMaskDirty = true;
  10101. },
  10102. enumerable: true,
  10103. configurable: true
  10104. });
  10105. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10106. get: function () {
  10107. return this._stencilTest;
  10108. },
  10109. set: function (value) {
  10110. if (this._stencilTest === value) {
  10111. return;
  10112. }
  10113. this._stencilTest = value;
  10114. this._isStencilTestDirty = true;
  10115. },
  10116. enumerable: true,
  10117. configurable: true
  10118. });
  10119. _StencilState.prototype.reset = function () {
  10120. this._stencilTest = false;
  10121. this._stencilMask = 0xFF;
  10122. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10123. this._stencilFuncRef = 1;
  10124. this._stencilFuncMask = 0xFF;
  10125. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10126. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10127. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10128. this._isStencilTestDirty = true;
  10129. this._isStencilMaskDirty = true;
  10130. this._isStencilFuncDirty = true;
  10131. this._isStencilOpDirty = true;
  10132. };
  10133. _StencilState.prototype.apply = function (gl) {
  10134. if (!this.isDirty) {
  10135. return;
  10136. }
  10137. // Stencil test
  10138. if (this._isStencilTestDirty) {
  10139. if (this.stencilTest) {
  10140. gl.enable(gl.STENCIL_TEST);
  10141. }
  10142. else {
  10143. gl.disable(gl.STENCIL_TEST);
  10144. }
  10145. this._isStencilTestDirty = false;
  10146. }
  10147. // Stencil mask
  10148. if (this._isStencilMaskDirty) {
  10149. gl.stencilMask(this.stencilMask);
  10150. this._isStencilMaskDirty = false;
  10151. }
  10152. // Stencil func
  10153. if (this._isStencilFuncDirty) {
  10154. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10155. this._isStencilFuncDirty = false;
  10156. }
  10157. // Stencil op
  10158. if (this._isStencilOpDirty) {
  10159. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10160. this._isStencilOpDirty = false;
  10161. }
  10162. };
  10163. return _StencilState;
  10164. }());
  10165. BABYLON._StencilState = _StencilState;
  10166. })(BABYLON || (BABYLON = {}));
  10167. //# sourceMappingURL=babylon.stencilState.js.map
  10168. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10169. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10170. s = arguments[i];
  10171. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10172. t[p] = s[p];
  10173. }
  10174. return t;
  10175. };
  10176. var BABYLON;
  10177. (function (BABYLON) {
  10178. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10179. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10180. };
  10181. var compileRawShader = function (gl, source, type) {
  10182. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10183. gl.shaderSource(shader, source);
  10184. gl.compileShader(shader);
  10185. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10186. var log = gl.getShaderInfoLog(shader);
  10187. if (log) {
  10188. throw new Error(log);
  10189. }
  10190. }
  10191. if (!shader) {
  10192. throw new Error("Something went wrong while compile the shader.");
  10193. }
  10194. return shader;
  10195. };
  10196. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10197. var magFilter = gl.NEAREST;
  10198. var minFilter = gl.NEAREST;
  10199. switch (samplingMode) {
  10200. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10201. magFilter = gl.LINEAR;
  10202. if (generateMipMaps) {
  10203. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10204. }
  10205. else {
  10206. minFilter = gl.LINEAR;
  10207. }
  10208. break;
  10209. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10210. magFilter = gl.LINEAR;
  10211. if (generateMipMaps) {
  10212. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10213. }
  10214. else {
  10215. minFilter = gl.LINEAR;
  10216. }
  10217. break;
  10218. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10219. magFilter = gl.NEAREST;
  10220. if (generateMipMaps) {
  10221. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10222. }
  10223. else {
  10224. minFilter = gl.NEAREST;
  10225. }
  10226. break;
  10227. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10228. magFilter = gl.NEAREST;
  10229. if (generateMipMaps) {
  10230. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10231. }
  10232. else {
  10233. minFilter = gl.NEAREST;
  10234. }
  10235. break;
  10236. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10237. magFilter = gl.NEAREST;
  10238. if (generateMipMaps) {
  10239. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10240. }
  10241. else {
  10242. minFilter = gl.LINEAR;
  10243. }
  10244. break;
  10245. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10246. magFilter = gl.NEAREST;
  10247. if (generateMipMaps) {
  10248. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10249. }
  10250. else {
  10251. minFilter = gl.LINEAR;
  10252. }
  10253. break;
  10254. case BABYLON.Texture.NEAREST_LINEAR:
  10255. magFilter = gl.NEAREST;
  10256. minFilter = gl.LINEAR;
  10257. break;
  10258. case BABYLON.Texture.NEAREST_NEAREST:
  10259. magFilter = gl.NEAREST;
  10260. minFilter = gl.NEAREST;
  10261. break;
  10262. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10263. magFilter = gl.LINEAR;
  10264. if (generateMipMaps) {
  10265. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10266. }
  10267. else {
  10268. minFilter = gl.NEAREST;
  10269. }
  10270. break;
  10271. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10272. magFilter = gl.LINEAR;
  10273. if (generateMipMaps) {
  10274. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10275. }
  10276. else {
  10277. minFilter = gl.NEAREST;
  10278. }
  10279. break;
  10280. case BABYLON.Texture.LINEAR_LINEAR:
  10281. magFilter = gl.LINEAR;
  10282. minFilter = gl.LINEAR;
  10283. break;
  10284. case BABYLON.Texture.LINEAR_NEAREST:
  10285. magFilter = gl.LINEAR;
  10286. minFilter = gl.NEAREST;
  10287. break;
  10288. }
  10289. return {
  10290. min: minFilter,
  10291. mag: magFilter
  10292. };
  10293. };
  10294. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10295. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10296. var img;
  10297. var onload = function () {
  10298. loadedImages[index] = img;
  10299. loadedImages._internalCount++;
  10300. if (scene) {
  10301. scene._removePendingData(img);
  10302. }
  10303. if (loadedImages._internalCount === 6) {
  10304. onfinish(loadedImages);
  10305. }
  10306. };
  10307. var onerror = function (message, exception) {
  10308. if (scene) {
  10309. scene._removePendingData(img);
  10310. }
  10311. if (onErrorCallBack) {
  10312. onErrorCallBack(message, exception);
  10313. }
  10314. };
  10315. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10316. if (scene) {
  10317. scene._addPendingData(img);
  10318. }
  10319. };
  10320. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10321. if (onError === void 0) { onError = null; }
  10322. var loadedImages = [];
  10323. loadedImages._internalCount = 0;
  10324. for (var index = 0; index < 6; index++) {
  10325. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10326. }
  10327. };
  10328. var BufferPointer = /** @class */ (function () {
  10329. function BufferPointer() {
  10330. }
  10331. return BufferPointer;
  10332. }());
  10333. var InstancingAttributeInfo = /** @class */ (function () {
  10334. function InstancingAttributeInfo() {
  10335. }
  10336. return InstancingAttributeInfo;
  10337. }());
  10338. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10339. /**
  10340. * Define options used to create a render target texture
  10341. */
  10342. var RenderTargetCreationOptions = /** @class */ (function () {
  10343. function RenderTargetCreationOptions() {
  10344. }
  10345. return RenderTargetCreationOptions;
  10346. }());
  10347. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10348. /**
  10349. * Define options used to create a depth texture
  10350. */
  10351. var DepthTextureCreationOptions = /** @class */ (function () {
  10352. function DepthTextureCreationOptions() {
  10353. }
  10354. return DepthTextureCreationOptions;
  10355. }());
  10356. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10357. /**
  10358. * Regroup several parameters relative to the browser in use
  10359. */
  10360. var EngineCapabilities = /** @class */ (function () {
  10361. function EngineCapabilities() {
  10362. }
  10363. return EngineCapabilities;
  10364. }());
  10365. BABYLON.EngineCapabilities = EngineCapabilities;
  10366. /**
  10367. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10368. */
  10369. var Engine = /** @class */ (function () {
  10370. /**
  10371. * @constructor
  10372. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10373. * @param antialias defines enable antialiasing (default: false)
  10374. * @param options defines further options to be sent to the getContext() function
  10375. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10376. */
  10377. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10378. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10379. var _this = this;
  10380. // Public members
  10381. this.forcePOTTextures = false;
  10382. this.isFullscreen = false;
  10383. this.isPointerLock = false;
  10384. this.cullBackFaces = true;
  10385. this.renderEvenInBackground = true;
  10386. this.preventCacheWipeBetweenFrames = false;
  10387. // To enable/disable IDB support and avoid XHR on .manifest
  10388. this.enableOfflineSupport = false;
  10389. this.scenes = new Array();
  10390. this.postProcesses = new Array();
  10391. // Observables
  10392. /**
  10393. * Observable event triggered each time the rendering canvas is resized
  10394. */
  10395. this.onResizeObservable = new BABYLON.Observable();
  10396. /**
  10397. * Observable event triggered each time the canvas loses focus
  10398. */
  10399. this.onCanvasBlurObservable = new BABYLON.Observable();
  10400. /**
  10401. * Observable event triggered each time the canvas gains focus
  10402. */
  10403. this.onCanvasFocusObservable = new BABYLON.Observable();
  10404. /**
  10405. * Observable event triggered each time the canvas receives pointerout event
  10406. */
  10407. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10408. /**
  10409. * Observable event triggered before each texture is initialized
  10410. */
  10411. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10412. //WebVR
  10413. this._vrDisplay = undefined;
  10414. this._vrSupported = false;
  10415. this._vrExclusivePointerMode = false;
  10416. // Uniform buffers list
  10417. this.disableUniformBuffers = false;
  10418. this._uniformBuffers = new Array();
  10419. // Observables
  10420. /**
  10421. * Observable raised when the engine begins a new frame
  10422. */
  10423. this.onBeginFrameObservable = new BABYLON.Observable();
  10424. /**
  10425. * Observable raised when the engine ends the current frame
  10426. */
  10427. this.onEndFrameObservable = new BABYLON.Observable();
  10428. /**
  10429. * Observable raised when the engine is about to compile a shader
  10430. */
  10431. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10432. /**
  10433. * Observable raised when the engine has jsut compiled a shader
  10434. */
  10435. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10436. this._windowIsBackground = false;
  10437. this._webGLVersion = 1.0;
  10438. this._badOS = false;
  10439. this._badDesktopOS = false;
  10440. /**
  10441. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10442. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10443. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10444. */
  10445. this.disableTextureBindingOptimization = false;
  10446. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10447. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10448. this.onVRRequestPresentStart = new BABYLON.Observable();
  10449. this._colorWrite = true;
  10450. this._drawCalls = new BABYLON.PerfCounter();
  10451. this._textureCollisions = new BABYLON.PerfCounter();
  10452. this._renderingQueueLaunched = false;
  10453. this._activeRenderLoops = new Array();
  10454. // Deterministic lockstepMaxSteps
  10455. this._deterministicLockstep = false;
  10456. this._lockstepMaxSteps = 4;
  10457. // Lost context
  10458. this.onContextLostObservable = new BABYLON.Observable();
  10459. this.onContextRestoredObservable = new BABYLON.Observable();
  10460. this._contextWasLost = false;
  10461. this._doNotHandleContextLost = false;
  10462. // FPS
  10463. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10464. this._fps = 60;
  10465. this._deltaTime = 0;
  10466. /**
  10467. * Turn this value on if you want to pause FPS computation when in background
  10468. */
  10469. this.disablePerformanceMonitorInBackground = false;
  10470. // States
  10471. this._depthCullingState = new BABYLON._DepthCullingState();
  10472. this._stencilState = new BABYLON._StencilState();
  10473. this._alphaState = new BABYLON._AlphaState();
  10474. this._alphaMode = Engine.ALPHA_DISABLE;
  10475. // Cache
  10476. this._internalTexturesCache = new Array();
  10477. this._activeChannel = 0;
  10478. this._currentTextureChannel = -1;
  10479. this._boundTexturesCache = {};
  10480. this._compiledEffects = {};
  10481. this._vertexAttribArraysEnabled = [];
  10482. this._uintIndicesCurrentlySet = false;
  10483. this._currentBoundBuffer = new Array();
  10484. this._currentBufferPointers = new Array();
  10485. this._currentInstanceLocations = new Array();
  10486. this._currentInstanceBuffers = new Array();
  10487. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10488. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10489. this._vaoRecordInProgress = false;
  10490. this._mustWipeVertexAttributes = false;
  10491. this._nextFreeTextureSlots = new Array();
  10492. this._maxSimultaneousTextures = 0;
  10493. this._activeRequests = new Array();
  10494. // Hardware supported Compressed Textures
  10495. this._texturesSupported = new Array();
  10496. this._onVRFullScreenTriggered = function () {
  10497. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10498. //get the old size before we change
  10499. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10500. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10501. //get the width and height, change the render size
  10502. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10503. _this.setHardwareScalingLevel(1);
  10504. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10505. }
  10506. else {
  10507. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10508. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10509. }
  10510. };
  10511. this._boundUniforms = {};
  10512. // Register promises
  10513. BABYLON.PromisePolyfill.Apply();
  10514. var canvas = null;
  10515. Engine.Instances.push(this);
  10516. if (!canvasOrContext) {
  10517. return;
  10518. }
  10519. options = options || {};
  10520. if (canvasOrContext.getContext) {
  10521. canvas = canvasOrContext;
  10522. this._renderingCanvas = canvas;
  10523. if (antialias != null) {
  10524. options.antialias = antialias;
  10525. }
  10526. if (options.deterministicLockstep === undefined) {
  10527. options.deterministicLockstep = false;
  10528. }
  10529. if (options.lockstepMaxSteps === undefined) {
  10530. options.lockstepMaxSteps = 4;
  10531. }
  10532. if (options.preserveDrawingBuffer === undefined) {
  10533. options.preserveDrawingBuffer = false;
  10534. }
  10535. if (options.audioEngine === undefined) {
  10536. options.audioEngine = true;
  10537. }
  10538. if (options.stencil === undefined) {
  10539. options.stencil = true;
  10540. }
  10541. this._deterministicLockstep = options.deterministicLockstep;
  10542. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10543. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10544. // Exceptions
  10545. if (navigator && navigator.userAgent) {
  10546. var ua = navigator.userAgent;
  10547. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10548. var exception = _a[_i];
  10549. var key = exception.key;
  10550. var targets = exception.targets;
  10551. if (ua.indexOf(key) > -1) {
  10552. if (exception.capture && exception.captureConstraint) {
  10553. var capture = exception.capture;
  10554. var constraint = exception.captureConstraint;
  10555. var regex = new RegExp(capture);
  10556. var matches = regex.exec(ua);
  10557. if (matches && matches.length > 0) {
  10558. var capturedValue = parseInt(matches[matches.length - 1]);
  10559. if (capturedValue >= constraint) {
  10560. continue;
  10561. }
  10562. }
  10563. }
  10564. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10565. var target = targets_1[_b];
  10566. switch (target) {
  10567. case "uniformBuffer":
  10568. this.disableUniformBuffers = true;
  10569. break;
  10570. case "textureBindingOptimization":
  10571. this.disableTextureBindingOptimization = true;
  10572. break;
  10573. }
  10574. }
  10575. break;
  10576. }
  10577. }
  10578. }
  10579. // GL
  10580. if (!options.disableWebGL2Support) {
  10581. try {
  10582. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10583. if (this._gl) {
  10584. this._webGLVersion = 2.0;
  10585. }
  10586. }
  10587. catch (e) {
  10588. // Do nothing
  10589. }
  10590. }
  10591. if (!this._gl) {
  10592. if (!canvas) {
  10593. throw new Error("The provided canvas is null or undefined.");
  10594. }
  10595. try {
  10596. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10597. }
  10598. catch (e) {
  10599. throw new Error("WebGL not supported");
  10600. }
  10601. }
  10602. if (!this._gl) {
  10603. throw new Error("WebGL not supported");
  10604. }
  10605. this._onCanvasFocus = function () {
  10606. _this.onCanvasFocusObservable.notifyObservers(_this);
  10607. };
  10608. this._onCanvasBlur = function () {
  10609. _this.onCanvasBlurObservable.notifyObservers(_this);
  10610. };
  10611. canvas.addEventListener("focus", this._onCanvasFocus);
  10612. canvas.addEventListener("blur", this._onCanvasBlur);
  10613. this._onBlur = function () {
  10614. if (_this.disablePerformanceMonitorInBackground) {
  10615. _this._performanceMonitor.disable();
  10616. }
  10617. _this._windowIsBackground = true;
  10618. };
  10619. this._onFocus = function () {
  10620. if (_this.disablePerformanceMonitorInBackground) {
  10621. _this._performanceMonitor.enable();
  10622. }
  10623. _this._windowIsBackground = false;
  10624. };
  10625. this._onCanvasPointerOut = function (ev) {
  10626. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10627. };
  10628. window.addEventListener("blur", this._onBlur);
  10629. window.addEventListener("focus", this._onFocus);
  10630. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10631. // Context lost
  10632. if (!this._doNotHandleContextLost) {
  10633. this._onContextLost = function (evt) {
  10634. evt.preventDefault();
  10635. _this._contextWasLost = true;
  10636. BABYLON.Tools.Warn("WebGL context lost.");
  10637. _this.onContextLostObservable.notifyObservers(_this);
  10638. };
  10639. this._onContextRestored = function (evt) {
  10640. // Adding a timeout to avoid race condition at browser level
  10641. setTimeout(function () {
  10642. // Rebuild gl context
  10643. _this._initGLContext();
  10644. // Rebuild effects
  10645. _this._rebuildEffects();
  10646. // Rebuild textures
  10647. _this._rebuildInternalTextures();
  10648. // Rebuild buffers
  10649. _this._rebuildBuffers();
  10650. // Cache
  10651. _this.wipeCaches(true);
  10652. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10653. _this.onContextRestoredObservable.notifyObservers(_this);
  10654. _this._contextWasLost = false;
  10655. }, 0);
  10656. };
  10657. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10658. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10659. }
  10660. }
  10661. else {
  10662. this._gl = canvasOrContext;
  10663. this._renderingCanvas = this._gl.canvas;
  10664. if (this._gl.renderbufferStorageMultisample) {
  10665. this._webGLVersion = 2.0;
  10666. }
  10667. options.stencil = this._gl.getContextAttributes().stencil;
  10668. }
  10669. // Viewport
  10670. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10671. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10672. this.resize();
  10673. this._isStencilEnable = options.stencil ? true : false;
  10674. this._initGLContext();
  10675. if (canvas) {
  10676. // Fullscreen
  10677. this._onFullscreenChange = function () {
  10678. if (document.fullscreen !== undefined) {
  10679. _this.isFullscreen = document.fullscreen;
  10680. }
  10681. else if (document.mozFullScreen !== undefined) {
  10682. _this.isFullscreen = document.mozFullScreen;
  10683. }
  10684. else if (document.webkitIsFullScreen !== undefined) {
  10685. _this.isFullscreen = document.webkitIsFullScreen;
  10686. }
  10687. else if (document.msIsFullScreen !== undefined) {
  10688. _this.isFullscreen = document.msIsFullScreen;
  10689. }
  10690. // Pointer lock
  10691. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10692. canvas.requestPointerLock = canvas.requestPointerLock ||
  10693. canvas.msRequestPointerLock ||
  10694. canvas.mozRequestPointerLock ||
  10695. canvas.webkitRequestPointerLock;
  10696. if (canvas.requestPointerLock) {
  10697. canvas.requestPointerLock();
  10698. }
  10699. }
  10700. };
  10701. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10702. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10703. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10704. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10705. // Pointer lock
  10706. this._onPointerLockChange = function () {
  10707. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10708. document.webkitPointerLockElement === canvas ||
  10709. document.msPointerLockElement === canvas ||
  10710. document.pointerLockElement === canvas);
  10711. };
  10712. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10713. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10714. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10715. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10716. this._onVRDisplayPointerRestricted = function () {
  10717. if (canvas) {
  10718. canvas.requestPointerLock();
  10719. }
  10720. };
  10721. this._onVRDisplayPointerUnrestricted = function () {
  10722. document.exitPointerLock();
  10723. };
  10724. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10725. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10726. }
  10727. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10728. Engine.audioEngine = new BABYLON.AudioEngine();
  10729. }
  10730. // Prepare buffer pointers
  10731. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10732. this._currentBufferPointers[i] = new BufferPointer();
  10733. }
  10734. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10735. // Load WebVR Devices
  10736. if (options.autoEnableWebVR) {
  10737. this.initWebVR();
  10738. }
  10739. // Detect if we are running on a faulty buggy OS.
  10740. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10741. // Detect if we are running on a faulty buggy desktop OS.
  10742. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10743. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10744. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10745. }
  10746. Object.defineProperty(Engine, "LastCreatedEngine", {
  10747. get: function () {
  10748. if (Engine.Instances.length === 0) {
  10749. return null;
  10750. }
  10751. return Engine.Instances[Engine.Instances.length - 1];
  10752. },
  10753. enumerable: true,
  10754. configurable: true
  10755. });
  10756. Object.defineProperty(Engine, "LastCreatedScene", {
  10757. get: function () {
  10758. var lastCreatedEngine = Engine.LastCreatedEngine;
  10759. if (!lastCreatedEngine) {
  10760. return null;
  10761. }
  10762. if (lastCreatedEngine.scenes.length === 0) {
  10763. return null;
  10764. }
  10765. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10766. },
  10767. enumerable: true,
  10768. configurable: true
  10769. });
  10770. /**
  10771. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10772. */
  10773. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10774. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10775. var engine = Engine.Instances[engineIndex];
  10776. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10777. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10778. }
  10779. }
  10780. };
  10781. Object.defineProperty(Engine, "NEVER", {
  10782. get: function () {
  10783. return Engine._NEVER;
  10784. },
  10785. enumerable: true,
  10786. configurable: true
  10787. });
  10788. Object.defineProperty(Engine, "ALWAYS", {
  10789. get: function () {
  10790. return Engine._ALWAYS;
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(Engine, "LESS", {
  10796. get: function () {
  10797. return Engine._LESS;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(Engine, "EQUAL", {
  10803. get: function () {
  10804. return Engine._EQUAL;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(Engine, "LEQUAL", {
  10810. get: function () {
  10811. return Engine._LEQUAL;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(Engine, "GREATER", {
  10817. get: function () {
  10818. return Engine._GREATER;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(Engine, "GEQUAL", {
  10824. get: function () {
  10825. return Engine._GEQUAL;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(Engine, "NOTEQUAL", {
  10831. get: function () {
  10832. return Engine._NOTEQUAL;
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(Engine, "KEEP", {
  10838. get: function () {
  10839. return Engine._KEEP;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(Engine, "REPLACE", {
  10845. get: function () {
  10846. return Engine._REPLACE;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(Engine, "INCR", {
  10852. get: function () {
  10853. return Engine._INCR;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(Engine, "DECR", {
  10859. get: function () {
  10860. return Engine._DECR;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(Engine, "INVERT", {
  10866. get: function () {
  10867. return Engine._INVERT;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(Engine, "INCR_WRAP", {
  10873. get: function () {
  10874. return Engine._INCR_WRAP;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(Engine, "DECR_WRAP", {
  10880. get: function () {
  10881. return Engine._DECR_WRAP;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10887. get: function () {
  10888. return Engine._ALPHA_DISABLE;
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10894. get: function () {
  10895. return Engine._ALPHA_ONEONE;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(Engine, "ALPHA_ADD", {
  10901. get: function () {
  10902. return Engine._ALPHA_ADD;
  10903. },
  10904. enumerable: true,
  10905. configurable: true
  10906. });
  10907. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10908. get: function () {
  10909. return Engine._ALPHA_COMBINE;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10915. get: function () {
  10916. return Engine._ALPHA_SUBTRACT;
  10917. },
  10918. enumerable: true,
  10919. configurable: true
  10920. });
  10921. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10922. get: function () {
  10923. return Engine._ALPHA_MULTIPLY;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10929. get: function () {
  10930. return Engine._ALPHA_MAXIMIZED;
  10931. },
  10932. enumerable: true,
  10933. configurable: true
  10934. });
  10935. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10936. get: function () {
  10937. return Engine._ALPHA_PREMULTIPLIED;
  10938. },
  10939. enumerable: true,
  10940. configurable: true
  10941. });
  10942. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10943. get: function () {
  10944. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10945. },
  10946. enumerable: true,
  10947. configurable: true
  10948. });
  10949. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10950. get: function () {
  10951. return Engine._ALPHA_INTERPOLATE;
  10952. },
  10953. enumerable: true,
  10954. configurable: true
  10955. });
  10956. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10957. get: function () {
  10958. return Engine._ALPHA_SCREENMODE;
  10959. },
  10960. enumerable: true,
  10961. configurable: true
  10962. });
  10963. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10964. get: function () {
  10965. return Engine._DELAYLOADSTATE_NONE;
  10966. },
  10967. enumerable: true,
  10968. configurable: true
  10969. });
  10970. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10971. get: function () {
  10972. return Engine._DELAYLOADSTATE_LOADED;
  10973. },
  10974. enumerable: true,
  10975. configurable: true
  10976. });
  10977. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10978. get: function () {
  10979. return Engine._DELAYLOADSTATE_LOADING;
  10980. },
  10981. enumerable: true,
  10982. configurable: true
  10983. });
  10984. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10985. get: function () {
  10986. return Engine._DELAYLOADSTATE_NOTLOADED;
  10987. },
  10988. enumerable: true,
  10989. configurable: true
  10990. });
  10991. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10992. get: function () {
  10993. return Engine._TEXTUREFORMAT_ALPHA;
  10994. },
  10995. enumerable: true,
  10996. configurable: true
  10997. });
  10998. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10999. get: function () {
  11000. return Engine._TEXTUREFORMAT_LUMINANCE;
  11001. },
  11002. enumerable: true,
  11003. configurable: true
  11004. });
  11005. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11006. /**
  11007. * R32F
  11008. */
  11009. get: function () {
  11010. return Engine._TEXTUREFORMAT_R32F;
  11011. },
  11012. enumerable: true,
  11013. configurable: true
  11014. });
  11015. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11016. /**
  11017. * RG32F
  11018. */
  11019. get: function () {
  11020. return Engine._TEXTUREFORMAT_RG32F;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11026. /**
  11027. * RGB32F
  11028. */
  11029. get: function () {
  11030. return Engine._TEXTUREFORMAT_RGB32F;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11036. /**
  11037. * RGBA32F
  11038. */
  11039. get: function () {
  11040. return Engine._TEXTUREFORMAT_RGBA32F;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11046. get: function () {
  11047. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11053. get: function () {
  11054. return Engine._TEXTUREFORMAT_RGB;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11060. get: function () {
  11061. return Engine._TEXTUREFORMAT_RGBA;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11067. get: function () {
  11068. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11074. get: function () {
  11075. return Engine._TEXTURETYPE_FLOAT;
  11076. },
  11077. enumerable: true,
  11078. configurable: true
  11079. });
  11080. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11081. get: function () {
  11082. return Engine._TEXTURETYPE_HALF_FLOAT;
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11088. get: function () {
  11089. return Engine._SCALEMODE_FLOOR;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11095. get: function () {
  11096. return Engine._SCALEMODE_NEAREST;
  11097. },
  11098. enumerable: true,
  11099. configurable: true
  11100. });
  11101. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11102. get: function () {
  11103. return Engine._SCALEMODE_CEILING;
  11104. },
  11105. enumerable: true,
  11106. configurable: true
  11107. });
  11108. Object.defineProperty(Engine, "Version", {
  11109. get: function () {
  11110. return "3.2.0-alphaB";
  11111. },
  11112. enumerable: true,
  11113. configurable: true
  11114. });
  11115. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11116. get: function () {
  11117. return this._vrExclusivePointerMode;
  11118. },
  11119. enumerable: true,
  11120. configurable: true
  11121. });
  11122. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11123. get: function () {
  11124. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11125. },
  11126. enumerable: true,
  11127. configurable: true
  11128. });
  11129. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11130. get: function () {
  11131. return this._webGLVersion < 2 || this.forcePOTTextures;
  11132. },
  11133. enumerable: true,
  11134. configurable: true
  11135. });
  11136. Object.defineProperty(Engine.prototype, "badOS", {
  11137. get: function () {
  11138. return this._badOS;
  11139. },
  11140. enumerable: true,
  11141. configurable: true
  11142. });
  11143. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11144. get: function () {
  11145. return this._badDesktopOS;
  11146. },
  11147. enumerable: true,
  11148. configurable: true
  11149. });
  11150. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11151. get: function () {
  11152. return this._performanceMonitor;
  11153. },
  11154. enumerable: true,
  11155. configurable: true
  11156. });
  11157. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11158. get: function () {
  11159. return this._texturesSupported;
  11160. },
  11161. enumerable: true,
  11162. configurable: true
  11163. });
  11164. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11165. get: function () {
  11166. return this._textureFormatInUse;
  11167. },
  11168. enumerable: true,
  11169. configurable: true
  11170. });
  11171. Object.defineProperty(Engine.prototype, "currentViewport", {
  11172. get: function () {
  11173. return this._cachedViewport;
  11174. },
  11175. enumerable: true,
  11176. configurable: true
  11177. });
  11178. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11179. // Empty texture
  11180. get: function () {
  11181. if (!this._emptyTexture) {
  11182. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11183. }
  11184. return this._emptyTexture;
  11185. },
  11186. enumerable: true,
  11187. configurable: true
  11188. });
  11189. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11190. get: function () {
  11191. if (!this._emptyTexture3D) {
  11192. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11193. }
  11194. return this._emptyTexture3D;
  11195. },
  11196. enumerable: true,
  11197. configurable: true
  11198. });
  11199. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11200. get: function () {
  11201. if (!this._emptyCubeTexture) {
  11202. var faceData = new Uint8Array(4);
  11203. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11204. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11205. }
  11206. return this._emptyCubeTexture;
  11207. },
  11208. enumerable: true,
  11209. configurable: true
  11210. });
  11211. Engine.prototype._rebuildInternalTextures = function () {
  11212. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11213. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11214. var internalTexture = currentState_1[_i];
  11215. internalTexture._rebuild();
  11216. }
  11217. };
  11218. Engine.prototype._rebuildEffects = function () {
  11219. for (var key in this._compiledEffects) {
  11220. var effect = this._compiledEffects[key];
  11221. effect._prepareEffect();
  11222. }
  11223. BABYLON.Effect.ResetCache();
  11224. };
  11225. Engine.prototype._rebuildBuffers = function () {
  11226. // Index / Vertex
  11227. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11228. var scene = _a[_i];
  11229. scene.resetCachedMaterial();
  11230. scene._rebuildGeometries();
  11231. scene._rebuildTextures();
  11232. }
  11233. // Uniforms
  11234. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11235. var uniformBuffer = _c[_b];
  11236. uniformBuffer._rebuild();
  11237. }
  11238. };
  11239. Engine.prototype._initGLContext = function () {
  11240. // Caps
  11241. this._caps = new EngineCapabilities();
  11242. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11243. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11244. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11245. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11246. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11247. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11248. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11249. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11250. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11251. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11252. // Infos
  11253. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11254. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11255. if (rendererInfo != null) {
  11256. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11257. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11258. }
  11259. if (!this._glVendor) {
  11260. this._glVendor = "Unknown vendor";
  11261. }
  11262. if (!this._glRenderer) {
  11263. this._glRenderer = "Unknown renderer";
  11264. }
  11265. // Constants
  11266. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11267. if (this._gl.RGBA16F !== 0x881A) {
  11268. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11269. }
  11270. if (this._gl.RGBA32F !== 0x8814) {
  11271. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11272. }
  11273. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11274. this._gl.DEPTH24_STENCIL8 = 35056;
  11275. }
  11276. // Extensions
  11277. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11278. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11279. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11280. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11281. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11282. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11283. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11284. 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');
  11285. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11286. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11287. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11288. this._caps.highPrecisionShaderSupported = true;
  11289. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11290. if (this._caps.timerQuery) {
  11291. if (this._webGLVersion === 1) {
  11292. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11293. }
  11294. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11295. }
  11296. // Checks if some of the format renders first to allow the use of webgl inspector.
  11297. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11298. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11299. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11300. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11301. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11302. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11303. if (this._webGLVersion > 1) {
  11304. this._gl.HALF_FLOAT_OES = 0x140B;
  11305. }
  11306. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11307. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11308. // Draw buffers
  11309. if (this._webGLVersion > 1) {
  11310. this._caps.drawBuffersExtension = true;
  11311. }
  11312. else {
  11313. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11314. if (drawBuffersExtension !== null) {
  11315. this._caps.drawBuffersExtension = true;
  11316. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11317. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11318. for (var i = 0; i < 16; i++) {
  11319. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11320. }
  11321. }
  11322. else {
  11323. this._caps.drawBuffersExtension = false;
  11324. }
  11325. }
  11326. // Depth Texture
  11327. if (this._webGLVersion > 1) {
  11328. this._caps.depthTextureExtension = true;
  11329. }
  11330. else {
  11331. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11332. if (depthTextureExtension != null) {
  11333. this._caps.depthTextureExtension = true;
  11334. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11335. }
  11336. }
  11337. // Vertex array object
  11338. if (this._webGLVersion > 1) {
  11339. this._caps.vertexArrayObject = true;
  11340. }
  11341. else {
  11342. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11343. if (vertexArrayObjectExtension != null) {
  11344. this._caps.vertexArrayObject = true;
  11345. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11346. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11347. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11348. }
  11349. else {
  11350. this._caps.vertexArrayObject = false;
  11351. }
  11352. }
  11353. // Instances count
  11354. if (this._webGLVersion > 1) {
  11355. this._caps.instancedArrays = true;
  11356. }
  11357. else {
  11358. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11359. if (instanceExtension != null) {
  11360. this._caps.instancedArrays = true;
  11361. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11362. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11363. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11364. }
  11365. else {
  11366. this._caps.instancedArrays = false;
  11367. }
  11368. }
  11369. // Intelligently add supported compressed formats in order to check for.
  11370. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11371. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11372. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11373. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11374. if (this._caps.astc)
  11375. this.texturesSupported.push('-astc.ktx');
  11376. if (this._caps.s3tc)
  11377. this.texturesSupported.push('-dxt.ktx');
  11378. if (this._caps.pvrtc)
  11379. this.texturesSupported.push('-pvrtc.ktx');
  11380. if (this._caps.etc2)
  11381. this.texturesSupported.push('-etc2.ktx');
  11382. if (this._caps.etc1)
  11383. this.texturesSupported.push('-etc1.ktx');
  11384. if (this._gl.getShaderPrecisionFormat) {
  11385. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11386. if (highp) {
  11387. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11388. }
  11389. }
  11390. // Depth buffer
  11391. this.setDepthBuffer(true);
  11392. this.setDepthFunctionToLessOrEqual();
  11393. this.setDepthWrite(true);
  11394. // Texture maps
  11395. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11396. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11397. this._nextFreeTextureSlots.push(slot);
  11398. }
  11399. };
  11400. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11401. get: function () {
  11402. return this._webGLVersion;
  11403. },
  11404. enumerable: true,
  11405. configurable: true
  11406. });
  11407. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11408. /**
  11409. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11410. */
  11411. get: function () {
  11412. return this._isStencilEnable;
  11413. },
  11414. enumerable: true,
  11415. configurable: true
  11416. });
  11417. Engine.prototype._prepareWorkingCanvas = function () {
  11418. if (this._workingCanvas) {
  11419. return;
  11420. }
  11421. this._workingCanvas = document.createElement("canvas");
  11422. var context = this._workingCanvas.getContext("2d");
  11423. if (context) {
  11424. this._workingContext = context;
  11425. }
  11426. };
  11427. Engine.prototype.resetTextureCache = function () {
  11428. for (var key in this._boundTexturesCache) {
  11429. var boundTexture = this._boundTexturesCache[key];
  11430. if (boundTexture) {
  11431. this._removeDesignatedSlot(boundTexture);
  11432. }
  11433. this._boundTexturesCache[key] = null;
  11434. }
  11435. if (!this.disableTextureBindingOptimization) {
  11436. this._nextFreeTextureSlots = [];
  11437. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11438. this._nextFreeTextureSlots.push(slot);
  11439. }
  11440. }
  11441. this._currentTextureChannel = -1;
  11442. };
  11443. Engine.prototype.isDeterministicLockStep = function () {
  11444. return this._deterministicLockstep;
  11445. };
  11446. Engine.prototype.getLockstepMaxSteps = function () {
  11447. return this._lockstepMaxSteps;
  11448. };
  11449. Engine.prototype.getGlInfo = function () {
  11450. return {
  11451. vendor: this._glVendor,
  11452. renderer: this._glRenderer,
  11453. version: this._glVersion
  11454. };
  11455. };
  11456. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11457. if (useScreen === void 0) { useScreen = false; }
  11458. var viewport = camera.viewport;
  11459. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11460. };
  11461. Engine.prototype.getRenderWidth = function (useScreen) {
  11462. if (useScreen === void 0) { useScreen = false; }
  11463. if (!useScreen && this._currentRenderTarget) {
  11464. return this._currentRenderTarget.width;
  11465. }
  11466. return this._gl.drawingBufferWidth;
  11467. };
  11468. Engine.prototype.getRenderHeight = function (useScreen) {
  11469. if (useScreen === void 0) { useScreen = false; }
  11470. if (!useScreen && this._currentRenderTarget) {
  11471. return this._currentRenderTarget.height;
  11472. }
  11473. return this._gl.drawingBufferHeight;
  11474. };
  11475. Engine.prototype.getRenderingCanvas = function () {
  11476. return this._renderingCanvas;
  11477. };
  11478. Engine.prototype.getRenderingCanvasClientRect = function () {
  11479. if (!this._renderingCanvas) {
  11480. return null;
  11481. }
  11482. return this._renderingCanvas.getBoundingClientRect();
  11483. };
  11484. Engine.prototype.setHardwareScalingLevel = function (level) {
  11485. this._hardwareScalingLevel = level;
  11486. this.resize();
  11487. };
  11488. Engine.prototype.getHardwareScalingLevel = function () {
  11489. return this._hardwareScalingLevel;
  11490. };
  11491. Engine.prototype.getLoadedTexturesCache = function () {
  11492. return this._internalTexturesCache;
  11493. };
  11494. Engine.prototype.getCaps = function () {
  11495. return this._caps;
  11496. };
  11497. Object.defineProperty(Engine.prototype, "drawCalls", {
  11498. /** The number of draw calls submitted last frame */
  11499. get: function () {
  11500. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11501. return 0;
  11502. },
  11503. enumerable: true,
  11504. configurable: true
  11505. });
  11506. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11507. get: function () {
  11508. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11509. return null;
  11510. },
  11511. enumerable: true,
  11512. configurable: true
  11513. });
  11514. Engine.prototype.getDepthFunction = function () {
  11515. return this._depthCullingState.depthFunc;
  11516. };
  11517. Engine.prototype.setDepthFunction = function (depthFunc) {
  11518. this._depthCullingState.depthFunc = depthFunc;
  11519. };
  11520. Engine.prototype.setDepthFunctionToGreater = function () {
  11521. this._depthCullingState.depthFunc = this._gl.GREATER;
  11522. };
  11523. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11524. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11525. };
  11526. Engine.prototype.setDepthFunctionToLess = function () {
  11527. this._depthCullingState.depthFunc = this._gl.LESS;
  11528. };
  11529. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11530. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11531. };
  11532. Engine.prototype.getStencilBuffer = function () {
  11533. return this._stencilState.stencilTest;
  11534. };
  11535. Engine.prototype.setStencilBuffer = function (enable) {
  11536. this._stencilState.stencilTest = enable;
  11537. };
  11538. Engine.prototype.getStencilMask = function () {
  11539. return this._stencilState.stencilMask;
  11540. };
  11541. Engine.prototype.setStencilMask = function (mask) {
  11542. this._stencilState.stencilMask = mask;
  11543. };
  11544. Engine.prototype.getStencilFunction = function () {
  11545. return this._stencilState.stencilFunc;
  11546. };
  11547. Engine.prototype.getStencilFunctionReference = function () {
  11548. return this._stencilState.stencilFuncRef;
  11549. };
  11550. Engine.prototype.getStencilFunctionMask = function () {
  11551. return this._stencilState.stencilFuncMask;
  11552. };
  11553. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11554. this._stencilState.stencilFunc = stencilFunc;
  11555. };
  11556. Engine.prototype.setStencilFunctionReference = function (reference) {
  11557. this._stencilState.stencilFuncRef = reference;
  11558. };
  11559. Engine.prototype.setStencilFunctionMask = function (mask) {
  11560. this._stencilState.stencilFuncMask = mask;
  11561. };
  11562. Engine.prototype.getStencilOperationFail = function () {
  11563. return this._stencilState.stencilOpStencilFail;
  11564. };
  11565. Engine.prototype.getStencilOperationDepthFail = function () {
  11566. return this._stencilState.stencilOpDepthFail;
  11567. };
  11568. Engine.prototype.getStencilOperationPass = function () {
  11569. return this._stencilState.stencilOpStencilDepthPass;
  11570. };
  11571. Engine.prototype.setStencilOperationFail = function (operation) {
  11572. this._stencilState.stencilOpStencilFail = operation;
  11573. };
  11574. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11575. this._stencilState.stencilOpDepthFail = operation;
  11576. };
  11577. Engine.prototype.setStencilOperationPass = function (operation) {
  11578. this._stencilState.stencilOpStencilDepthPass = operation;
  11579. };
  11580. Engine.prototype.setDitheringState = function (value) {
  11581. if (value) {
  11582. this._gl.enable(this._gl.DITHER);
  11583. }
  11584. else {
  11585. this._gl.disable(this._gl.DITHER);
  11586. }
  11587. };
  11588. Engine.prototype.setRasterizerState = function (value) {
  11589. if (value) {
  11590. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11591. }
  11592. else {
  11593. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11594. }
  11595. };
  11596. /**
  11597. * stop executing a render loop function and remove it from the execution array
  11598. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11599. */
  11600. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11601. if (!renderFunction) {
  11602. this._activeRenderLoops = [];
  11603. return;
  11604. }
  11605. var index = this._activeRenderLoops.indexOf(renderFunction);
  11606. if (index >= 0) {
  11607. this._activeRenderLoops.splice(index, 1);
  11608. }
  11609. };
  11610. Engine.prototype._renderLoop = function () {
  11611. if (!this._contextWasLost) {
  11612. var shouldRender = true;
  11613. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11614. shouldRender = false;
  11615. }
  11616. if (shouldRender) {
  11617. // Start new frame
  11618. this.beginFrame();
  11619. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11620. var renderFunction = this._activeRenderLoops[index];
  11621. renderFunction();
  11622. }
  11623. // Present
  11624. this.endFrame();
  11625. }
  11626. }
  11627. if (this._activeRenderLoops.length > 0) {
  11628. // Register new frame
  11629. var requester = null;
  11630. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11631. requester = this._vrDisplay;
  11632. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11633. }
  11634. else {
  11635. this._renderingQueueLaunched = false;
  11636. }
  11637. };
  11638. /**
  11639. * Register and execute a render loop. The engine can have more than one render function.
  11640. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11641. * @example
  11642. * engine.runRenderLoop(function () {
  11643. * scene.render()
  11644. * })
  11645. */
  11646. Engine.prototype.runRenderLoop = function (renderFunction) {
  11647. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11648. return;
  11649. }
  11650. this._activeRenderLoops.push(renderFunction);
  11651. if (!this._renderingQueueLaunched) {
  11652. this._renderingQueueLaunched = true;
  11653. this._bindedRenderFunction = this._renderLoop.bind(this);
  11654. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11655. }
  11656. };
  11657. /**
  11658. * Toggle full screen mode.
  11659. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11660. * @param {any} options - an options object to be sent to the requestFullscreen function
  11661. */
  11662. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11663. if (this.isFullscreen) {
  11664. BABYLON.Tools.ExitFullscreen();
  11665. }
  11666. else {
  11667. this._pointerLockRequested = requestPointerLock;
  11668. if (this._renderingCanvas) {
  11669. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11670. }
  11671. }
  11672. };
  11673. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11674. if (stencil === void 0) { stencil = false; }
  11675. this.applyStates();
  11676. var mode = 0;
  11677. if (backBuffer && color) {
  11678. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11679. mode |= this._gl.COLOR_BUFFER_BIT;
  11680. }
  11681. if (depth) {
  11682. this._gl.clearDepth(1.0);
  11683. mode |= this._gl.DEPTH_BUFFER_BIT;
  11684. }
  11685. if (stencil) {
  11686. this._gl.clearStencil(0);
  11687. mode |= this._gl.STENCIL_BUFFER_BIT;
  11688. }
  11689. this._gl.clear(mode);
  11690. };
  11691. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11692. var gl = this._gl;
  11693. // Save state
  11694. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11695. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11696. // Change state
  11697. gl.enable(gl.SCISSOR_TEST);
  11698. gl.scissor(x, y, width, height);
  11699. // Clear
  11700. this.clear(clearColor, true, true, true);
  11701. // Restore state
  11702. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11703. if (curScissor === true) {
  11704. gl.enable(gl.SCISSOR_TEST);
  11705. }
  11706. else {
  11707. gl.disable(gl.SCISSOR_TEST);
  11708. }
  11709. };
  11710. /**
  11711. * Set the WebGL's viewport
  11712. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11713. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11714. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11715. */
  11716. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11717. var width = requiredWidth || this.getRenderWidth();
  11718. var height = requiredHeight || this.getRenderHeight();
  11719. var x = viewport.x || 0;
  11720. var y = viewport.y || 0;
  11721. this._cachedViewport = viewport;
  11722. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11723. };
  11724. /**
  11725. * Directly set the WebGL Viewport
  11726. * The x, y, width & height are directly passed to the WebGL call
  11727. * @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.
  11728. */
  11729. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11730. var currentViewport = this._cachedViewport;
  11731. this._cachedViewport = null;
  11732. this._gl.viewport(x, y, width, height);
  11733. return currentViewport;
  11734. };
  11735. Engine.prototype.beginFrame = function () {
  11736. this.onBeginFrameObservable.notifyObservers(this);
  11737. this._measureFps();
  11738. };
  11739. Engine.prototype.endFrame = function () {
  11740. //force a flush in case we are using a bad OS.
  11741. if (this._badOS) {
  11742. this.flushFramebuffer();
  11743. }
  11744. //submit frame to the vr device, if enabled
  11745. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11746. // TODO: We should only submit the frame if we read frameData successfully.
  11747. this._vrDisplay.submitFrame();
  11748. }
  11749. this.onEndFrameObservable.notifyObservers(this);
  11750. };
  11751. /**
  11752. * resize the view according to the canvas' size.
  11753. * @example
  11754. * window.addEventListener("resize", function () {
  11755. * engine.resize();
  11756. * });
  11757. */
  11758. Engine.prototype.resize = function () {
  11759. // We're not resizing the size of the canvas while in VR mode & presenting
  11760. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11761. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11762. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11763. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11764. }
  11765. };
  11766. /**
  11767. * force a specific size of the canvas
  11768. * @param {number} width - the new canvas' width
  11769. * @param {number} height - the new canvas' height
  11770. */
  11771. Engine.prototype.setSize = function (width, height) {
  11772. if (!this._renderingCanvas) {
  11773. return;
  11774. }
  11775. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11776. return;
  11777. }
  11778. this._renderingCanvas.width = width;
  11779. this._renderingCanvas.height = height;
  11780. for (var index = 0; index < this.scenes.length; index++) {
  11781. var scene = this.scenes[index];
  11782. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11783. var cam = scene.cameras[camIndex];
  11784. cam._currentRenderId = 0;
  11785. }
  11786. }
  11787. if (this.onResizeObservable.hasObservers) {
  11788. this.onResizeObservable.notifyObservers(this);
  11789. }
  11790. };
  11791. // WebVR functions
  11792. Engine.prototype.isVRDevicePresent = function () {
  11793. return !!this._vrDisplay;
  11794. };
  11795. Engine.prototype.getVRDevice = function () {
  11796. return this._vrDisplay;
  11797. };
  11798. /**
  11799. * Initializes a webVR display and starts listening to display change events.
  11800. * The onVRDisplayChangedObservable will be notified upon these changes.
  11801. * @returns The onVRDisplayChangedObservable.
  11802. */
  11803. Engine.prototype.initWebVR = function () {
  11804. this.initWebVRAsync();
  11805. return this.onVRDisplayChangedObservable;
  11806. };
  11807. /**
  11808. * Initializes a webVR display and starts listening to display change events.
  11809. * The onVRDisplayChangedObservable will be notified upon these changes.
  11810. * @returns A promise containing a VRDisplay and if vr is supported.
  11811. */
  11812. Engine.prototype.initWebVRAsync = function () {
  11813. var _this = this;
  11814. var notifyObservers = function () {
  11815. var eventArgs = {
  11816. vrDisplay: _this._vrDisplay,
  11817. vrSupported: _this._vrSupported
  11818. };
  11819. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11820. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11821. };
  11822. if (!this._onVrDisplayConnect) {
  11823. this._onVrDisplayConnect = function (event) {
  11824. _this._vrDisplay = event.display;
  11825. notifyObservers();
  11826. };
  11827. this._onVrDisplayDisconnect = function () {
  11828. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11829. _this._vrDisplay = undefined;
  11830. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11831. notifyObservers();
  11832. };
  11833. this._onVrDisplayPresentChange = function () {
  11834. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11835. };
  11836. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11837. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11838. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11839. }
  11840. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11841. this._webVRInitPromise.then(notifyObservers);
  11842. return this._webVRInitPromise;
  11843. };
  11844. Engine.prototype.enableVR = function () {
  11845. var _this = this;
  11846. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11847. var onResolved = function () {
  11848. _this.onVRRequestPresentComplete.notifyObservers(true);
  11849. _this._onVRFullScreenTriggered();
  11850. };
  11851. var onRejected = function () {
  11852. _this.onVRRequestPresentComplete.notifyObservers(false);
  11853. };
  11854. this.onVRRequestPresentStart.notifyObservers(this);
  11855. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11856. }
  11857. };
  11858. Engine.prototype.disableVR = function () {
  11859. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11860. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11861. }
  11862. };
  11863. Engine.prototype._getVRDisplaysAsync = function () {
  11864. var _this = this;
  11865. return new Promise(function (res, rej) {
  11866. if (navigator.getVRDisplays) {
  11867. navigator.getVRDisplays().then(function (devices) {
  11868. _this._vrSupported = true;
  11869. // note that devices may actually be an empty array. This is fine;
  11870. // we expect this._vrDisplay to be undefined in this case.
  11871. _this._vrDisplay = devices[0];
  11872. res({
  11873. vrDisplay: _this._vrDisplay,
  11874. vrSupported: _this._vrSupported
  11875. });
  11876. });
  11877. }
  11878. else {
  11879. _this._vrDisplay = undefined;
  11880. _this._vrSupported = false;
  11881. res({
  11882. vrDisplay: _this._vrDisplay,
  11883. vrSupported: _this._vrSupported
  11884. });
  11885. }
  11886. });
  11887. };
  11888. /**
  11889. * Binds the frame buffer to the specified texture.
  11890. * @param texture The texture to render to or null for the default canvas
  11891. * @param faceIndex The face of the texture to render to in case of cube texture
  11892. * @param requiredWidth The width of the target to render to
  11893. * @param requiredHeight The height of the target to render to
  11894. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11895. * @param depthStencilTexture The depth stencil texture to use to render
  11896. */
  11897. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11898. if (this._currentRenderTarget) {
  11899. this.unBindFramebuffer(this._currentRenderTarget);
  11900. }
  11901. this._currentRenderTarget = texture;
  11902. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11903. var gl = this._gl;
  11904. if (texture.isCube) {
  11905. if (faceIndex === undefined) {
  11906. faceIndex = 0;
  11907. }
  11908. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11909. if (depthStencilTexture) {
  11910. if (depthStencilTexture._generateStencilBuffer) {
  11911. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11912. }
  11913. else {
  11914. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11915. }
  11916. }
  11917. }
  11918. if (this._cachedViewport && !forceFullscreenViewport) {
  11919. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11920. }
  11921. else {
  11922. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11923. }
  11924. this.wipeCaches();
  11925. };
  11926. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11927. if (this._currentFramebuffer !== framebuffer) {
  11928. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11929. this._currentFramebuffer = framebuffer;
  11930. }
  11931. };
  11932. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11933. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11934. this._currentRenderTarget = null;
  11935. // If MSAA, we need to bitblt back to main texture
  11936. var gl = this._gl;
  11937. if (texture._MSAAFramebuffer) {
  11938. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11939. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11940. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11941. }
  11942. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11943. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11944. gl.generateMipmap(gl.TEXTURE_2D);
  11945. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11946. }
  11947. if (onBeforeUnbind) {
  11948. if (texture._MSAAFramebuffer) {
  11949. // Bind the correct framebuffer
  11950. this.bindUnboundFramebuffer(texture._framebuffer);
  11951. }
  11952. onBeforeUnbind();
  11953. }
  11954. this.bindUnboundFramebuffer(null);
  11955. };
  11956. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11957. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11958. this._currentRenderTarget = null;
  11959. // If MSAA, we need to bitblt back to main texture
  11960. var gl = this._gl;
  11961. if (textures[0]._MSAAFramebuffer) {
  11962. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11963. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11964. var attachments = textures[0]._attachments;
  11965. if (!attachments) {
  11966. attachments = new Array(textures.length);
  11967. textures[0]._attachments = attachments;
  11968. }
  11969. for (var i = 0; i < textures.length; i++) {
  11970. var texture = textures[i];
  11971. for (var j = 0; j < attachments.length; j++) {
  11972. attachments[j] = gl.NONE;
  11973. }
  11974. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11975. gl.readBuffer(attachments[i]);
  11976. gl.drawBuffers(attachments);
  11977. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11978. }
  11979. for (var i = 0; i < attachments.length; i++) {
  11980. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11981. }
  11982. gl.drawBuffers(attachments);
  11983. }
  11984. for (var i = 0; i < textures.length; i++) {
  11985. var texture = textures[i];
  11986. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11987. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11988. gl.generateMipmap(gl.TEXTURE_2D);
  11989. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11990. }
  11991. }
  11992. if (onBeforeUnbind) {
  11993. if (textures[0]._MSAAFramebuffer) {
  11994. // Bind the correct framebuffer
  11995. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11996. }
  11997. onBeforeUnbind();
  11998. }
  11999. this.bindUnboundFramebuffer(null);
  12000. };
  12001. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12002. if (texture.generateMipMaps) {
  12003. var gl = this._gl;
  12004. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12005. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12006. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12007. }
  12008. };
  12009. Engine.prototype.flushFramebuffer = function () {
  12010. this._gl.flush();
  12011. };
  12012. Engine.prototype.restoreDefaultFramebuffer = function () {
  12013. if (this._currentRenderTarget) {
  12014. this.unBindFramebuffer(this._currentRenderTarget);
  12015. }
  12016. else {
  12017. this.bindUnboundFramebuffer(null);
  12018. }
  12019. if (this._cachedViewport) {
  12020. this.setViewport(this._cachedViewport);
  12021. }
  12022. this.wipeCaches();
  12023. };
  12024. // UBOs
  12025. Engine.prototype.createUniformBuffer = function (elements) {
  12026. var ubo = this._gl.createBuffer();
  12027. if (!ubo) {
  12028. throw new Error("Unable to create uniform buffer");
  12029. }
  12030. this.bindUniformBuffer(ubo);
  12031. if (elements instanceof Float32Array) {
  12032. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12033. }
  12034. else {
  12035. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12036. }
  12037. this.bindUniformBuffer(null);
  12038. ubo.references = 1;
  12039. return ubo;
  12040. };
  12041. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12042. var ubo = this._gl.createBuffer();
  12043. if (!ubo) {
  12044. throw new Error("Unable to create dynamic uniform buffer");
  12045. }
  12046. this.bindUniformBuffer(ubo);
  12047. if (elements instanceof Float32Array) {
  12048. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12049. }
  12050. else {
  12051. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12052. }
  12053. this.bindUniformBuffer(null);
  12054. ubo.references = 1;
  12055. return ubo;
  12056. };
  12057. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12058. this.bindUniformBuffer(uniformBuffer);
  12059. if (offset === undefined) {
  12060. offset = 0;
  12061. }
  12062. if (count === undefined) {
  12063. if (elements instanceof Float32Array) {
  12064. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12065. }
  12066. else {
  12067. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12068. }
  12069. }
  12070. else {
  12071. if (elements instanceof Float32Array) {
  12072. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12073. }
  12074. else {
  12075. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12076. }
  12077. }
  12078. this.bindUniformBuffer(null);
  12079. };
  12080. // VBOs
  12081. Engine.prototype._resetVertexBufferBinding = function () {
  12082. this.bindArrayBuffer(null);
  12083. this._cachedVertexBuffers = null;
  12084. };
  12085. Engine.prototype.createVertexBuffer = function (vertices) {
  12086. var vbo = this._gl.createBuffer();
  12087. if (!vbo) {
  12088. throw new Error("Unable to create vertex buffer");
  12089. }
  12090. this.bindArrayBuffer(vbo);
  12091. if (vertices instanceof Float32Array) {
  12092. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12093. }
  12094. else {
  12095. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12096. }
  12097. this._resetVertexBufferBinding();
  12098. vbo.references = 1;
  12099. return vbo;
  12100. };
  12101. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12102. var vbo = this._gl.createBuffer();
  12103. if (!vbo) {
  12104. throw new Error("Unable to create dynamic vertex buffer");
  12105. }
  12106. this.bindArrayBuffer(vbo);
  12107. if (vertices instanceof Float32Array) {
  12108. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12109. }
  12110. else {
  12111. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12112. }
  12113. this._resetVertexBufferBinding();
  12114. vbo.references = 1;
  12115. return vbo;
  12116. };
  12117. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12118. if (offset === void 0) { offset = 0; }
  12119. // Force cache update
  12120. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12121. this.bindIndexBuffer(indexBuffer);
  12122. var arrayBuffer;
  12123. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12124. arrayBuffer = indices;
  12125. }
  12126. else {
  12127. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12128. }
  12129. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12130. this._resetIndexBufferBinding();
  12131. };
  12132. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12133. this.bindArrayBuffer(vertexBuffer);
  12134. if (offset === undefined) {
  12135. offset = 0;
  12136. }
  12137. if (count === undefined) {
  12138. if (vertices instanceof Float32Array) {
  12139. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12140. }
  12141. else {
  12142. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12143. }
  12144. }
  12145. else {
  12146. if (vertices instanceof Float32Array) {
  12147. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12148. }
  12149. else {
  12150. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12151. }
  12152. }
  12153. this._resetVertexBufferBinding();
  12154. };
  12155. Engine.prototype._resetIndexBufferBinding = function () {
  12156. this.bindIndexBuffer(null);
  12157. this._cachedIndexBuffer = null;
  12158. };
  12159. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12160. var vbo = this._gl.createBuffer();
  12161. if (!vbo) {
  12162. throw new Error("Unable to create index buffer");
  12163. }
  12164. this.bindIndexBuffer(vbo);
  12165. // Check for 32 bits indices
  12166. var arrayBuffer;
  12167. var need32Bits = false;
  12168. if (indices instanceof Uint16Array) {
  12169. arrayBuffer = indices;
  12170. }
  12171. else {
  12172. //check 32 bit support
  12173. if (this._caps.uintIndices) {
  12174. if (indices instanceof Uint32Array) {
  12175. arrayBuffer = indices;
  12176. need32Bits = true;
  12177. }
  12178. else {
  12179. //number[] or Int32Array, check if 32 bit is necessary
  12180. for (var index = 0; index < indices.length; index++) {
  12181. if (indices[index] > 65535) {
  12182. need32Bits = true;
  12183. break;
  12184. }
  12185. }
  12186. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12187. }
  12188. }
  12189. else {
  12190. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12191. arrayBuffer = new Uint16Array(indices);
  12192. }
  12193. }
  12194. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12195. this._resetIndexBufferBinding();
  12196. vbo.references = 1;
  12197. vbo.is32Bits = need32Bits;
  12198. return vbo;
  12199. };
  12200. Engine.prototype.bindArrayBuffer = function (buffer) {
  12201. if (!this._vaoRecordInProgress) {
  12202. this._unbindVertexArrayObject();
  12203. }
  12204. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12205. };
  12206. Engine.prototype.bindUniformBuffer = function (buffer) {
  12207. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12208. };
  12209. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12210. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12211. };
  12212. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12213. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12214. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12215. };
  12216. ;
  12217. Engine.prototype.bindIndexBuffer = function (buffer) {
  12218. if (!this._vaoRecordInProgress) {
  12219. this._unbindVertexArrayObject();
  12220. }
  12221. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12222. };
  12223. Engine.prototype.bindBuffer = function (buffer, target) {
  12224. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12225. this._gl.bindBuffer(target, buffer);
  12226. this._currentBoundBuffer[target] = buffer;
  12227. }
  12228. };
  12229. Engine.prototype.updateArrayBuffer = function (data) {
  12230. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12231. };
  12232. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12233. var pointer = this._currentBufferPointers[indx];
  12234. var changed = false;
  12235. if (!pointer.active) {
  12236. changed = true;
  12237. pointer.active = true;
  12238. pointer.index = indx;
  12239. pointer.size = size;
  12240. pointer.type = type;
  12241. pointer.normalized = normalized;
  12242. pointer.stride = stride;
  12243. pointer.offset = offset;
  12244. pointer.buffer = buffer;
  12245. }
  12246. else {
  12247. if (pointer.buffer !== buffer) {
  12248. pointer.buffer = buffer;
  12249. changed = true;
  12250. }
  12251. if (pointer.size !== size) {
  12252. pointer.size = size;
  12253. changed = true;
  12254. }
  12255. if (pointer.type !== type) {
  12256. pointer.type = type;
  12257. changed = true;
  12258. }
  12259. if (pointer.normalized !== normalized) {
  12260. pointer.normalized = normalized;
  12261. changed = true;
  12262. }
  12263. if (pointer.stride !== stride) {
  12264. pointer.stride = stride;
  12265. changed = true;
  12266. }
  12267. if (pointer.offset !== offset) {
  12268. pointer.offset = offset;
  12269. changed = true;
  12270. }
  12271. }
  12272. if (changed || this._vaoRecordInProgress) {
  12273. this.bindArrayBuffer(buffer);
  12274. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12275. }
  12276. };
  12277. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12278. if (indexBuffer == null) {
  12279. return;
  12280. }
  12281. if (this._cachedIndexBuffer !== indexBuffer) {
  12282. this._cachedIndexBuffer = indexBuffer;
  12283. this.bindIndexBuffer(indexBuffer);
  12284. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12285. }
  12286. };
  12287. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12288. var attributes = effect.getAttributesNames();
  12289. if (!this._vaoRecordInProgress) {
  12290. this._unbindVertexArrayObject();
  12291. }
  12292. this.unbindAllAttributes();
  12293. for (var index = 0; index < attributes.length; index++) {
  12294. var order = effect.getAttributeLocation(index);
  12295. if (order >= 0) {
  12296. var vertexBuffer = vertexBuffers[attributes[index]];
  12297. if (!vertexBuffer) {
  12298. continue;
  12299. }
  12300. this._gl.enableVertexAttribArray(order);
  12301. if (!this._vaoRecordInProgress) {
  12302. this._vertexAttribArraysEnabled[order] = true;
  12303. }
  12304. var buffer = vertexBuffer.getBuffer();
  12305. if (buffer) {
  12306. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12307. if (vertexBuffer.getIsInstanced()) {
  12308. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12309. if (!this._vaoRecordInProgress) {
  12310. this._currentInstanceLocations.push(order);
  12311. this._currentInstanceBuffers.push(buffer);
  12312. }
  12313. }
  12314. }
  12315. }
  12316. }
  12317. };
  12318. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12319. var vao = this._gl.createVertexArray();
  12320. this._vaoRecordInProgress = true;
  12321. this._gl.bindVertexArray(vao);
  12322. this._mustWipeVertexAttributes = true;
  12323. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12324. this.bindIndexBuffer(indexBuffer);
  12325. this._vaoRecordInProgress = false;
  12326. this._gl.bindVertexArray(null);
  12327. return vao;
  12328. };
  12329. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12330. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12331. this._cachedVertexArrayObject = vertexArrayObject;
  12332. this._gl.bindVertexArray(vertexArrayObject);
  12333. this._cachedVertexBuffers = null;
  12334. this._cachedIndexBuffer = null;
  12335. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12336. this._mustWipeVertexAttributes = true;
  12337. }
  12338. };
  12339. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12340. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12341. this._cachedVertexBuffers = vertexBuffer;
  12342. this._cachedEffectForVertexBuffers = effect;
  12343. var attributesCount = effect.getAttributesCount();
  12344. this._unbindVertexArrayObject();
  12345. this.unbindAllAttributes();
  12346. var offset = 0;
  12347. for (var index = 0; index < attributesCount; index++) {
  12348. if (index < vertexDeclaration.length) {
  12349. var order = effect.getAttributeLocation(index);
  12350. if (order >= 0) {
  12351. this._gl.enableVertexAttribArray(order);
  12352. this._vertexAttribArraysEnabled[order] = true;
  12353. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12354. }
  12355. offset += vertexDeclaration[index] * 4;
  12356. }
  12357. }
  12358. }
  12359. this._bindIndexBufferWithCache(indexBuffer);
  12360. };
  12361. Engine.prototype._unbindVertexArrayObject = function () {
  12362. if (!this._cachedVertexArrayObject) {
  12363. return;
  12364. }
  12365. this._cachedVertexArrayObject = null;
  12366. this._gl.bindVertexArray(null);
  12367. };
  12368. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12369. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12370. this._cachedVertexBuffers = vertexBuffers;
  12371. this._cachedEffectForVertexBuffers = effect;
  12372. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12373. }
  12374. this._bindIndexBufferWithCache(indexBuffer);
  12375. };
  12376. Engine.prototype.unbindInstanceAttributes = function () {
  12377. var boundBuffer;
  12378. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12379. var instancesBuffer = this._currentInstanceBuffers[i];
  12380. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12381. boundBuffer = instancesBuffer;
  12382. this.bindArrayBuffer(instancesBuffer);
  12383. }
  12384. var offsetLocation = this._currentInstanceLocations[i];
  12385. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12386. }
  12387. this._currentInstanceBuffers.length = 0;
  12388. this._currentInstanceLocations.length = 0;
  12389. };
  12390. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12391. this._gl.deleteVertexArray(vao);
  12392. };
  12393. Engine.prototype._releaseBuffer = function (buffer) {
  12394. buffer.references--;
  12395. if (buffer.references === 0) {
  12396. this._gl.deleteBuffer(buffer);
  12397. return true;
  12398. }
  12399. return false;
  12400. };
  12401. Engine.prototype.createInstancesBuffer = function (capacity) {
  12402. var buffer = this._gl.createBuffer();
  12403. if (!buffer) {
  12404. throw new Error("Unable to create instance buffer");
  12405. }
  12406. buffer.capacity = capacity;
  12407. this.bindArrayBuffer(buffer);
  12408. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12409. return buffer;
  12410. };
  12411. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12412. this._gl.deleteBuffer(buffer);
  12413. };
  12414. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12415. this.bindArrayBuffer(instancesBuffer);
  12416. if (data) {
  12417. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12418. }
  12419. if (offsetLocations[0].index !== undefined) {
  12420. var stride = 0;
  12421. for (var i = 0; i < offsetLocations.length; i++) {
  12422. var ai = offsetLocations[i];
  12423. stride += ai.attributeSize * 4;
  12424. }
  12425. for (var i = 0; i < offsetLocations.length; i++) {
  12426. var ai = offsetLocations[i];
  12427. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12428. this._gl.enableVertexAttribArray(ai.index);
  12429. this._vertexAttribArraysEnabled[ai.index] = true;
  12430. }
  12431. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12432. this._gl.vertexAttribDivisor(ai.index, 1);
  12433. this._currentInstanceLocations.push(ai.index);
  12434. this._currentInstanceBuffers.push(instancesBuffer);
  12435. }
  12436. }
  12437. else {
  12438. for (var index = 0; index < 4; index++) {
  12439. var offsetLocation = offsetLocations[index];
  12440. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12441. this._gl.enableVertexAttribArray(offsetLocation);
  12442. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12443. }
  12444. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12445. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12446. this._currentInstanceLocations.push(offsetLocation);
  12447. this._currentInstanceBuffers.push(instancesBuffer);
  12448. }
  12449. }
  12450. };
  12451. Engine.prototype.applyStates = function () {
  12452. this._depthCullingState.apply(this._gl);
  12453. this._stencilState.apply(this._gl);
  12454. this._alphaState.apply(this._gl);
  12455. };
  12456. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12457. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12458. };
  12459. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12460. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12461. };
  12462. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12463. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12464. };
  12465. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12466. // Apply states
  12467. this.applyStates();
  12468. this._drawCalls.addCount(1, false);
  12469. // Render
  12470. var drawMode = this.DrawMode(fillMode);
  12471. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12472. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12473. if (instancesCount) {
  12474. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12475. }
  12476. else {
  12477. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12478. }
  12479. };
  12480. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12481. // Apply states
  12482. this.applyStates();
  12483. this._drawCalls.addCount(1, false);
  12484. var drawMode = this.DrawMode(fillMode);
  12485. if (instancesCount) {
  12486. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12487. }
  12488. else {
  12489. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12490. }
  12491. };
  12492. Engine.prototype.DrawMode = function (fillMode) {
  12493. switch (fillMode) {
  12494. // Triangle views
  12495. case BABYLON.Material.TriangleFillMode:
  12496. return this._gl.TRIANGLES;
  12497. case BABYLON.Material.PointFillMode:
  12498. return this._gl.POINTS;
  12499. case BABYLON.Material.WireFrameFillMode:
  12500. return this._gl.LINES;
  12501. // Draw modes
  12502. case BABYLON.Material.PointListDrawMode:
  12503. return this._gl.POINTS;
  12504. case BABYLON.Material.LineListDrawMode:
  12505. return this._gl.LINES;
  12506. case BABYLON.Material.LineLoopDrawMode:
  12507. return this._gl.LINE_LOOP;
  12508. case BABYLON.Material.LineStripDrawMode:
  12509. return this._gl.LINE_STRIP;
  12510. case BABYLON.Material.TriangleStripDrawMode:
  12511. return this._gl.TRIANGLE_STRIP;
  12512. case BABYLON.Material.TriangleFanDrawMode:
  12513. return this._gl.TRIANGLE_FAN;
  12514. default:
  12515. return this._gl.TRIANGLES;
  12516. }
  12517. };
  12518. // Shaders
  12519. Engine.prototype._releaseEffect = function (effect) {
  12520. if (this._compiledEffects[effect._key]) {
  12521. delete this._compiledEffects[effect._key];
  12522. this._deleteProgram(effect.getProgram());
  12523. }
  12524. };
  12525. Engine.prototype._deleteProgram = function (program) {
  12526. if (program) {
  12527. program.__SPECTOR_rebuildProgram = null;
  12528. if (program.transformFeedback) {
  12529. this.deleteTransformFeedback(program.transformFeedback);
  12530. program.transformFeedback = null;
  12531. }
  12532. this._gl.deleteProgram(program);
  12533. }
  12534. };
  12535. /**
  12536. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12537. * @param samplers An array of string used to represent textures
  12538. */
  12539. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12540. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12541. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12542. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12543. if (this._compiledEffects[name]) {
  12544. var compiledEffect = this._compiledEffects[name];
  12545. if (onCompiled && compiledEffect.isReady()) {
  12546. onCompiled(compiledEffect);
  12547. }
  12548. return compiledEffect;
  12549. }
  12550. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12551. effect._key = name;
  12552. this._compiledEffects[name] = effect;
  12553. return effect;
  12554. };
  12555. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12556. if (uniformsNames === void 0) { uniformsNames = []; }
  12557. if (samplers === void 0) { samplers = []; }
  12558. if (defines === void 0) { defines = ""; }
  12559. return this.createEffect({
  12560. vertex: "particles",
  12561. fragmentElement: fragmentName
  12562. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12563. };
  12564. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12565. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12566. context = context || this._gl;
  12567. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12568. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12569. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12570. };
  12571. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12572. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12573. context = context || this._gl;
  12574. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12575. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12576. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12577. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12578. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12579. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12580. return program;
  12581. };
  12582. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12583. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12584. var shaderProgram = context.createProgram();
  12585. if (!shaderProgram) {
  12586. throw new Error("Unable to create program");
  12587. }
  12588. context.attachShader(shaderProgram, vertexShader);
  12589. context.attachShader(shaderProgram, fragmentShader);
  12590. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12591. var transformFeedback = this.createTransformFeedback();
  12592. this.bindTransformFeedback(transformFeedback);
  12593. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12594. shaderProgram.transformFeedback = transformFeedback;
  12595. }
  12596. context.linkProgram(shaderProgram);
  12597. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12598. this.bindTransformFeedback(null);
  12599. }
  12600. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12601. if (!linked) {
  12602. context.validateProgram(shaderProgram);
  12603. var error = context.getProgramInfoLog(shaderProgram);
  12604. if (error) {
  12605. throw new Error(error);
  12606. }
  12607. }
  12608. context.deleteShader(vertexShader);
  12609. context.deleteShader(fragmentShader);
  12610. return shaderProgram;
  12611. };
  12612. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12613. var results = new Array();
  12614. for (var index = 0; index < uniformsNames.length; index++) {
  12615. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12616. }
  12617. return results;
  12618. };
  12619. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12620. var results = [];
  12621. for (var index = 0; index < attributesNames.length; index++) {
  12622. try {
  12623. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12624. }
  12625. catch (e) {
  12626. results.push(-1);
  12627. }
  12628. }
  12629. return results;
  12630. };
  12631. Engine.prototype.enableEffect = function (effect) {
  12632. if (!effect) {
  12633. return;
  12634. }
  12635. // Use program
  12636. this.bindSamplers(effect);
  12637. this._currentEffect = effect;
  12638. if (effect.onBind) {
  12639. effect.onBind(effect);
  12640. }
  12641. effect.onBindObservable.notifyObservers(effect);
  12642. };
  12643. Engine.prototype.setIntArray = function (uniform, array) {
  12644. if (!uniform)
  12645. return;
  12646. this._gl.uniform1iv(uniform, array);
  12647. };
  12648. Engine.prototype.setIntArray2 = function (uniform, array) {
  12649. if (!uniform || array.length % 2 !== 0)
  12650. return;
  12651. this._gl.uniform2iv(uniform, array);
  12652. };
  12653. Engine.prototype.setIntArray3 = function (uniform, array) {
  12654. if (!uniform || array.length % 3 !== 0)
  12655. return;
  12656. this._gl.uniform3iv(uniform, array);
  12657. };
  12658. Engine.prototype.setIntArray4 = function (uniform, array) {
  12659. if (!uniform || array.length % 4 !== 0)
  12660. return;
  12661. this._gl.uniform4iv(uniform, array);
  12662. };
  12663. Engine.prototype.setFloatArray = function (uniform, array) {
  12664. if (!uniform)
  12665. return;
  12666. this._gl.uniform1fv(uniform, array);
  12667. };
  12668. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12669. if (!uniform || array.length % 2 !== 0)
  12670. return;
  12671. this._gl.uniform2fv(uniform, array);
  12672. };
  12673. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12674. if (!uniform || array.length % 3 !== 0)
  12675. return;
  12676. this._gl.uniform3fv(uniform, array);
  12677. };
  12678. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12679. if (!uniform || array.length % 4 !== 0)
  12680. return;
  12681. this._gl.uniform4fv(uniform, array);
  12682. };
  12683. Engine.prototype.setArray = function (uniform, array) {
  12684. if (!uniform)
  12685. return;
  12686. this._gl.uniform1fv(uniform, array);
  12687. };
  12688. Engine.prototype.setArray2 = function (uniform, array) {
  12689. if (!uniform || array.length % 2 !== 0)
  12690. return;
  12691. this._gl.uniform2fv(uniform, array);
  12692. };
  12693. Engine.prototype.setArray3 = function (uniform, array) {
  12694. if (!uniform || array.length % 3 !== 0)
  12695. return;
  12696. this._gl.uniform3fv(uniform, array);
  12697. };
  12698. Engine.prototype.setArray4 = function (uniform, array) {
  12699. if (!uniform || array.length % 4 !== 0)
  12700. return;
  12701. this._gl.uniform4fv(uniform, array);
  12702. };
  12703. Engine.prototype.setMatrices = function (uniform, matrices) {
  12704. if (!uniform)
  12705. return;
  12706. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12707. };
  12708. Engine.prototype.setMatrix = function (uniform, matrix) {
  12709. if (!uniform)
  12710. return;
  12711. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12712. };
  12713. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12714. if (!uniform)
  12715. return;
  12716. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12717. };
  12718. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12719. if (!uniform)
  12720. return;
  12721. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12722. };
  12723. Engine.prototype.setInt = function (uniform, value) {
  12724. if (!uniform)
  12725. return;
  12726. this._gl.uniform1i(uniform, value);
  12727. };
  12728. Engine.prototype.setFloat = function (uniform, value) {
  12729. if (!uniform)
  12730. return;
  12731. this._gl.uniform1f(uniform, value);
  12732. };
  12733. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12734. if (!uniform)
  12735. return;
  12736. this._gl.uniform2f(uniform, x, y);
  12737. };
  12738. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12739. if (!uniform)
  12740. return;
  12741. this._gl.uniform3f(uniform, x, y, z);
  12742. };
  12743. Engine.prototype.setBool = function (uniform, bool) {
  12744. if (!uniform)
  12745. return;
  12746. this._gl.uniform1i(uniform, bool);
  12747. };
  12748. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12749. if (!uniform)
  12750. return;
  12751. this._gl.uniform4f(uniform, x, y, z, w);
  12752. };
  12753. Engine.prototype.setColor3 = function (uniform, color3) {
  12754. if (!uniform)
  12755. return;
  12756. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12757. };
  12758. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12759. if (!uniform)
  12760. return;
  12761. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12762. };
  12763. /**
  12764. * Sets a Color4 on a uniform variable
  12765. * @param uniform defines the uniform location
  12766. * @param color4 defines the value to be set
  12767. */
  12768. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12769. if (!uniform)
  12770. return;
  12771. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12772. };
  12773. // States
  12774. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12775. if (zOffset === void 0) { zOffset = 0; }
  12776. if (reverseSide === void 0) { reverseSide = false; }
  12777. // Culling
  12778. if (this._depthCullingState.cull !== culling || force) {
  12779. this._depthCullingState.cull = culling;
  12780. }
  12781. // Cull face
  12782. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12783. if (this._depthCullingState.cullFace !== cullFace || force) {
  12784. this._depthCullingState.cullFace = cullFace;
  12785. }
  12786. // Z offset
  12787. this.setZOffset(zOffset);
  12788. // Front face
  12789. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12790. if (this._depthCullingState.frontFace !== frontFace || force) {
  12791. this._depthCullingState.frontFace = frontFace;
  12792. }
  12793. };
  12794. Engine.prototype.setZOffset = function (value) {
  12795. this._depthCullingState.zOffset = value;
  12796. };
  12797. Engine.prototype.getZOffset = function () {
  12798. return this._depthCullingState.zOffset;
  12799. };
  12800. Engine.prototype.setDepthBuffer = function (enable) {
  12801. this._depthCullingState.depthTest = enable;
  12802. };
  12803. Engine.prototype.getDepthWrite = function () {
  12804. return this._depthCullingState.depthMask;
  12805. };
  12806. Engine.prototype.setDepthWrite = function (enable) {
  12807. this._depthCullingState.depthMask = enable;
  12808. };
  12809. Engine.prototype.setColorWrite = function (enable) {
  12810. this._gl.colorMask(enable, enable, enable, enable);
  12811. this._colorWrite = enable;
  12812. };
  12813. Engine.prototype.getColorWrite = function () {
  12814. return this._colorWrite;
  12815. };
  12816. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12817. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12818. };
  12819. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12820. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12821. if (this._alphaMode === mode) {
  12822. return;
  12823. }
  12824. switch (mode) {
  12825. case Engine.ALPHA_DISABLE:
  12826. this._alphaState.alphaBlend = false;
  12827. break;
  12828. case Engine.ALPHA_PREMULTIPLIED:
  12829. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12830. this._alphaState.alphaBlend = true;
  12831. break;
  12832. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12833. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12834. this._alphaState.alphaBlend = true;
  12835. break;
  12836. case Engine.ALPHA_COMBINE:
  12837. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12838. this._alphaState.alphaBlend = true;
  12839. break;
  12840. case Engine.ALPHA_ONEONE:
  12841. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12842. this._alphaState.alphaBlend = true;
  12843. break;
  12844. case Engine.ALPHA_ADD:
  12845. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12846. this._alphaState.alphaBlend = true;
  12847. break;
  12848. case Engine.ALPHA_SUBTRACT:
  12849. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12850. this._alphaState.alphaBlend = true;
  12851. break;
  12852. case Engine.ALPHA_MULTIPLY:
  12853. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12854. this._alphaState.alphaBlend = true;
  12855. break;
  12856. case Engine.ALPHA_MAXIMIZED:
  12857. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12858. this._alphaState.alphaBlend = true;
  12859. break;
  12860. case Engine.ALPHA_INTERPOLATE:
  12861. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12862. this._alphaState.alphaBlend = true;
  12863. break;
  12864. case Engine.ALPHA_SCREENMODE:
  12865. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12866. this._alphaState.alphaBlend = true;
  12867. break;
  12868. }
  12869. if (!noDepthWriteChange) {
  12870. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12871. }
  12872. this._alphaMode = mode;
  12873. };
  12874. Engine.prototype.getAlphaMode = function () {
  12875. return this._alphaMode;
  12876. };
  12877. // Textures
  12878. Engine.prototype.wipeCaches = function (bruteForce) {
  12879. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12880. return;
  12881. }
  12882. this._currentEffect = null;
  12883. // 6/8/2017: deltakosh: Should not be required anymore.
  12884. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12885. if (bruteForce) {
  12886. this.resetTextureCache();
  12887. this._currentProgram = null;
  12888. this._stencilState.reset();
  12889. this._depthCullingState.reset();
  12890. this.setDepthFunctionToLessOrEqual();
  12891. this._alphaState.reset();
  12892. }
  12893. this._resetVertexBufferBinding();
  12894. this._cachedIndexBuffer = null;
  12895. this._cachedEffectForVertexBuffers = null;
  12896. this._unbindVertexArrayObject();
  12897. this.bindIndexBuffer(null);
  12898. };
  12899. /**
  12900. * Set the compressed texture format to use, based on the formats you have, and the formats
  12901. * supported by the hardware / browser.
  12902. *
  12903. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12904. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12905. * to API arguments needed to compressed textures. This puts the burden on the container
  12906. * generator to house the arcane code for determining these for current & future formats.
  12907. *
  12908. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12909. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12910. *
  12911. * Note: The result of this call is not taken into account when a texture is base64.
  12912. *
  12913. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12914. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12915. *
  12916. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12917. * @returns The extension selected.
  12918. */
  12919. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12920. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12921. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12922. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12923. return this._textureFormatInUse = this._texturesSupported[i];
  12924. }
  12925. }
  12926. }
  12927. // actively set format to nothing, to allow this to be called more than once
  12928. // and possibly fail the 2nd time
  12929. this._textureFormatInUse = null;
  12930. return null;
  12931. };
  12932. Engine.prototype._createTexture = function () {
  12933. var texture = this._gl.createTexture();
  12934. if (!texture) {
  12935. throw new Error("Unable to create texture");
  12936. }
  12937. return texture;
  12938. };
  12939. /**
  12940. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12941. * @param {string} urlArg- This contains one of the following:
  12942. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12943. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12944. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12945. *
  12946. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12947. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12948. * @param {Scene} scene- Needed for loading to the correct scene.
  12949. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12950. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12951. * @param {callback} onError- Optional callback to be called upon failure.
  12952. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12953. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12954. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12955. *
  12956. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12957. */
  12958. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12959. var _this = this;
  12960. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12961. if (onLoad === void 0) { onLoad = null; }
  12962. if (onError === void 0) { onError = null; }
  12963. if (buffer === void 0) { buffer = null; }
  12964. if (fallBack === void 0) { fallBack = null; }
  12965. if (format === void 0) { format = null; }
  12966. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12967. var fromData = url.substr(0, 5) === "data:";
  12968. var fromBlob = url.substr(0, 5) === "blob:";
  12969. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12970. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12971. // establish the file extension, if possible
  12972. var lastDot = url.lastIndexOf('.');
  12973. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12974. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12975. var isTGA = (extension.indexOf(".tga") === 0);
  12976. // determine if a ktx file should be substituted
  12977. var isKTX = false;
  12978. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12979. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12980. isKTX = true;
  12981. }
  12982. if (scene) {
  12983. scene._addPendingData(texture);
  12984. }
  12985. texture.url = url;
  12986. texture.generateMipMaps = !noMipmap;
  12987. texture.samplingMode = samplingMode;
  12988. texture.invertY = invertY;
  12989. if (!this._doNotHandleContextLost) {
  12990. // Keep a link to the buffer only if we plan to handle context lost
  12991. texture._buffer = buffer;
  12992. }
  12993. var onLoadObserver = null;
  12994. if (onLoad && !fallBack) {
  12995. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12996. }
  12997. if (!fallBack)
  12998. this._internalTexturesCache.push(texture);
  12999. var onerror = function (message, exception) {
  13000. if (scene) {
  13001. scene._removePendingData(texture);
  13002. }
  13003. if (onLoadObserver) {
  13004. texture.onLoadedObservable.remove(onLoadObserver);
  13005. }
  13006. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13007. if (isKTX) {
  13008. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13009. }
  13010. else if (BABYLON.Tools.UseFallbackTexture) {
  13011. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13012. }
  13013. if (onError) {
  13014. onError(message || "Unknown error", exception);
  13015. }
  13016. };
  13017. var callback = null;
  13018. // processing for non-image formats
  13019. if (isKTX || isTGA || isDDS) {
  13020. if (isKTX) {
  13021. callback = function (data) {
  13022. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13023. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13024. ktx.uploadLevels(_this._gl, !noMipmap);
  13025. return false;
  13026. }, samplingMode);
  13027. };
  13028. }
  13029. else if (isTGA) {
  13030. callback = function (arrayBuffer) {
  13031. var data = new Uint8Array(arrayBuffer);
  13032. var header = BABYLON.TGATools.GetTGAHeader(data);
  13033. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13034. BABYLON.TGATools.UploadContent(_this._gl, data);
  13035. return false;
  13036. }, samplingMode);
  13037. };
  13038. }
  13039. else if (isDDS) {
  13040. callback = function (data) {
  13041. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13042. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13043. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13044. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13045. return false;
  13046. }, samplingMode);
  13047. };
  13048. }
  13049. if (!buffer) {
  13050. this._loadFile(url, function (data) {
  13051. if (callback) {
  13052. callback(data);
  13053. }
  13054. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13055. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13056. });
  13057. }
  13058. else {
  13059. if (callback) {
  13060. callback(buffer);
  13061. }
  13062. }
  13063. // image format processing
  13064. }
  13065. else {
  13066. var onload = function (img) {
  13067. if (fromBlob && !_this._doNotHandleContextLost) {
  13068. // We need to store the image if we need to rebuild the texture
  13069. // in case of a webgl context lost
  13070. texture._buffer = img;
  13071. }
  13072. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13073. var gl = _this._gl;
  13074. var isPot = (img.width === potWidth && img.height === potHeight);
  13075. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13076. if (isPot) {
  13077. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13078. return false;
  13079. }
  13080. // Using shaders to rescale because canvas.drawImage is lossy
  13081. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13082. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13083. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13084. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13085. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13086. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13087. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13088. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13089. _this._releaseTexture(source);
  13090. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13091. continuationCallback();
  13092. });
  13093. return true;
  13094. }, samplingMode);
  13095. };
  13096. if (!fromData || isBase64)
  13097. if (buffer instanceof HTMLImageElement) {
  13098. onload(buffer);
  13099. }
  13100. else {
  13101. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13102. }
  13103. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13104. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13105. else
  13106. onload(buffer);
  13107. }
  13108. return texture;
  13109. };
  13110. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13111. var _this = this;
  13112. var rtt = this.createRenderTargetTexture({
  13113. width: destination.width,
  13114. height: destination.height,
  13115. }, {
  13116. generateMipMaps: false,
  13117. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13118. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13119. generateDepthBuffer: false,
  13120. generateStencilBuffer: false
  13121. });
  13122. if (!this._rescalePostProcess) {
  13123. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13124. }
  13125. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13126. _this._rescalePostProcess.onApply = function (effect) {
  13127. effect._bindTexture("textureSampler", source);
  13128. };
  13129. var hostingScene = scene;
  13130. if (!hostingScene) {
  13131. hostingScene = _this.scenes[_this.scenes.length - 1];
  13132. }
  13133. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13134. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13135. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13136. _this.unBindFramebuffer(rtt);
  13137. _this._releaseTexture(rtt);
  13138. if (onComplete) {
  13139. onComplete();
  13140. }
  13141. });
  13142. };
  13143. Engine.prototype._getInternalFormat = function (format) {
  13144. var internalFormat = this._gl.RGBA;
  13145. switch (format) {
  13146. case Engine.TEXTUREFORMAT_ALPHA:
  13147. internalFormat = this._gl.ALPHA;
  13148. break;
  13149. case Engine.TEXTUREFORMAT_LUMINANCE:
  13150. internalFormat = this._gl.LUMINANCE;
  13151. break;
  13152. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13153. internalFormat = this._gl.LUMINANCE_ALPHA;
  13154. break;
  13155. case Engine.TEXTUREFORMAT_RGB:
  13156. case Engine.TEXTUREFORMAT_RGB32F:
  13157. internalFormat = this._gl.RGB;
  13158. break;
  13159. case Engine.TEXTUREFORMAT_RGBA:
  13160. case Engine.TEXTUREFORMAT_RGBA32F:
  13161. internalFormat = this._gl.RGBA;
  13162. break;
  13163. case Engine.TEXTUREFORMAT_R32F:
  13164. internalFormat = this._gl.RED;
  13165. break;
  13166. case Engine.TEXTUREFORMAT_RG32F:
  13167. internalFormat = this._gl.RG;
  13168. break;
  13169. }
  13170. return internalFormat;
  13171. };
  13172. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13173. if (compression === void 0) { compression = null; }
  13174. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13175. if (!texture) {
  13176. return;
  13177. }
  13178. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13179. var internalFormat = this._getInternalFormat(format);
  13180. var textureType = this._getWebGLTextureType(type);
  13181. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13182. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13183. if (!this._doNotHandleContextLost) {
  13184. texture._bufferView = data;
  13185. texture.format = format;
  13186. texture.type = type;
  13187. texture.invertY = invertY;
  13188. texture._compression = compression;
  13189. }
  13190. if (texture.width % 4 !== 0) {
  13191. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13192. }
  13193. if (compression && data) {
  13194. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13195. }
  13196. else {
  13197. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13198. }
  13199. if (texture.generateMipMaps) {
  13200. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13201. }
  13202. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13203. // this.resetTextureCache();
  13204. texture.isReady = true;
  13205. };
  13206. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13207. if (compression === void 0) { compression = null; }
  13208. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13209. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13210. texture.baseWidth = width;
  13211. texture.baseHeight = height;
  13212. texture.width = width;
  13213. texture.height = height;
  13214. texture.format = format;
  13215. texture.generateMipMaps = generateMipMaps;
  13216. texture.samplingMode = samplingMode;
  13217. texture.invertY = invertY;
  13218. texture._compression = compression;
  13219. texture.type = type;
  13220. if (!this._doNotHandleContextLost) {
  13221. texture._bufferView = data;
  13222. }
  13223. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13224. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13225. // Filters
  13226. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13227. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13228. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13229. if (generateMipMaps) {
  13230. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13231. }
  13232. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13233. this._internalTexturesCache.push(texture);
  13234. return texture;
  13235. };
  13236. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13237. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13238. texture.baseWidth = width;
  13239. texture.baseHeight = height;
  13240. if (generateMipMaps) {
  13241. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13242. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13243. }
  13244. // this.resetTextureCache();
  13245. texture.width = width;
  13246. texture.height = height;
  13247. texture.isReady = false;
  13248. texture.generateMipMaps = generateMipMaps;
  13249. texture.samplingMode = samplingMode;
  13250. this.updateTextureSamplingMode(samplingMode, texture);
  13251. this._internalTexturesCache.push(texture);
  13252. return texture;
  13253. };
  13254. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13255. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13256. if (texture.isCube) {
  13257. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13258. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13259. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13260. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13261. }
  13262. else if (texture.is3D) {
  13263. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13264. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13265. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13266. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13267. }
  13268. else {
  13269. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13270. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13271. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13272. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13273. }
  13274. texture.samplingMode = samplingMode;
  13275. };
  13276. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13277. if (premulAlpha === void 0) { premulAlpha = false; }
  13278. if (!texture) {
  13279. return;
  13280. }
  13281. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13282. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13283. if (premulAlpha) {
  13284. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13285. }
  13286. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13287. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13288. if (texture.generateMipMaps) {
  13289. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13290. }
  13291. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13292. if (premulAlpha) {
  13293. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13294. }
  13295. texture.isReady = true;
  13296. };
  13297. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13298. if (!texture || texture._isDisabled) {
  13299. return;
  13300. }
  13301. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13302. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13303. try {
  13304. // Testing video texture support
  13305. if (this._videoTextureSupported === undefined) {
  13306. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13307. if (this._gl.getError() !== 0) {
  13308. this._videoTextureSupported = false;
  13309. }
  13310. else {
  13311. this._videoTextureSupported = true;
  13312. }
  13313. }
  13314. // Copy video through the current working canvas if video texture is not supported
  13315. if (!this._videoTextureSupported) {
  13316. if (!texture._workingCanvas) {
  13317. texture._workingCanvas = document.createElement("canvas");
  13318. var context = texture._workingCanvas.getContext("2d");
  13319. if (!context) {
  13320. throw new Error("Unable to get 2d context");
  13321. }
  13322. texture._workingContext = context;
  13323. texture._workingCanvas.width = texture.width;
  13324. texture._workingCanvas.height = texture.height;
  13325. }
  13326. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13327. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13328. }
  13329. else {
  13330. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13331. }
  13332. if (texture.generateMipMaps) {
  13333. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13334. }
  13335. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13336. // this.resetTextureCache();
  13337. texture.isReady = true;
  13338. }
  13339. catch (ex) {
  13340. // Something unexpected
  13341. // Let's disable the texture
  13342. texture._isDisabled = true;
  13343. }
  13344. };
  13345. /**
  13346. * Updates a depth texture Comparison Mode and Function.
  13347. * If the comparison Function is equal to 0, the mode will be set to none.
  13348. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13349. * @param texture The texture to set the comparison function for
  13350. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13351. */
  13352. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13353. if (this.webGLVersion === 1) {
  13354. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13355. return;
  13356. }
  13357. var gl = this._gl;
  13358. if (texture.isCube) {
  13359. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13360. if (comparisonFunction === 0) {
  13361. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13362. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13363. }
  13364. else {
  13365. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13367. }
  13368. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13369. }
  13370. else {
  13371. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13372. if (comparisonFunction === 0) {
  13373. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13374. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13375. }
  13376. else {
  13377. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13378. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13379. }
  13380. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13381. }
  13382. texture._comparisonFunction = comparisonFunction;
  13383. };
  13384. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13385. var width = size.width || size;
  13386. var height = size.height || size;
  13387. internalTexture.baseWidth = width;
  13388. internalTexture.baseHeight = height;
  13389. internalTexture.width = width;
  13390. internalTexture.height = height;
  13391. internalTexture.isReady = true;
  13392. internalTexture.samples = 1;
  13393. internalTexture.generateMipMaps = false;
  13394. internalTexture._generateDepthBuffer = true;
  13395. internalTexture._generateStencilBuffer = generateStencil;
  13396. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13397. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13398. internalTexture._comparisonFunction = comparisonFunction;
  13399. var gl = this._gl;
  13400. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13401. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13402. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13403. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13404. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13405. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13406. if (comparisonFunction === 0) {
  13407. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13408. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13409. }
  13410. else {
  13411. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13412. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13413. }
  13414. };
  13415. /**
  13416. * Creates a depth stencil texture.
  13417. * This is only available in WebGL 2 or with the depth texture extension available.
  13418. * @param size The size of face edge in the texture.
  13419. * @param options The options defining the texture.
  13420. * @returns The texture
  13421. */
  13422. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13423. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13424. if (!this._caps.depthTextureExtension) {
  13425. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13426. return internalTexture;
  13427. }
  13428. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13429. var gl = this._gl;
  13430. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13431. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13432. if (this.webGLVersion > 1) {
  13433. if (internalOptions.generateStencil) {
  13434. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13435. }
  13436. else {
  13437. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13438. }
  13439. }
  13440. else {
  13441. if (internalOptions.generateStencil) {
  13442. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13443. }
  13444. else {
  13445. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13446. }
  13447. }
  13448. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13449. return internalTexture;
  13450. };
  13451. /**
  13452. * Creates a depth stencil cube texture.
  13453. * This is only available in WebGL 2.
  13454. * @param size The size of face edge in the cube texture.
  13455. * @param options The options defining the cube texture.
  13456. * @returns The cube texture
  13457. */
  13458. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13459. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13460. internalTexture.isCube = true;
  13461. if (this.webGLVersion === 1) {
  13462. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13463. return internalTexture;
  13464. }
  13465. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13466. var gl = this._gl;
  13467. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13468. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13469. // Create the depth/stencil buffer
  13470. for (var face = 0; face < 6; face++) {
  13471. if (internalOptions.generateStencil) {
  13472. 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);
  13473. }
  13474. else {
  13475. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13476. }
  13477. }
  13478. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13479. return internalTexture;
  13480. };
  13481. /**
  13482. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13483. * @param renderTarget The render target to set the frame buffer for
  13484. */
  13485. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13486. // Create the framebuffer
  13487. var internalTexture = renderTarget.getInternalTexture();
  13488. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13489. return;
  13490. }
  13491. var gl = this._gl;
  13492. var depthStencilTexture = renderTarget.depthStencilTexture;
  13493. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13494. if (depthStencilTexture.isCube) {
  13495. if (depthStencilTexture._generateStencilBuffer) {
  13496. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13497. }
  13498. else {
  13499. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13500. }
  13501. }
  13502. else {
  13503. if (depthStencilTexture._generateStencilBuffer) {
  13504. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13505. }
  13506. else {
  13507. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13508. }
  13509. }
  13510. this.bindUnboundFramebuffer(null);
  13511. };
  13512. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13513. var fullOptions = new RenderTargetCreationOptions();
  13514. if (options !== undefined && typeof options === "object") {
  13515. fullOptions.generateMipMaps = options.generateMipMaps;
  13516. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13517. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13518. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13519. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13520. }
  13521. else {
  13522. fullOptions.generateMipMaps = options;
  13523. fullOptions.generateDepthBuffer = true;
  13524. fullOptions.generateStencilBuffer = false;
  13525. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13526. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13527. }
  13528. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13529. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13530. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13531. }
  13532. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13533. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13534. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13535. }
  13536. var gl = this._gl;
  13537. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13538. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13539. var width = size.width || size;
  13540. var height = size.height || size;
  13541. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13542. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13543. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13544. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13545. }
  13546. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13547. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13548. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13549. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13550. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13551. // Create the framebuffer
  13552. var framebuffer = gl.createFramebuffer();
  13553. this.bindUnboundFramebuffer(framebuffer);
  13554. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13555. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13556. if (fullOptions.generateMipMaps) {
  13557. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13558. }
  13559. // Unbind
  13560. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13561. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13562. this.bindUnboundFramebuffer(null);
  13563. texture._framebuffer = framebuffer;
  13564. texture.baseWidth = width;
  13565. texture.baseHeight = height;
  13566. texture.width = width;
  13567. texture.height = height;
  13568. texture.isReady = true;
  13569. texture.samples = 1;
  13570. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13571. texture.samplingMode = fullOptions.samplingMode;
  13572. texture.type = fullOptions.type;
  13573. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13574. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13575. // this.resetTextureCache();
  13576. this._internalTexturesCache.push(texture);
  13577. return texture;
  13578. };
  13579. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13580. var generateMipMaps = false;
  13581. var generateDepthBuffer = true;
  13582. var generateStencilBuffer = false;
  13583. var generateDepthTexture = false;
  13584. var textureCount = 1;
  13585. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13586. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13587. var types = [], samplingModes = [];
  13588. if (options !== undefined) {
  13589. generateMipMaps = options.generateMipMaps;
  13590. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13591. generateStencilBuffer = options.generateStencilBuffer;
  13592. generateDepthTexture = options.generateDepthTexture;
  13593. textureCount = options.textureCount || 1;
  13594. if (options.types) {
  13595. types = options.types;
  13596. }
  13597. if (options.samplingModes) {
  13598. samplingModes = options.samplingModes;
  13599. }
  13600. }
  13601. var gl = this._gl;
  13602. // Create the framebuffer
  13603. var framebuffer = gl.createFramebuffer();
  13604. this.bindUnboundFramebuffer(framebuffer);
  13605. var width = size.width || size;
  13606. var height = size.height || size;
  13607. var textures = [];
  13608. var attachments = [];
  13609. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13610. for (var i = 0; i < textureCount; i++) {
  13611. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13612. var type = types[i] || defaultType;
  13613. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13614. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13615. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13616. }
  13617. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13618. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13619. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13620. }
  13621. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13622. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13623. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13624. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13625. }
  13626. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13627. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13628. textures.push(texture);
  13629. attachments.push(attachment);
  13630. gl.activeTexture(gl["TEXTURE" + i]);
  13631. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13632. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13633. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13634. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13635. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13636. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13637. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13638. if (generateMipMaps) {
  13639. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13640. }
  13641. // Unbind
  13642. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13643. texture._framebuffer = framebuffer;
  13644. texture._depthStencilBuffer = depthStencilBuffer;
  13645. texture.baseWidth = width;
  13646. texture.baseHeight = height;
  13647. texture.width = width;
  13648. texture.height = height;
  13649. texture.isReady = true;
  13650. texture.samples = 1;
  13651. texture.generateMipMaps = generateMipMaps;
  13652. texture.samplingMode = samplingMode;
  13653. texture.type = type;
  13654. texture._generateDepthBuffer = generateDepthBuffer;
  13655. texture._generateStencilBuffer = generateStencilBuffer;
  13656. texture._attachments = attachments;
  13657. this._internalTexturesCache.push(texture);
  13658. }
  13659. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13660. // Depth texture
  13661. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13662. gl.activeTexture(gl.TEXTURE0);
  13663. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13664. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13665. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13666. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13667. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13668. 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);
  13669. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13670. depthTexture._framebuffer = framebuffer;
  13671. depthTexture.baseWidth = width;
  13672. depthTexture.baseHeight = height;
  13673. depthTexture.width = width;
  13674. depthTexture.height = height;
  13675. depthTexture.isReady = true;
  13676. depthTexture.samples = 1;
  13677. depthTexture.generateMipMaps = generateMipMaps;
  13678. depthTexture.samplingMode = gl.NEAREST;
  13679. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13680. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13681. textures.push(depthTexture);
  13682. this._internalTexturesCache.push(depthTexture);
  13683. }
  13684. gl.drawBuffers(attachments);
  13685. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13686. this.bindUnboundFramebuffer(null);
  13687. this.resetTextureCache();
  13688. return textures;
  13689. };
  13690. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13691. if (samples === void 0) { samples = 1; }
  13692. var depthStencilBuffer = null;
  13693. var gl = this._gl;
  13694. // Create the depth/stencil buffer
  13695. if (generateStencilBuffer) {
  13696. depthStencilBuffer = gl.createRenderbuffer();
  13697. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13698. if (samples > 1) {
  13699. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13700. }
  13701. else {
  13702. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13703. }
  13704. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13705. }
  13706. else if (generateDepthBuffer) {
  13707. depthStencilBuffer = gl.createRenderbuffer();
  13708. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13709. if (samples > 1) {
  13710. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13711. }
  13712. else {
  13713. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13714. }
  13715. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13716. }
  13717. return depthStencilBuffer;
  13718. };
  13719. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13720. if (this.webGLVersion < 2 || !texture) {
  13721. return 1;
  13722. }
  13723. if (texture.samples === samples) {
  13724. return samples;
  13725. }
  13726. var gl = this._gl;
  13727. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13728. // Dispose previous render buffers
  13729. if (texture._depthStencilBuffer) {
  13730. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13731. texture._depthStencilBuffer = null;
  13732. }
  13733. if (texture._MSAAFramebuffer) {
  13734. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13735. texture._MSAAFramebuffer = null;
  13736. }
  13737. if (texture._MSAARenderBuffer) {
  13738. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13739. texture._MSAARenderBuffer = null;
  13740. }
  13741. if (samples > 1) {
  13742. var framebuffer = gl.createFramebuffer();
  13743. if (!framebuffer) {
  13744. throw new Error("Unable to create multi sampled framebuffer");
  13745. }
  13746. texture._MSAAFramebuffer = framebuffer;
  13747. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13748. var colorRenderbuffer = gl.createRenderbuffer();
  13749. if (!colorRenderbuffer) {
  13750. throw new Error("Unable to create multi sampled framebuffer");
  13751. }
  13752. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13753. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13754. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13755. texture._MSAARenderBuffer = colorRenderbuffer;
  13756. }
  13757. else {
  13758. this.bindUnboundFramebuffer(texture._framebuffer);
  13759. }
  13760. texture.samples = samples;
  13761. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13762. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13763. this.bindUnboundFramebuffer(null);
  13764. return samples;
  13765. };
  13766. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13767. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13768. return 1;
  13769. }
  13770. if (textures[0].samples === samples) {
  13771. return samples;
  13772. }
  13773. var gl = this._gl;
  13774. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13775. // Dispose previous render buffers
  13776. if (textures[0]._depthStencilBuffer) {
  13777. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13778. textures[0]._depthStencilBuffer = null;
  13779. }
  13780. if (textures[0]._MSAAFramebuffer) {
  13781. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13782. textures[0]._MSAAFramebuffer = null;
  13783. }
  13784. for (var i = 0; i < textures.length; i++) {
  13785. if (textures[i]._MSAARenderBuffer) {
  13786. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13787. textures[i]._MSAARenderBuffer = null;
  13788. }
  13789. }
  13790. if (samples > 1) {
  13791. var framebuffer = gl.createFramebuffer();
  13792. if (!framebuffer) {
  13793. throw new Error("Unable to create multi sampled framebuffer");
  13794. }
  13795. this.bindUnboundFramebuffer(framebuffer);
  13796. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13797. var attachments = [];
  13798. for (var i = 0; i < textures.length; i++) {
  13799. var texture = textures[i];
  13800. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13801. var colorRenderbuffer = gl.createRenderbuffer();
  13802. if (!colorRenderbuffer) {
  13803. throw new Error("Unable to create multi sampled framebuffer");
  13804. }
  13805. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13806. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13807. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13808. texture._MSAAFramebuffer = framebuffer;
  13809. texture._MSAARenderBuffer = colorRenderbuffer;
  13810. texture.samples = samples;
  13811. texture._depthStencilBuffer = depthStencilBuffer;
  13812. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13813. attachments.push(attachment);
  13814. }
  13815. gl.drawBuffers(attachments);
  13816. }
  13817. else {
  13818. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13819. }
  13820. this.bindUnboundFramebuffer(null);
  13821. return samples;
  13822. };
  13823. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13824. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13825. };
  13826. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13827. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13828. };
  13829. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13830. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13831. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13832. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13833. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13834. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13835. }
  13836. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13837. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13838. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13839. }
  13840. var gl = this._gl;
  13841. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13842. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13843. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13844. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13845. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13846. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13847. }
  13848. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13851. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13852. for (var face = 0; face < 6; face++) {
  13853. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13854. }
  13855. // Create the framebuffer
  13856. var framebuffer = gl.createFramebuffer();
  13857. this.bindUnboundFramebuffer(framebuffer);
  13858. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13859. // MipMaps
  13860. if (fullOptions.generateMipMaps) {
  13861. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13862. }
  13863. // Unbind
  13864. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13865. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13866. this.bindUnboundFramebuffer(null);
  13867. texture._framebuffer = framebuffer;
  13868. texture.width = size;
  13869. texture.height = size;
  13870. texture.isReady = true;
  13871. texture.isCube = true;
  13872. texture.samples = 1;
  13873. texture.generateMipMaps = fullOptions.generateMipMaps;
  13874. texture.samplingMode = fullOptions.samplingMode;
  13875. texture.type = fullOptions.type;
  13876. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13877. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13878. this._internalTexturesCache.push(texture);
  13879. return texture;
  13880. };
  13881. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13882. var _this = this;
  13883. if (onLoad === void 0) { onLoad = null; }
  13884. if (onError === void 0) { onError = null; }
  13885. if (forcedExtension === void 0) { forcedExtension = null; }
  13886. var callback = function (loadData) {
  13887. if (!loadData) {
  13888. if (onLoad) {
  13889. onLoad(null);
  13890. }
  13891. return;
  13892. }
  13893. var texture = loadData.texture;
  13894. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13895. texture._lodGenerationScale = scale;
  13896. texture._lodGenerationOffset = offset;
  13897. if (_this._caps.textureLOD) {
  13898. // Do not add extra process if texture lod is supported.
  13899. if (onLoad) {
  13900. onLoad(texture);
  13901. }
  13902. return;
  13903. }
  13904. var mipSlices = 3;
  13905. var gl = _this._gl;
  13906. var width = loadData.width;
  13907. if (!width) {
  13908. return;
  13909. }
  13910. var textures = [];
  13911. for (var i = 0; i < mipSlices; i++) {
  13912. //compute LOD from even spacing in smoothness (matching shader calculation)
  13913. var smoothness = i / (mipSlices - 1);
  13914. var roughness = 1 - smoothness;
  13915. var minLODIndex = offset; // roughness = 0
  13916. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13917. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13918. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13919. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13920. glTextureFromLod.isCube = true;
  13921. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13922. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13923. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13924. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13925. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13926. if (loadData.isDDS) {
  13927. var info = loadData.info;
  13928. var data = loadData.data;
  13929. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13930. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13931. }
  13932. else {
  13933. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13934. }
  13935. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13936. // Wrap in a base texture for easy binding.
  13937. var lodTexture = new BABYLON.BaseTexture(scene);
  13938. lodTexture.isCube = true;
  13939. lodTexture._texture = glTextureFromLod;
  13940. glTextureFromLod.isReady = true;
  13941. textures.push(lodTexture);
  13942. }
  13943. texture._lodTextureHigh = textures[2];
  13944. texture._lodTextureMid = textures[1];
  13945. texture._lodTextureLow = textures[0];
  13946. if (onLoad) {
  13947. onLoad(texture);
  13948. }
  13949. };
  13950. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13951. };
  13952. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13953. var _this = this;
  13954. if (onLoad === void 0) { onLoad = null; }
  13955. if (onError === void 0) { onError = null; }
  13956. if (forcedExtension === void 0) { forcedExtension = null; }
  13957. var gl = this._gl;
  13958. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13959. texture.isCube = true;
  13960. texture.url = rootUrl;
  13961. texture.generateMipMaps = !noMipmap;
  13962. if (!this._doNotHandleContextLost) {
  13963. texture._extension = forcedExtension;
  13964. texture._files = files;
  13965. }
  13966. var isKTX = false;
  13967. var isDDS = false;
  13968. var lastDot = rootUrl.lastIndexOf('.');
  13969. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13970. if (this._textureFormatInUse) {
  13971. extension = this._textureFormatInUse;
  13972. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13973. isKTX = true;
  13974. }
  13975. else {
  13976. isDDS = (extension === ".dds");
  13977. }
  13978. var onerror = function (request, exception) {
  13979. if (onError && request) {
  13980. onError(request.status + " " + request.statusText, exception);
  13981. }
  13982. };
  13983. if (isKTX) {
  13984. this._loadFile(rootUrl, function (data) {
  13985. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13986. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13987. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13988. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13989. ktx.uploadLevels(_this._gl, !noMipmap);
  13990. _this.setCubeMapTextureParams(gl, loadMipmap);
  13991. texture.width = ktx.pixelWidth;
  13992. texture.height = ktx.pixelHeight;
  13993. texture.isReady = true;
  13994. }, undefined, undefined, true, onerror);
  13995. }
  13996. else if (isDDS) {
  13997. if (files && files.length === 6) {
  13998. this._cascadeLoadFiles(scene, function (imgs) {
  13999. var info;
  14000. var loadMipmap = false;
  14001. var width = 0;
  14002. for (var index = 0; index < imgs.length; index++) {
  14003. var data = imgs[index];
  14004. info = BABYLON.DDSTools.GetDDSInfo(data);
  14005. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14006. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14007. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14008. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14009. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14010. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14011. }
  14012. texture.width = info.width;
  14013. texture.height = info.height;
  14014. texture.type = info.textureType;
  14015. width = info.width;
  14016. }
  14017. _this.setCubeMapTextureParams(gl, loadMipmap);
  14018. texture.isReady = true;
  14019. if (onLoad) {
  14020. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14021. }
  14022. }, files, onError);
  14023. }
  14024. else {
  14025. this._loadFile(rootUrl, function (data) {
  14026. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14027. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14028. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14029. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14030. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14031. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14032. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14033. }
  14034. _this.setCubeMapTextureParams(gl, loadMipmap);
  14035. texture.width = info.width;
  14036. texture.height = info.height;
  14037. texture.isReady = true;
  14038. texture.type = info.textureType;
  14039. if (onLoad) {
  14040. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14041. }
  14042. }, undefined, undefined, true, onerror);
  14043. }
  14044. }
  14045. else {
  14046. if (!files) {
  14047. throw new Error("Cannot load cubemap because files were not defined");
  14048. }
  14049. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14050. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14051. var height = width;
  14052. _this._prepareWorkingCanvas();
  14053. if (!_this._workingCanvas || !_this._workingContext) {
  14054. return;
  14055. }
  14056. _this._workingCanvas.width = width;
  14057. _this._workingCanvas.height = height;
  14058. var faces = [
  14059. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14060. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14061. ];
  14062. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14063. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14064. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14065. for (var index = 0; index < faces.length; index++) {
  14066. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14067. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14068. }
  14069. if (!noMipmap) {
  14070. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14071. }
  14072. _this.setCubeMapTextureParams(gl, !noMipmap);
  14073. texture.width = width;
  14074. texture.height = height;
  14075. texture.isReady = true;
  14076. if (format) {
  14077. texture.format = format;
  14078. }
  14079. texture.onLoadedObservable.notifyObservers(texture);
  14080. texture.onLoadedObservable.clear();
  14081. if (onLoad) {
  14082. onLoad();
  14083. }
  14084. }, files, onError);
  14085. }
  14086. this._internalTexturesCache.push(texture);
  14087. return texture;
  14088. };
  14089. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14090. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14091. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14092. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14093. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14094. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14095. // this.resetTextureCache();
  14096. };
  14097. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14098. if (compression === void 0) { compression = null; }
  14099. if (level === void 0) { level = 0; }
  14100. texture._bufferViewArray = data;
  14101. texture.format = format;
  14102. texture.type = type;
  14103. texture.invertY = invertY;
  14104. texture._compression = compression;
  14105. var gl = this._gl;
  14106. var textureType = this._getWebGLTextureType(type);
  14107. var internalFormat = this._getInternalFormat(format);
  14108. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14109. var needConversion = false;
  14110. if (internalFormat === gl.RGB) {
  14111. internalFormat = gl.RGBA;
  14112. needConversion = true;
  14113. }
  14114. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14115. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14116. if (texture.width % 4 !== 0) {
  14117. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14118. }
  14119. // Data are known to be in +X +Y +Z -X -Y -Z
  14120. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14121. var faceData = data[faceIndex];
  14122. if (compression) {
  14123. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14124. }
  14125. else {
  14126. if (needConversion) {
  14127. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14128. }
  14129. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14130. }
  14131. }
  14132. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14133. if (isPot && texture.generateMipMaps && level === 0) {
  14134. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14135. }
  14136. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14137. // this.resetTextureCache();
  14138. texture.isReady = true;
  14139. };
  14140. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14141. if (compression === void 0) { compression = null; }
  14142. var gl = this._gl;
  14143. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14144. texture.isCube = true;
  14145. texture.generateMipMaps = generateMipMaps;
  14146. texture.format = format;
  14147. texture.type = type;
  14148. if (!this._doNotHandleContextLost) {
  14149. texture._bufferViewArray = data;
  14150. }
  14151. var textureType = this._getWebGLTextureType(type);
  14152. var internalFormat = this._getInternalFormat(format);
  14153. if (internalFormat === gl.RGB) {
  14154. internalFormat = gl.RGBA;
  14155. }
  14156. var width = size;
  14157. var height = width;
  14158. texture.width = width;
  14159. texture.height = height;
  14160. // Double check on POT to generate Mips.
  14161. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14162. if (!isPot) {
  14163. generateMipMaps = false;
  14164. }
  14165. // Upload data if needed. The texture won't be ready until then.
  14166. if (data) {
  14167. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14168. }
  14169. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14170. // Filters
  14171. if (data && generateMipMaps) {
  14172. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14173. }
  14174. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14175. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14176. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14177. }
  14178. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14179. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14180. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14181. }
  14182. else {
  14183. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14184. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14185. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14186. }
  14187. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14188. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14189. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14190. return texture;
  14191. };
  14192. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14193. var _this = this;
  14194. if (onLoad === void 0) { onLoad = null; }
  14195. if (onError === void 0) { onError = null; }
  14196. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14197. if (invertY === void 0) { invertY = false; }
  14198. var gl = this._gl;
  14199. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14200. scene._addPendingData(texture);
  14201. texture.url = url;
  14202. this._internalTexturesCache.push(texture);
  14203. var onerror = function (request, exception) {
  14204. scene._removePendingData(texture);
  14205. if (onError && request) {
  14206. onError(request.status + " " + request.statusText, exception);
  14207. }
  14208. };
  14209. var internalCallback = function (data) {
  14210. var width = texture.width;
  14211. var faceDataArrays = callback(data);
  14212. if (!faceDataArrays) {
  14213. return;
  14214. }
  14215. if (mipmmapGenerator) {
  14216. var textureType = _this._getWebGLTextureType(type);
  14217. var internalFormat = _this._getInternalFormat(format);
  14218. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14219. var needConversion = false;
  14220. if (internalFormat === gl.RGB) {
  14221. internalFormat = gl.RGBA;
  14222. needConversion = true;
  14223. }
  14224. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14225. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14226. var mipData = mipmmapGenerator(faceDataArrays);
  14227. for (var level = 0; level < mipData.length; level++) {
  14228. var mipSize = width >> level;
  14229. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14230. var mipFaceData = mipData[level][faceIndex];
  14231. if (needConversion) {
  14232. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14233. }
  14234. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14235. }
  14236. }
  14237. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14238. }
  14239. else {
  14240. texture.generateMipMaps = !noMipmap;
  14241. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14242. }
  14243. texture.isReady = true;
  14244. // this.resetTextureCache();
  14245. scene._removePendingData(texture);
  14246. if (onLoad) {
  14247. onLoad();
  14248. }
  14249. };
  14250. this._loadFile(url, function (data) {
  14251. internalCallback(data);
  14252. }, undefined, scene.database, true, onerror);
  14253. return texture;
  14254. };
  14255. ;
  14256. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14257. if (compression === void 0) { compression = null; }
  14258. var internalFormat = this._getInternalFormat(format);
  14259. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14260. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14261. if (!this._doNotHandleContextLost) {
  14262. texture._bufferView = data;
  14263. texture.format = format;
  14264. texture.invertY = invertY;
  14265. texture._compression = compression;
  14266. }
  14267. if (texture.width % 4 !== 0) {
  14268. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14269. }
  14270. if (compression && data) {
  14271. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14272. }
  14273. else {
  14274. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14275. }
  14276. if (texture.generateMipMaps) {
  14277. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14278. }
  14279. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14280. // this.resetTextureCache();
  14281. texture.isReady = true;
  14282. };
  14283. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14284. if (compression === void 0) { compression = null; }
  14285. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14286. texture.baseWidth = width;
  14287. texture.baseHeight = height;
  14288. texture.baseDepth = depth;
  14289. texture.width = width;
  14290. texture.height = height;
  14291. texture.depth = depth;
  14292. texture.format = format;
  14293. texture.generateMipMaps = generateMipMaps;
  14294. texture.samplingMode = samplingMode;
  14295. texture.is3D = true;
  14296. if (!this._doNotHandleContextLost) {
  14297. texture._bufferView = data;
  14298. }
  14299. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14300. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14301. // Filters
  14302. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14303. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14304. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14305. if (generateMipMaps) {
  14306. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14307. }
  14308. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14309. this._internalTexturesCache.push(texture);
  14310. return texture;
  14311. };
  14312. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14313. var gl = this._gl;
  14314. if (!gl) {
  14315. return;
  14316. }
  14317. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14319. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14320. if (!noMipmap && !isCompressed) {
  14321. gl.generateMipmap(gl.TEXTURE_2D);
  14322. }
  14323. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14324. // this.resetTextureCache();
  14325. if (scene) {
  14326. scene._removePendingData(texture);
  14327. }
  14328. texture.onLoadedObservable.notifyObservers(texture);
  14329. texture.onLoadedObservable.clear();
  14330. };
  14331. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14332. var _this = this;
  14333. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14334. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14335. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14336. var gl = this._gl;
  14337. if (!gl) {
  14338. return;
  14339. }
  14340. if (!texture._webGLTexture) {
  14341. // this.resetTextureCache();
  14342. if (scene) {
  14343. scene._removePendingData(texture);
  14344. }
  14345. return;
  14346. }
  14347. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14348. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14349. texture.baseWidth = width;
  14350. texture.baseHeight = height;
  14351. texture.width = potWidth;
  14352. texture.height = potHeight;
  14353. texture.isReady = true;
  14354. if (processFunction(potWidth, potHeight, function () {
  14355. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14356. })) {
  14357. // Returning as texture needs extra async steps
  14358. return;
  14359. }
  14360. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14361. };
  14362. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14363. // Create new RGBA data container.
  14364. var rgbaData;
  14365. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14366. rgbaData = new Float32Array(width * height * 4);
  14367. }
  14368. else {
  14369. rgbaData = new Uint32Array(width * height * 4);
  14370. }
  14371. // Convert each pixel.
  14372. for (var x = 0; x < width; x++) {
  14373. for (var y = 0; y < height; y++) {
  14374. var index = (y * width + x) * 3;
  14375. var newIndex = (y * width + x) * 4;
  14376. // Map Old Value to new value.
  14377. rgbaData[newIndex + 0] = rgbData[index + 0];
  14378. rgbaData[newIndex + 1] = rgbData[index + 1];
  14379. rgbaData[newIndex + 2] = rgbData[index + 2];
  14380. // Add fully opaque alpha channel.
  14381. rgbaData[newIndex + 3] = 1;
  14382. }
  14383. }
  14384. return rgbaData;
  14385. };
  14386. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14387. var gl = this._gl;
  14388. if (texture._framebuffer) {
  14389. gl.deleteFramebuffer(texture._framebuffer);
  14390. texture._framebuffer = null;
  14391. }
  14392. if (texture._depthStencilBuffer) {
  14393. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14394. texture._depthStencilBuffer = null;
  14395. }
  14396. if (texture._MSAAFramebuffer) {
  14397. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14398. texture._MSAAFramebuffer = null;
  14399. }
  14400. if (texture._MSAARenderBuffer) {
  14401. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14402. texture._MSAARenderBuffer = null;
  14403. }
  14404. };
  14405. Engine.prototype._releaseTexture = function (texture) {
  14406. var gl = this._gl;
  14407. this._releaseFramebufferObjects(texture);
  14408. gl.deleteTexture(texture._webGLTexture);
  14409. // Unbind channels
  14410. this.unbindAllTextures();
  14411. var index = this._internalTexturesCache.indexOf(texture);
  14412. if (index !== -1) {
  14413. this._internalTexturesCache.splice(index, 1);
  14414. }
  14415. // Integrated fixed lod samplers.
  14416. if (texture._lodTextureHigh) {
  14417. texture._lodTextureHigh.dispose();
  14418. }
  14419. if (texture._lodTextureMid) {
  14420. texture._lodTextureMid.dispose();
  14421. }
  14422. if (texture._lodTextureLow) {
  14423. texture._lodTextureLow.dispose();
  14424. }
  14425. };
  14426. Engine.prototype.setProgram = function (program) {
  14427. if (this._currentProgram !== program) {
  14428. this._gl.useProgram(program);
  14429. this._currentProgram = program;
  14430. }
  14431. };
  14432. Engine.prototype.bindSamplers = function (effect) {
  14433. this.setProgram(effect.getProgram());
  14434. var samplers = effect.getSamplers();
  14435. for (var index = 0; index < samplers.length; index++) {
  14436. var uniform = effect.getUniform(samplers[index]);
  14437. if (uniform) {
  14438. this._boundUniforms[index] = uniform;
  14439. }
  14440. }
  14441. this._currentEffect = null;
  14442. };
  14443. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14444. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14445. return;
  14446. }
  14447. // Remove
  14448. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14449. // Bind last to it
  14450. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14451. // Bind to dummy
  14452. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14453. };
  14454. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14455. if (!internalTexture) {
  14456. return -1;
  14457. }
  14458. internalTexture._initialSlot = channel;
  14459. if (this.disableTextureBindingOptimization) {
  14460. if (channel !== internalTexture._designatedSlot) {
  14461. this._textureCollisions.addCount(1, false);
  14462. }
  14463. }
  14464. else {
  14465. if (channel !== internalTexture._designatedSlot) {
  14466. if (internalTexture._designatedSlot > -1) {
  14467. return internalTexture._designatedSlot;
  14468. }
  14469. else {
  14470. // No slot for this texture, let's pick a new one (if we find a free slot)
  14471. if (this._nextFreeTextureSlots.length) {
  14472. return this._nextFreeTextureSlots[0];
  14473. }
  14474. // We need to recycle the oldest bound texture, sorry.
  14475. this._textureCollisions.addCount(1, false);
  14476. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14477. }
  14478. }
  14479. }
  14480. return channel;
  14481. };
  14482. Engine.prototype._linkTrackers = function (previous, next) {
  14483. previous.next = next;
  14484. next.previous = previous;
  14485. };
  14486. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14487. var currentSlot = internalTexture._designatedSlot;
  14488. if (currentSlot === -1) {
  14489. return -1;
  14490. }
  14491. internalTexture._designatedSlot = -1;
  14492. if (this.disableTextureBindingOptimization) {
  14493. return -1;
  14494. }
  14495. // Remove from bound list
  14496. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14497. // Free the slot
  14498. this._boundTexturesCache[currentSlot] = null;
  14499. this._nextFreeTextureSlots.push(currentSlot);
  14500. return currentSlot;
  14501. };
  14502. Engine.prototype._activateCurrentTexture = function () {
  14503. if (this._currentTextureChannel !== this._activeChannel) {
  14504. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14505. this._currentTextureChannel = this._activeChannel;
  14506. }
  14507. };
  14508. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14509. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14510. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14511. this._activeChannel = texture._designatedSlot;
  14512. }
  14513. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14514. var isTextureForRendering = texture && texture._initialSlot > -1;
  14515. if (currentTextureBound !== texture) {
  14516. if (currentTextureBound) {
  14517. this._removeDesignatedSlot(currentTextureBound);
  14518. }
  14519. this._activateCurrentTexture();
  14520. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14521. this._boundTexturesCache[this._activeChannel] = texture;
  14522. if (texture) {
  14523. if (!this.disableTextureBindingOptimization) {
  14524. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14525. if (slotIndex > -1) {
  14526. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14527. }
  14528. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14529. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14530. }
  14531. texture._designatedSlot = this._activeChannel;
  14532. }
  14533. }
  14534. else if (forTextureDataUpdate) {
  14535. this._activateCurrentTexture();
  14536. }
  14537. if (isTextureForRendering && !forTextureDataUpdate) {
  14538. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14539. }
  14540. };
  14541. Engine.prototype._bindTexture = function (channel, texture) {
  14542. if (channel < 0) {
  14543. return;
  14544. }
  14545. if (texture) {
  14546. channel = this._getCorrectTextureChannel(channel, texture);
  14547. }
  14548. this._activeChannel = channel;
  14549. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14550. };
  14551. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14552. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14553. };
  14554. Engine.prototype.unbindAllTextures = function () {
  14555. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14556. this._activeChannel = channel;
  14557. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14558. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14559. if (this.webGLVersion > 1) {
  14560. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14561. }
  14562. }
  14563. };
  14564. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14565. if (channel < 0) {
  14566. return;
  14567. }
  14568. if (uniform) {
  14569. this._boundUniforms[channel] = uniform;
  14570. }
  14571. this._setTexture(channel, texture);
  14572. };
  14573. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14574. var uniform = this._boundUniforms[sourceSlot];
  14575. if (uniform._currentState === destination) {
  14576. return;
  14577. }
  14578. this._gl.uniform1i(uniform, destination);
  14579. uniform._currentState = destination;
  14580. };
  14581. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14582. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14583. // Not ready?
  14584. if (!texture) {
  14585. if (this._boundTexturesCache[channel] != null) {
  14586. this._activeChannel = channel;
  14587. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14588. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14589. if (this.webGLVersion > 1) {
  14590. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14591. }
  14592. }
  14593. return false;
  14594. }
  14595. // Video
  14596. if (texture.video) {
  14597. this._activeChannel = channel;
  14598. texture.update();
  14599. }
  14600. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14601. texture.delayLoad();
  14602. return false;
  14603. }
  14604. var internalTexture;
  14605. if (texture.isReady()) {
  14606. internalTexture = texture.getInternalTexture();
  14607. }
  14608. else if (texture.isCube) {
  14609. internalTexture = this.emptyCubeTexture;
  14610. }
  14611. else if (texture.is3D) {
  14612. internalTexture = this.emptyTexture3D;
  14613. }
  14614. else {
  14615. internalTexture = this.emptyTexture;
  14616. }
  14617. if (!isPartOfTextureArray) {
  14618. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14619. }
  14620. if (this._boundTexturesCache[channel] === internalTexture) {
  14621. this._moveBoundTextureOnTop(internalTexture);
  14622. if (!isPartOfTextureArray) {
  14623. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14624. }
  14625. return false;
  14626. }
  14627. this._activeChannel = channel;
  14628. if (internalTexture && internalTexture.is3D) {
  14629. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14630. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14631. internalTexture._cachedWrapU = texture.wrapU;
  14632. switch (texture.wrapU) {
  14633. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14634. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14635. break;
  14636. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14637. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14638. break;
  14639. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14640. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14641. break;
  14642. }
  14643. }
  14644. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14645. internalTexture._cachedWrapV = texture.wrapV;
  14646. switch (texture.wrapV) {
  14647. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14648. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14649. break;
  14650. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14651. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14652. break;
  14653. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14654. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14655. break;
  14656. }
  14657. }
  14658. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14659. internalTexture._cachedWrapR = texture.wrapR;
  14660. switch (texture.wrapR) {
  14661. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14662. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14663. break;
  14664. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14665. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14666. break;
  14667. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14668. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14669. break;
  14670. }
  14671. }
  14672. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14673. }
  14674. else if (internalTexture && internalTexture.isCube) {
  14675. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14676. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14677. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14678. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14679. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14680. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14681. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14682. }
  14683. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14684. }
  14685. else {
  14686. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14687. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14688. internalTexture._cachedWrapU = texture.wrapU;
  14689. switch (texture.wrapU) {
  14690. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14691. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14692. break;
  14693. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14694. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14695. break;
  14696. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14697. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14698. break;
  14699. }
  14700. }
  14701. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14702. internalTexture._cachedWrapV = texture.wrapV;
  14703. switch (texture.wrapV) {
  14704. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14705. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14706. break;
  14707. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14708. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14709. break;
  14710. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14711. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14712. break;
  14713. }
  14714. }
  14715. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14716. }
  14717. return true;
  14718. };
  14719. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14720. if (channel < 0 || !uniform) {
  14721. return;
  14722. }
  14723. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14724. this._textureUnits = new Int32Array(textures.length);
  14725. }
  14726. for (var i = 0; i < textures.length; i++) {
  14727. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14728. }
  14729. this._gl.uniform1iv(uniform, this._textureUnits);
  14730. for (var index = 0; index < textures.length; index++) {
  14731. this._setTexture(this._textureUnits[index], textures[index], true);
  14732. }
  14733. };
  14734. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14735. var internalTexture = texture.getInternalTexture();
  14736. if (!internalTexture) {
  14737. return;
  14738. }
  14739. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14740. var value = texture.anisotropicFilteringLevel;
  14741. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14742. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14743. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14744. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14745. }
  14746. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14747. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14748. internalTexture._cachedAnisotropicFilteringLevel = value;
  14749. }
  14750. };
  14751. Engine.prototype.readPixels = function (x, y, width, height) {
  14752. var data = new Uint8Array(height * width * 4);
  14753. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14754. return data;
  14755. };
  14756. /**
  14757. * Add an externaly attached data from its key.
  14758. * This method call will fail and return false, if such key already exists.
  14759. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14760. * @param key the unique key that identifies the data
  14761. * @param data the data object to associate to the key for this Engine instance
  14762. * @return true if no such key were already present and the data was added successfully, false otherwise
  14763. */
  14764. Engine.prototype.addExternalData = function (key, data) {
  14765. if (!this._externalData) {
  14766. this._externalData = new BABYLON.StringDictionary();
  14767. }
  14768. return this._externalData.add(key, data);
  14769. };
  14770. /**
  14771. * Get an externaly attached data from its key
  14772. * @param key the unique key that identifies the data
  14773. * @return the associated data, if present (can be null), or undefined if not present
  14774. */
  14775. Engine.prototype.getExternalData = function (key) {
  14776. if (!this._externalData) {
  14777. this._externalData = new BABYLON.StringDictionary();
  14778. }
  14779. return this._externalData.get(key);
  14780. };
  14781. /**
  14782. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14783. * @param key the unique key that identifies the data
  14784. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14785. * @return the associated data, can be null if the factory returned null.
  14786. */
  14787. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14788. if (!this._externalData) {
  14789. this._externalData = new BABYLON.StringDictionary();
  14790. }
  14791. return this._externalData.getOrAddWithFactory(key, factory);
  14792. };
  14793. /**
  14794. * Remove an externaly attached data from the Engine instance
  14795. * @param key the unique key that identifies the data
  14796. * @return true if the data was successfully removed, false if it doesn't exist
  14797. */
  14798. Engine.prototype.removeExternalData = function (key) {
  14799. if (!this._externalData) {
  14800. this._externalData = new BABYLON.StringDictionary();
  14801. }
  14802. return this._externalData.remove(key);
  14803. };
  14804. Engine.prototype.unbindAllAttributes = function () {
  14805. if (this._mustWipeVertexAttributes) {
  14806. this._mustWipeVertexAttributes = false;
  14807. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14808. this._gl.disableVertexAttribArray(i);
  14809. this._vertexAttribArraysEnabled[i] = false;
  14810. this._currentBufferPointers[i].active = false;
  14811. }
  14812. return;
  14813. }
  14814. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14815. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14816. continue;
  14817. }
  14818. this._gl.disableVertexAttribArray(i);
  14819. this._vertexAttribArraysEnabled[i] = false;
  14820. this._currentBufferPointers[i].active = false;
  14821. }
  14822. };
  14823. Engine.prototype.releaseEffects = function () {
  14824. for (var name in this._compiledEffects) {
  14825. this._deleteProgram(this._compiledEffects[name]._program);
  14826. }
  14827. this._compiledEffects = {};
  14828. };
  14829. // Dispose
  14830. Engine.prototype.dispose = function () {
  14831. this.hideLoadingUI();
  14832. this.stopRenderLoop();
  14833. // Release postProcesses
  14834. while (this.postProcesses.length) {
  14835. this.postProcesses[0].dispose();
  14836. }
  14837. // Empty texture
  14838. if (this._emptyTexture) {
  14839. this._releaseTexture(this._emptyTexture);
  14840. this._emptyTexture = null;
  14841. }
  14842. if (this._emptyCubeTexture) {
  14843. this._releaseTexture(this._emptyCubeTexture);
  14844. this._emptyCubeTexture = null;
  14845. }
  14846. // Rescale PP
  14847. if (this._rescalePostProcess) {
  14848. this._rescalePostProcess.dispose();
  14849. }
  14850. // Release scenes
  14851. while (this.scenes.length) {
  14852. this.scenes[0].dispose();
  14853. }
  14854. // Release audio engine
  14855. if (Engine.audioEngine) {
  14856. Engine.audioEngine.dispose();
  14857. }
  14858. // Release effects
  14859. this.releaseEffects();
  14860. // Unbind
  14861. this.unbindAllAttributes();
  14862. if (this._dummyFramebuffer) {
  14863. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14864. }
  14865. //WebVR
  14866. this.disableVR();
  14867. // Events
  14868. if (BABYLON.Tools.IsWindowObjectExist()) {
  14869. window.removeEventListener("blur", this._onBlur);
  14870. window.removeEventListener("focus", this._onFocus);
  14871. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14872. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14873. if (this._renderingCanvas) {
  14874. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14875. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14876. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14877. if (!this._doNotHandleContextLost) {
  14878. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14879. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14880. }
  14881. }
  14882. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14883. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14884. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14885. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14886. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14887. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14888. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14889. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14890. if (this._onVrDisplayConnect) {
  14891. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14892. if (this._onVrDisplayDisconnect) {
  14893. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14894. }
  14895. if (this._onVrDisplayPresentChange) {
  14896. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14897. }
  14898. this._onVrDisplayConnect = null;
  14899. this._onVrDisplayDisconnect = null;
  14900. }
  14901. }
  14902. // Remove from Instances
  14903. var index = Engine.Instances.indexOf(this);
  14904. if (index >= 0) {
  14905. Engine.Instances.splice(index, 1);
  14906. }
  14907. this._workingCanvas = null;
  14908. this._workingContext = null;
  14909. this._currentBufferPointers = [];
  14910. this._renderingCanvas = null;
  14911. this._currentProgram = null;
  14912. this.onResizeObservable.clear();
  14913. this.onCanvasBlurObservable.clear();
  14914. this.onCanvasFocusObservable.clear();
  14915. this.onCanvasPointerOutObservable.clear();
  14916. this.onBeginFrameObservable.clear();
  14917. this.onEndFrameObservable.clear();
  14918. BABYLON.Effect.ResetCache();
  14919. // Abort active requests
  14920. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14921. var request = _a[_i];
  14922. request.abort();
  14923. }
  14924. };
  14925. // Loading screen
  14926. Engine.prototype.displayLoadingUI = function () {
  14927. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14928. return;
  14929. }
  14930. var loadingScreen = this.loadingScreen;
  14931. if (loadingScreen) {
  14932. loadingScreen.displayLoadingUI();
  14933. }
  14934. };
  14935. Engine.prototype.hideLoadingUI = function () {
  14936. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14937. return;
  14938. }
  14939. var loadingScreen = this.loadingScreen;
  14940. if (loadingScreen) {
  14941. loadingScreen.hideLoadingUI();
  14942. }
  14943. };
  14944. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14945. get: function () {
  14946. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14947. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14948. return this._loadingScreen;
  14949. },
  14950. set: function (loadingScreen) {
  14951. this._loadingScreen = loadingScreen;
  14952. },
  14953. enumerable: true,
  14954. configurable: true
  14955. });
  14956. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14957. set: function (text) {
  14958. this.loadingScreen.loadingUIText = text;
  14959. },
  14960. enumerable: true,
  14961. configurable: true
  14962. });
  14963. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14964. set: function (color) {
  14965. this.loadingScreen.loadingUIBackgroundColor = color;
  14966. },
  14967. enumerable: true,
  14968. configurable: true
  14969. });
  14970. Engine.prototype.attachContextLostEvent = function (callback) {
  14971. if (this._renderingCanvas) {
  14972. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14973. }
  14974. };
  14975. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14976. if (this._renderingCanvas) {
  14977. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14978. }
  14979. };
  14980. Engine.prototype.getVertexShaderSource = function (program) {
  14981. var shaders = this._gl.getAttachedShaders(program);
  14982. if (!shaders) {
  14983. return null;
  14984. }
  14985. return this._gl.getShaderSource(shaders[0]);
  14986. };
  14987. Engine.prototype.getFragmentShaderSource = function (program) {
  14988. var shaders = this._gl.getAttachedShaders(program);
  14989. if (!shaders) {
  14990. return null;
  14991. }
  14992. return this._gl.getShaderSource(shaders[1]);
  14993. };
  14994. Engine.prototype.getError = function () {
  14995. return this._gl.getError();
  14996. };
  14997. // FPS
  14998. Engine.prototype.getFps = function () {
  14999. return this._fps;
  15000. };
  15001. Engine.prototype.getDeltaTime = function () {
  15002. return this._deltaTime;
  15003. };
  15004. Engine.prototype._measureFps = function () {
  15005. this._performanceMonitor.sampleFrame();
  15006. this._fps = this._performanceMonitor.averageFPS;
  15007. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15008. };
  15009. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15010. if (faceIndex === void 0) { faceIndex = -1; }
  15011. var gl = this._gl;
  15012. if (!this._dummyFramebuffer) {
  15013. var dummy = gl.createFramebuffer();
  15014. if (!dummy) {
  15015. throw new Error("Unable to create dummy framebuffer");
  15016. }
  15017. this._dummyFramebuffer = dummy;
  15018. }
  15019. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15020. if (faceIndex > -1) {
  15021. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15022. }
  15023. else {
  15024. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15025. }
  15026. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15027. var buffer;
  15028. switch (readType) {
  15029. case gl.UNSIGNED_BYTE:
  15030. buffer = new Uint8Array(4 * width * height);
  15031. readType = gl.UNSIGNED_BYTE;
  15032. break;
  15033. default:
  15034. buffer = new Float32Array(4 * width * height);
  15035. readType = gl.FLOAT;
  15036. break;
  15037. }
  15038. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15039. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15040. return buffer;
  15041. };
  15042. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15043. if (this._webGLVersion > 1) {
  15044. return this._caps.colorBufferFloat;
  15045. }
  15046. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15047. };
  15048. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15049. if (this._webGLVersion > 1) {
  15050. return this._caps.colorBufferFloat;
  15051. }
  15052. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15053. };
  15054. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15055. Engine.prototype._canRenderToFramebuffer = function (type) {
  15056. var gl = this._gl;
  15057. //clear existing errors
  15058. while (gl.getError() !== gl.NO_ERROR) { }
  15059. var successful = true;
  15060. var texture = gl.createTexture();
  15061. gl.bindTexture(gl.TEXTURE_2D, texture);
  15062. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15064. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15065. var fb = gl.createFramebuffer();
  15066. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15067. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15068. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15069. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15070. successful = successful && (gl.getError() === gl.NO_ERROR);
  15071. //try render by clearing frame buffer's color buffer
  15072. if (successful) {
  15073. gl.clear(gl.COLOR_BUFFER_BIT);
  15074. successful = successful && (gl.getError() === gl.NO_ERROR);
  15075. }
  15076. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15077. if (successful) {
  15078. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15079. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15080. var readFormat = gl.RGBA;
  15081. var readType = gl.UNSIGNED_BYTE;
  15082. var buffer = new Uint8Array(4);
  15083. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15084. successful = successful && (gl.getError() === gl.NO_ERROR);
  15085. }
  15086. //clean up
  15087. gl.deleteTexture(texture);
  15088. gl.deleteFramebuffer(fb);
  15089. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15090. //clear accumulated errors
  15091. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15092. return successful;
  15093. };
  15094. Engine.prototype._getWebGLTextureType = function (type) {
  15095. if (type === Engine.TEXTURETYPE_FLOAT) {
  15096. return this._gl.FLOAT;
  15097. }
  15098. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15099. // Add Half Float Constant.
  15100. return this._gl.HALF_FLOAT_OES;
  15101. }
  15102. return this._gl.UNSIGNED_BYTE;
  15103. };
  15104. ;
  15105. /** @ignore */
  15106. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15107. if (this._webGLVersion === 1) {
  15108. return this._gl.RGBA;
  15109. }
  15110. if (type === Engine.TEXTURETYPE_FLOAT) {
  15111. if (format) {
  15112. switch (format) {
  15113. case Engine.TEXTUREFORMAT_R32F:
  15114. return this._gl.R32F;
  15115. case Engine.TEXTUREFORMAT_RG32F:
  15116. return this._gl.RG32F;
  15117. case Engine.TEXTUREFORMAT_RGB32F:
  15118. return this._gl.RGB32F;
  15119. }
  15120. }
  15121. return this._gl.RGBA32F;
  15122. }
  15123. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15124. return this._gl.RGBA16F;
  15125. }
  15126. return this._gl.RGBA;
  15127. };
  15128. ;
  15129. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15130. if (type === Engine.TEXTURETYPE_FLOAT) {
  15131. return this._gl.RGBA32F;
  15132. }
  15133. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15134. return this._gl.RGBA16F;
  15135. }
  15136. return this._gl.RGBA8;
  15137. };
  15138. ;
  15139. Engine.prototype.createQuery = function () {
  15140. return this._gl.createQuery();
  15141. };
  15142. Engine.prototype.deleteQuery = function (query) {
  15143. this._gl.deleteQuery(query);
  15144. return this;
  15145. };
  15146. Engine.prototype.isQueryResultAvailable = function (query) {
  15147. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15148. };
  15149. Engine.prototype.getQueryResult = function (query) {
  15150. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15151. };
  15152. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15153. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15154. this._gl.beginQuery(glAlgorithm, query);
  15155. return this;
  15156. };
  15157. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15158. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15159. this._gl.endQuery(glAlgorithm);
  15160. return this;
  15161. };
  15162. /* Time queries */
  15163. Engine.prototype._createTimeQuery = function () {
  15164. var timerQuery = this._caps.timerQuery;
  15165. if (timerQuery.createQueryEXT) {
  15166. return timerQuery.createQueryEXT();
  15167. }
  15168. return this.createQuery();
  15169. };
  15170. Engine.prototype._deleteTimeQuery = function (query) {
  15171. var timerQuery = this._caps.timerQuery;
  15172. if (timerQuery.deleteQueryEXT) {
  15173. timerQuery.deleteQueryEXT(query);
  15174. return;
  15175. }
  15176. this.deleteQuery(query);
  15177. };
  15178. Engine.prototype._getTimeQueryResult = function (query) {
  15179. var timerQuery = this._caps.timerQuery;
  15180. if (timerQuery.getQueryObjectEXT) {
  15181. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15182. }
  15183. return this.getQueryResult(query);
  15184. };
  15185. Engine.prototype._getTimeQueryAvailability = function (query) {
  15186. var timerQuery = this._caps.timerQuery;
  15187. if (timerQuery.getQueryObjectEXT) {
  15188. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15189. }
  15190. return this.isQueryResultAvailable(query);
  15191. };
  15192. Engine.prototype.startTimeQuery = function () {
  15193. var timerQuery = this._caps.timerQuery;
  15194. if (!timerQuery) {
  15195. return null;
  15196. }
  15197. var token = new BABYLON._TimeToken();
  15198. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15199. if (this._caps.canUseTimestampForTimerQuery) {
  15200. token._startTimeQuery = this._createTimeQuery();
  15201. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15202. }
  15203. else {
  15204. if (this._currentNonTimestampToken) {
  15205. return this._currentNonTimestampToken;
  15206. }
  15207. token._timeElapsedQuery = this._createTimeQuery();
  15208. if (timerQuery.beginQueryEXT) {
  15209. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15210. }
  15211. else {
  15212. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15213. }
  15214. this._currentNonTimestampToken = token;
  15215. }
  15216. return token;
  15217. };
  15218. Engine.prototype.endTimeQuery = function (token) {
  15219. var timerQuery = this._caps.timerQuery;
  15220. if (!timerQuery || !token) {
  15221. return -1;
  15222. }
  15223. if (this._caps.canUseTimestampForTimerQuery) {
  15224. if (!token._startTimeQuery) {
  15225. return -1;
  15226. }
  15227. if (!token._endTimeQuery) {
  15228. token._endTimeQuery = this._createTimeQuery();
  15229. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15230. }
  15231. }
  15232. else if (!token._timeElapsedQueryEnded) {
  15233. if (!token._timeElapsedQuery) {
  15234. return -1;
  15235. }
  15236. if (timerQuery.endQueryEXT) {
  15237. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15238. }
  15239. else {
  15240. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15241. }
  15242. token._timeElapsedQueryEnded = true;
  15243. }
  15244. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15245. var available = false;
  15246. if (token._endTimeQuery) {
  15247. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15248. }
  15249. else if (token._timeElapsedQuery) {
  15250. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15251. }
  15252. if (available && !disjoint) {
  15253. var result = 0;
  15254. if (this._caps.canUseTimestampForTimerQuery) {
  15255. if (!token._startTimeQuery || !token._endTimeQuery) {
  15256. return -1;
  15257. }
  15258. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15259. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15260. result = timeEnd - timeStart;
  15261. this._deleteTimeQuery(token._startTimeQuery);
  15262. this._deleteTimeQuery(token._endTimeQuery);
  15263. token._startTimeQuery = null;
  15264. token._endTimeQuery = null;
  15265. }
  15266. else {
  15267. if (!token._timeElapsedQuery) {
  15268. return -1;
  15269. }
  15270. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15271. this._deleteTimeQuery(token._timeElapsedQuery);
  15272. token._timeElapsedQuery = null;
  15273. token._timeElapsedQueryEnded = false;
  15274. this._currentNonTimestampToken = null;
  15275. }
  15276. return result;
  15277. }
  15278. return -1;
  15279. };
  15280. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15281. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15282. };
  15283. // Transform feedback
  15284. Engine.prototype.createTransformFeedback = function () {
  15285. return this._gl.createTransformFeedback();
  15286. };
  15287. Engine.prototype.deleteTransformFeedback = function (value) {
  15288. this._gl.deleteTransformFeedback(value);
  15289. };
  15290. Engine.prototype.bindTransformFeedback = function (value) {
  15291. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15292. };
  15293. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15294. if (usePoints === void 0) { usePoints = true; }
  15295. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15296. };
  15297. Engine.prototype.endTransformFeedback = function () {
  15298. this._gl.endTransformFeedback();
  15299. };
  15300. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15301. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15302. };
  15303. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15304. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15305. };
  15306. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15307. var _this = this;
  15308. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15309. this._activeRequests.push(request);
  15310. request.onCompleteObservable.add(function (request) {
  15311. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15312. });
  15313. return request;
  15314. };
  15315. /** @ignore */
  15316. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15317. var _this = this;
  15318. return new Promise(function (resolve, reject) {
  15319. _this._loadFile(url, function (data) {
  15320. resolve(data);
  15321. }, undefined, database, useArrayBuffer, function (request, exception) {
  15322. reject(exception);
  15323. });
  15324. });
  15325. };
  15326. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15327. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15328. var onload = function (data) {
  15329. loadedFiles[index] = data;
  15330. loadedFiles._internalCount++;
  15331. if (loadedFiles._internalCount === 6) {
  15332. onfinish(loadedFiles);
  15333. }
  15334. };
  15335. var onerror = function (request, exception) {
  15336. if (onErrorCallBack && request) {
  15337. onErrorCallBack(request.status + " " + request.statusText, exception);
  15338. }
  15339. };
  15340. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15341. };
  15342. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15343. if (onError === void 0) { onError = null; }
  15344. var loadedFiles = [];
  15345. loadedFiles._internalCount = 0;
  15346. for (var index = 0; index < 6; index++) {
  15347. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15348. }
  15349. };
  15350. // Statics
  15351. Engine.isSupported = function () {
  15352. try {
  15353. var tempcanvas = document.createElement("canvas");
  15354. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15355. return gl != null && !!window.WebGLRenderingContext;
  15356. }
  15357. catch (e) {
  15358. return false;
  15359. }
  15360. };
  15361. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15362. Engine.ExceptionList = [
  15363. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15364. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15365. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15366. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15367. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15368. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15369. ];
  15370. Engine.Instances = new Array();
  15371. // Const statics
  15372. Engine._ALPHA_DISABLE = 0;
  15373. Engine._ALPHA_ADD = 1;
  15374. Engine._ALPHA_COMBINE = 2;
  15375. Engine._ALPHA_SUBTRACT = 3;
  15376. Engine._ALPHA_MULTIPLY = 4;
  15377. Engine._ALPHA_MAXIMIZED = 5;
  15378. Engine._ALPHA_ONEONE = 6;
  15379. Engine._ALPHA_PREMULTIPLIED = 7;
  15380. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15381. Engine._ALPHA_INTERPOLATE = 9;
  15382. Engine._ALPHA_SCREENMODE = 10;
  15383. Engine._DELAYLOADSTATE_NONE = 0;
  15384. Engine._DELAYLOADSTATE_LOADED = 1;
  15385. Engine._DELAYLOADSTATE_LOADING = 2;
  15386. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15387. Engine._TEXTUREFORMAT_ALPHA = 0;
  15388. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15389. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15390. Engine._TEXTUREFORMAT_RGB = 4;
  15391. Engine._TEXTUREFORMAT_RGBA = 5;
  15392. Engine._TEXTUREFORMAT_R32F = 6;
  15393. Engine._TEXTUREFORMAT_RG32F = 7;
  15394. Engine._TEXTUREFORMAT_RGB32F = 8;
  15395. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15396. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15397. Engine._TEXTURETYPE_FLOAT = 1;
  15398. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15399. // Depht or Stencil test Constants.
  15400. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15401. 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.
  15402. 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.
  15403. 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.
  15404. 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.
  15405. 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.
  15406. 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.
  15407. 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.
  15408. // Stencil Actions Constants.
  15409. Engine._KEEP = 0x1E00;
  15410. Engine._REPLACE = 0x1E01;
  15411. Engine._INCR = 0x1E02;
  15412. Engine._DECR = 0x1E03;
  15413. Engine._INVERT = 0x150A;
  15414. Engine._INCR_WRAP = 0x8507;
  15415. Engine._DECR_WRAP = 0x8508;
  15416. // Texture rescaling mode
  15417. Engine._SCALEMODE_FLOOR = 1;
  15418. Engine._SCALEMODE_NEAREST = 2;
  15419. Engine._SCALEMODE_CEILING = 3;
  15420. // Updatable statics so stick with vars here
  15421. Engine.CollisionsEpsilon = 0.001;
  15422. Engine.CodeRepository = "src/";
  15423. Engine.ShadersRepository = "src/Shaders/";
  15424. return Engine;
  15425. }());
  15426. BABYLON.Engine = Engine;
  15427. })(BABYLON || (BABYLON = {}));
  15428. //# sourceMappingURL=babylon.engine.js.map
  15429. var BABYLON;
  15430. (function (BABYLON) {
  15431. /**
  15432. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15433. */
  15434. var Node = /** @class */ (function () {
  15435. /**
  15436. * Creates a new Node
  15437. * @param {string} name - the name and id to be given to this node
  15438. * @param {BABYLON.Scene} the scene this node will be added to
  15439. */
  15440. function Node(name, scene) {
  15441. if (scene === void 0) { scene = null; }
  15442. /**
  15443. * Gets or sets a string used to store user defined state for the node
  15444. */
  15445. this.state = "";
  15446. /**
  15447. * Gets or sets an object used to store user defined information for the node
  15448. */
  15449. this.metadata = null;
  15450. /**
  15451. * Gets or sets a boolean used to define if the node must be serialized
  15452. */
  15453. this.doNotSerialize = false;
  15454. /** @ignore */
  15455. this._isDisposed = false;
  15456. /**
  15457. * Gets a list of {BABYLON.Animation} associated with the node
  15458. */
  15459. this.animations = new Array();
  15460. this._ranges = {};
  15461. this._isEnabled = true;
  15462. this._isReady = true;
  15463. /** @ignore */
  15464. this._currentRenderId = -1;
  15465. this._parentRenderId = -1;
  15466. this._animationPropertiesOverride = null;
  15467. /**
  15468. * An event triggered when the mesh is disposed
  15469. * @type {BABYLON.Observable}
  15470. */
  15471. this.onDisposeObservable = new BABYLON.Observable();
  15472. // Behaviors
  15473. this._behaviors = new Array();
  15474. this.name = name;
  15475. this.id = name;
  15476. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15477. this.uniqueId = this._scene.getUniqueId();
  15478. this._initCache();
  15479. }
  15480. /**
  15481. * Gets a boolean indicating if the node has been disposed
  15482. * @returns true if the node was disposed
  15483. */
  15484. Node.prototype.isDisposed = function () {
  15485. return this._isDisposed;
  15486. };
  15487. Object.defineProperty(Node.prototype, "parent", {
  15488. get: function () {
  15489. return this._parentNode;
  15490. },
  15491. /**
  15492. * Gets or sets the parent of the node
  15493. */
  15494. set: function (parent) {
  15495. if (this._parentNode === parent) {
  15496. return;
  15497. }
  15498. // Remove self from list of children of parent
  15499. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15500. var index = this._parentNode._children.indexOf(this);
  15501. if (index !== -1) {
  15502. this._parentNode._children.splice(index, 1);
  15503. }
  15504. }
  15505. // Store new parent
  15506. this._parentNode = parent;
  15507. // Add as child to new parent
  15508. if (this._parentNode) {
  15509. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15510. this._parentNode._children = new Array();
  15511. }
  15512. this._parentNode._children.push(this);
  15513. }
  15514. },
  15515. enumerable: true,
  15516. configurable: true
  15517. });
  15518. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15519. /**
  15520. * Gets or sets the animation properties override
  15521. */
  15522. get: function () {
  15523. return this._animationPropertiesOverride;
  15524. },
  15525. set: function (value) {
  15526. this._animationPropertiesOverride = value;
  15527. },
  15528. enumerable: true,
  15529. configurable: true
  15530. });
  15531. /**
  15532. * Gets a string idenfifying the name of the class
  15533. * @returns "Node" string
  15534. */
  15535. Node.prototype.getClassName = function () {
  15536. return "Node";
  15537. };
  15538. Object.defineProperty(Node.prototype, "onDispose", {
  15539. /**
  15540. * Sets a callback that will be raised when the node will be disposed
  15541. */
  15542. set: function (callback) {
  15543. if (this._onDisposeObserver) {
  15544. this.onDisposeObservable.remove(this._onDisposeObserver);
  15545. }
  15546. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15547. },
  15548. enumerable: true,
  15549. configurable: true
  15550. });
  15551. /**
  15552. * Gets the scene of the node
  15553. * @returns a {BABYLON.Scene}
  15554. */
  15555. Node.prototype.getScene = function () {
  15556. return this._scene;
  15557. };
  15558. /**
  15559. * Gets the engine of the node
  15560. * @returns a {BABYLON.Engine}
  15561. */
  15562. Node.prototype.getEngine = function () {
  15563. return this._scene.getEngine();
  15564. };
  15565. /**
  15566. * Attach a behavior to the node
  15567. * @see http://doc.babylonjs.com/features/behaviour
  15568. * @param behavior defines the behavior to attach
  15569. * @returns the current Node
  15570. */
  15571. Node.prototype.addBehavior = function (behavior) {
  15572. var _this = this;
  15573. var index = this._behaviors.indexOf(behavior);
  15574. if (index !== -1) {
  15575. return this;
  15576. }
  15577. behavior.init();
  15578. if (this._scene.isLoading) {
  15579. // We defer the attach when the scene will be loaded
  15580. var observer = this._scene.onDataLoadedObservable.add(function () {
  15581. behavior.attach(_this);
  15582. setTimeout(function () {
  15583. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15584. _this._scene.onDataLoadedObservable.remove(observer);
  15585. }, 0);
  15586. });
  15587. }
  15588. else {
  15589. behavior.attach(this);
  15590. }
  15591. this._behaviors.push(behavior);
  15592. return this;
  15593. };
  15594. /**
  15595. * Remove an attached behavior
  15596. * @see http://doc.babylonjs.com/features/behaviour
  15597. * @param behavior defines the behavior to attach
  15598. * @returns the current Node
  15599. */
  15600. Node.prototype.removeBehavior = function (behavior) {
  15601. var index = this._behaviors.indexOf(behavior);
  15602. if (index === -1) {
  15603. return this;
  15604. }
  15605. this._behaviors[index].detach();
  15606. this._behaviors.splice(index, 1);
  15607. return this;
  15608. };
  15609. Object.defineProperty(Node.prototype, "behaviors", {
  15610. /**
  15611. * Gets the list of attached behaviors
  15612. * @see http://doc.babylonjs.com/features/behaviour
  15613. */
  15614. get: function () {
  15615. return this._behaviors;
  15616. },
  15617. enumerable: true,
  15618. configurable: true
  15619. });
  15620. /**
  15621. * Gets an attached behavior by name
  15622. * @param name defines the name of the behavior to look for
  15623. * @see http://doc.babylonjs.com/features/behaviour
  15624. * @returns null if behavior was not found else the requested behavior
  15625. */
  15626. Node.prototype.getBehaviorByName = function (name) {
  15627. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15628. var behavior = _a[_i];
  15629. if (behavior.name === name) {
  15630. return behavior;
  15631. }
  15632. }
  15633. return null;
  15634. };
  15635. /**
  15636. * Returns the world matrix of the node
  15637. * @returns a matrix containing the node's world matrix
  15638. */
  15639. Node.prototype.getWorldMatrix = function () {
  15640. return BABYLON.Matrix.Identity();
  15641. };
  15642. // override it in derived class if you add new variables to the cache
  15643. // and call the parent class method
  15644. /** @ignore */
  15645. Node.prototype._initCache = function () {
  15646. this._cache = {};
  15647. this._cache.parent = undefined;
  15648. };
  15649. /** @ignore */
  15650. Node.prototype.updateCache = function (force) {
  15651. if (!force && this.isSynchronized())
  15652. return;
  15653. this._cache.parent = this.parent;
  15654. this._updateCache();
  15655. };
  15656. // override it in derived class if you add new variables to the cache
  15657. // and call the parent class method if !ignoreParentClass
  15658. /** @ignore */
  15659. Node.prototype._updateCache = function (ignoreParentClass) {
  15660. };
  15661. // override it in derived class if you add new variables to the cache
  15662. /** @ignore */
  15663. Node.prototype._isSynchronized = function () {
  15664. return true;
  15665. };
  15666. /** @ignore */
  15667. Node.prototype._markSyncedWithParent = function () {
  15668. if (this.parent) {
  15669. this._parentRenderId = this.parent._currentRenderId;
  15670. }
  15671. };
  15672. /** @ignore */
  15673. Node.prototype.isSynchronizedWithParent = function () {
  15674. if (!this.parent) {
  15675. return true;
  15676. }
  15677. if (this._parentRenderId !== this.parent._currentRenderId) {
  15678. return false;
  15679. }
  15680. return this.parent.isSynchronized();
  15681. };
  15682. /** @ignore */
  15683. Node.prototype.isSynchronized = function (updateCache) {
  15684. var check = this.hasNewParent();
  15685. check = check || !this.isSynchronizedWithParent();
  15686. check = check || !this._isSynchronized();
  15687. if (updateCache)
  15688. this.updateCache(true);
  15689. return !check;
  15690. };
  15691. /** @ignore */
  15692. Node.prototype.hasNewParent = function (update) {
  15693. if (this._cache.parent === this.parent)
  15694. return false;
  15695. if (update)
  15696. this._cache.parent = this.parent;
  15697. return true;
  15698. };
  15699. /**
  15700. * Is this node ready to be used/rendered
  15701. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15702. * @return true if the node is ready
  15703. */
  15704. Node.prototype.isReady = function (completeCheck) {
  15705. if (completeCheck === void 0) { completeCheck = false; }
  15706. return this._isReady;
  15707. };
  15708. /**
  15709. * Is this node enabled?
  15710. * 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
  15711. * @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
  15712. * @return whether this node (and its parent) is enabled
  15713. * @see setEnabled
  15714. */
  15715. Node.prototype.isEnabled = function (checkAncestors) {
  15716. if (checkAncestors === void 0) { checkAncestors = true; }
  15717. if (checkAncestors === false) {
  15718. return this._isEnabled;
  15719. }
  15720. if (this._isEnabled === false) {
  15721. return false;
  15722. }
  15723. if (this.parent !== undefined && this.parent !== null) {
  15724. return this.parent.isEnabled(checkAncestors);
  15725. }
  15726. return true;
  15727. };
  15728. /**
  15729. * Set the enabled state of this node
  15730. * @param value defines the new enabled state
  15731. * @see isEnabled
  15732. */
  15733. Node.prototype.setEnabled = function (value) {
  15734. this._isEnabled = value;
  15735. };
  15736. /**
  15737. * Is this node a descendant of the given node?
  15738. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15739. * @param ancestor defines the parent node to inspect
  15740. * @see parent
  15741. * @returns a boolean indicating if this node is a descendant of the given node
  15742. */
  15743. Node.prototype.isDescendantOf = function (ancestor) {
  15744. if (this.parent) {
  15745. if (this.parent === ancestor) {
  15746. return true;
  15747. }
  15748. return this.parent.isDescendantOf(ancestor);
  15749. }
  15750. return false;
  15751. };
  15752. /** @ignore */
  15753. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15754. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15755. if (!this._children) {
  15756. return;
  15757. }
  15758. for (var index = 0; index < this._children.length; index++) {
  15759. var item = this._children[index];
  15760. if (!predicate || predicate(item)) {
  15761. results.push(item);
  15762. }
  15763. if (!directDescendantsOnly) {
  15764. item._getDescendants(results, false, predicate);
  15765. }
  15766. }
  15767. };
  15768. /**
  15769. * Will return all nodes that have this node as ascendant
  15770. * @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
  15771. * @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
  15772. * @return all children nodes of all types
  15773. */
  15774. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15775. var results = new Array();
  15776. this._getDescendants(results, directDescendantsOnly, predicate);
  15777. return results;
  15778. };
  15779. /**
  15780. * Get all child-meshes of this node
  15781. * @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
  15782. * @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
  15783. * @returns an array of {BABYLON.AbstractMesh}
  15784. */
  15785. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15786. var results = [];
  15787. this._getDescendants(results, directDescendantsOnly, function (node) {
  15788. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15789. });
  15790. return results;
  15791. };
  15792. /**
  15793. * Get all child-transformNodes of this node
  15794. * @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
  15795. * @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
  15796. * @returns an array of {BABYLON.TransformNode}
  15797. */
  15798. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15799. var results = [];
  15800. this._getDescendants(results, directDescendantsOnly, function (node) {
  15801. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15802. });
  15803. return results;
  15804. };
  15805. /**
  15806. * Get all direct children of this node
  15807. * @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
  15808. * @returns an array of {BABYLON.Node}
  15809. */
  15810. Node.prototype.getChildren = function (predicate) {
  15811. return this.getDescendants(true, predicate);
  15812. };
  15813. /** @ignore */
  15814. Node.prototype._setReady = function (state) {
  15815. if (state === this._isReady) {
  15816. return;
  15817. }
  15818. if (!state) {
  15819. this._isReady = false;
  15820. return;
  15821. }
  15822. this._isReady = true;
  15823. if (this.onReady) {
  15824. this.onReady(this);
  15825. }
  15826. };
  15827. /**
  15828. * Get an animation by name
  15829. * @param name defines the name of the animation to look for
  15830. * @returns null if not found else the requested animation
  15831. */
  15832. Node.prototype.getAnimationByName = function (name) {
  15833. for (var i = 0; i < this.animations.length; i++) {
  15834. var animation = this.animations[i];
  15835. if (animation.name === name) {
  15836. return animation;
  15837. }
  15838. }
  15839. return null;
  15840. };
  15841. /**
  15842. * Creates an animation range for this node
  15843. * @param name defines the name of the range
  15844. * @param from defines the starting key
  15845. * @param to defines the end key
  15846. */
  15847. Node.prototype.createAnimationRange = function (name, from, to) {
  15848. // check name not already in use
  15849. if (!this._ranges[name]) {
  15850. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15851. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15852. if (this.animations[i]) {
  15853. this.animations[i].createRange(name, from, to);
  15854. }
  15855. }
  15856. }
  15857. };
  15858. /**
  15859. * Delete a specific animation range
  15860. * @param name defines the name of the range to delete
  15861. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15862. */
  15863. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15864. if (deleteFrames === void 0) { deleteFrames = true; }
  15865. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15866. if (this.animations[i]) {
  15867. this.animations[i].deleteRange(name, deleteFrames);
  15868. }
  15869. }
  15870. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15871. };
  15872. /**
  15873. * Get an animation range by name
  15874. * @param name defines the name of the animation range to look for
  15875. * @returns null if not found else the requested animation range
  15876. */
  15877. Node.prototype.getAnimationRange = function (name) {
  15878. return this._ranges[name];
  15879. };
  15880. /**
  15881. * Will start the animation sequence
  15882. * @param name defines the range frames for animation sequence
  15883. * @param loop defines if the animation should loop (false by default)
  15884. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15885. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15886. * @returns the object created for this animation. If range does not exist, it will return null
  15887. */
  15888. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15889. var range = this.getAnimationRange(name);
  15890. if (!range) {
  15891. return null;
  15892. }
  15893. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15894. };
  15895. /**
  15896. * Serialize animation ranges into a JSON compatible object
  15897. * @returns serialization object
  15898. */
  15899. Node.prototype.serializeAnimationRanges = function () {
  15900. var serializationRanges = [];
  15901. for (var name in this._ranges) {
  15902. var localRange = this._ranges[name];
  15903. if (!localRange) {
  15904. continue;
  15905. }
  15906. var range = {};
  15907. range.name = name;
  15908. range.from = localRange.from;
  15909. range.to = localRange.to;
  15910. serializationRanges.push(range);
  15911. }
  15912. return serializationRanges;
  15913. };
  15914. /**
  15915. * Computes the world matrix of the node
  15916. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15917. * @returns the world matrix
  15918. */
  15919. Node.prototype.computeWorldMatrix = function (force) {
  15920. return BABYLON.Matrix.Identity();
  15921. };
  15922. /**
  15923. * Releases all associated resources
  15924. */
  15925. Node.prototype.dispose = function () {
  15926. this.parent = null;
  15927. // Callback
  15928. this.onDisposeObservable.notifyObservers(this);
  15929. this.onDisposeObservable.clear();
  15930. // Behaviors
  15931. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15932. var behavior = _a[_i];
  15933. behavior.detach();
  15934. }
  15935. this._behaviors = [];
  15936. this._isDisposed = true;
  15937. };
  15938. /**
  15939. * Parse animation range data from a serialization object and store them into a given node
  15940. * @param node defines where to store the animation ranges
  15941. * @param parsedNode defines the serialization object to read data from
  15942. * @param scene defines the hosting scene
  15943. */
  15944. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15945. if (parsedNode.ranges) {
  15946. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15947. var data = parsedNode.ranges[index];
  15948. node.createAnimationRange(data.name, data.from, data.to);
  15949. }
  15950. }
  15951. };
  15952. __decorate([
  15953. BABYLON.serialize()
  15954. ], Node.prototype, "name", void 0);
  15955. __decorate([
  15956. BABYLON.serialize()
  15957. ], Node.prototype, "id", void 0);
  15958. __decorate([
  15959. BABYLON.serialize()
  15960. ], Node.prototype, "uniqueId", void 0);
  15961. __decorate([
  15962. BABYLON.serialize()
  15963. ], Node.prototype, "state", void 0);
  15964. __decorate([
  15965. BABYLON.serialize()
  15966. ], Node.prototype, "metadata", void 0);
  15967. return Node;
  15968. }());
  15969. BABYLON.Node = Node;
  15970. })(BABYLON || (BABYLON = {}));
  15971. //# sourceMappingURL=babylon.node.js.map
  15972. var BABYLON;
  15973. (function (BABYLON) {
  15974. var BoundingSphere = /** @class */ (function () {
  15975. function BoundingSphere(minimum, maximum) {
  15976. this.minimum = minimum;
  15977. this.maximum = maximum;
  15978. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15979. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15980. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15981. this.radius = distance * 0.5;
  15982. this.centerWorld = BABYLON.Vector3.Zero();
  15983. this._update(BABYLON.Matrix.Identity());
  15984. }
  15985. // Methods
  15986. BoundingSphere.prototype._update = function (world) {
  15987. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15988. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15989. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15990. };
  15991. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15992. for (var i = 0; i < 6; i++) {
  15993. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15994. return false;
  15995. }
  15996. return true;
  15997. };
  15998. BoundingSphere.prototype.intersectsPoint = function (point) {
  15999. var x = this.centerWorld.x - point.x;
  16000. var y = this.centerWorld.y - point.y;
  16001. var z = this.centerWorld.z - point.z;
  16002. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16003. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16004. return false;
  16005. return true;
  16006. };
  16007. // Statics
  16008. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16009. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16010. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16011. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16012. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16013. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16014. return false;
  16015. return true;
  16016. };
  16017. return BoundingSphere;
  16018. }());
  16019. BABYLON.BoundingSphere = BoundingSphere;
  16020. })(BABYLON || (BABYLON = {}));
  16021. //# sourceMappingURL=babylon.boundingSphere.js.map
  16022. var BABYLON;
  16023. (function (BABYLON) {
  16024. var BoundingBox = /** @class */ (function () {
  16025. function BoundingBox(minimum, maximum) {
  16026. this.minimum = minimum;
  16027. this.maximum = maximum;
  16028. this.vectors = new Array();
  16029. this.vectorsWorld = new Array();
  16030. // Bounding vectors
  16031. this.vectors.push(this.minimum.clone());
  16032. this.vectors.push(this.maximum.clone());
  16033. this.vectors.push(this.minimum.clone());
  16034. this.vectors[2].x = this.maximum.x;
  16035. this.vectors.push(this.minimum.clone());
  16036. this.vectors[3].y = this.maximum.y;
  16037. this.vectors.push(this.minimum.clone());
  16038. this.vectors[4].z = this.maximum.z;
  16039. this.vectors.push(this.maximum.clone());
  16040. this.vectors[5].z = this.minimum.z;
  16041. this.vectors.push(this.maximum.clone());
  16042. this.vectors[6].x = this.minimum.x;
  16043. this.vectors.push(this.maximum.clone());
  16044. this.vectors[7].y = this.minimum.y;
  16045. // OBB
  16046. this.center = this.maximum.add(this.minimum).scale(0.5);
  16047. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16048. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16049. // World
  16050. for (var index = 0; index < this.vectors.length; index++) {
  16051. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16052. }
  16053. this.minimumWorld = BABYLON.Vector3.Zero();
  16054. this.maximumWorld = BABYLON.Vector3.Zero();
  16055. this.centerWorld = BABYLON.Vector3.Zero();
  16056. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16057. this._update(BABYLON.Matrix.Identity());
  16058. }
  16059. // Methods
  16060. BoundingBox.prototype.getWorldMatrix = function () {
  16061. return this._worldMatrix;
  16062. };
  16063. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16064. this._worldMatrix.copyFrom(matrix);
  16065. return this;
  16066. };
  16067. BoundingBox.prototype._update = function (world) {
  16068. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16069. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16070. for (var index = 0; index < this.vectors.length; index++) {
  16071. var v = this.vectorsWorld[index];
  16072. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16073. if (v.x < this.minimumWorld.x)
  16074. this.minimumWorld.x = v.x;
  16075. if (v.y < this.minimumWorld.y)
  16076. this.minimumWorld.y = v.y;
  16077. if (v.z < this.minimumWorld.z)
  16078. this.minimumWorld.z = v.z;
  16079. if (v.x > this.maximumWorld.x)
  16080. this.maximumWorld.x = v.x;
  16081. if (v.y > this.maximumWorld.y)
  16082. this.maximumWorld.y = v.y;
  16083. if (v.z > this.maximumWorld.z)
  16084. this.maximumWorld.z = v.z;
  16085. }
  16086. // Extend
  16087. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16088. this.extendSizeWorld.scaleInPlace(0.5);
  16089. // OBB
  16090. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16091. this.centerWorld.scaleInPlace(0.5);
  16092. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16093. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16094. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16095. this._worldMatrix = world;
  16096. };
  16097. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16098. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16099. };
  16100. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16101. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16102. };
  16103. BoundingBox.prototype.intersectsPoint = function (point) {
  16104. var delta = -BABYLON.Epsilon;
  16105. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16106. return false;
  16107. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16108. return false;
  16109. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16110. return false;
  16111. return true;
  16112. };
  16113. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16114. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16115. };
  16116. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16117. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16118. return false;
  16119. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16120. return false;
  16121. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16122. return false;
  16123. return true;
  16124. };
  16125. // Statics
  16126. BoundingBox.Intersects = function (box0, box1) {
  16127. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16128. return false;
  16129. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16130. return false;
  16131. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16132. return false;
  16133. return true;
  16134. };
  16135. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16136. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16137. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16138. return (num <= (sphereRadius * sphereRadius));
  16139. };
  16140. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16141. for (var p = 0; p < 6; p++) {
  16142. for (var i = 0; i < 8; i++) {
  16143. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16144. return false;
  16145. }
  16146. }
  16147. }
  16148. return true;
  16149. };
  16150. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16151. for (var p = 0; p < 6; p++) {
  16152. var inCount = 8;
  16153. for (var i = 0; i < 8; i++) {
  16154. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16155. --inCount;
  16156. }
  16157. else {
  16158. break;
  16159. }
  16160. }
  16161. if (inCount === 0)
  16162. return false;
  16163. }
  16164. return true;
  16165. };
  16166. return BoundingBox;
  16167. }());
  16168. BABYLON.BoundingBox = BoundingBox;
  16169. })(BABYLON || (BABYLON = {}));
  16170. //# sourceMappingURL=babylon.boundingBox.js.map
  16171. var BABYLON;
  16172. (function (BABYLON) {
  16173. var computeBoxExtents = function (axis, box) {
  16174. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16175. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16176. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16177. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16178. var r = r0 + r1 + r2;
  16179. return {
  16180. min: p - r,
  16181. max: p + r
  16182. };
  16183. };
  16184. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16185. var axisOverlap = function (axis, box0, box1) {
  16186. var result0 = computeBoxExtents(axis, box0);
  16187. var result1 = computeBoxExtents(axis, box1);
  16188. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16189. };
  16190. var BoundingInfo = /** @class */ (function () {
  16191. function BoundingInfo(minimum, maximum) {
  16192. this.minimum = minimum;
  16193. this.maximum = maximum;
  16194. this._isLocked = false;
  16195. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16196. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16197. }
  16198. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16199. get: function () {
  16200. return this._isLocked;
  16201. },
  16202. set: function (value) {
  16203. this._isLocked = value;
  16204. },
  16205. enumerable: true,
  16206. configurable: true
  16207. });
  16208. // Methods
  16209. BoundingInfo.prototype.update = function (world) {
  16210. if (this._isLocked) {
  16211. return;
  16212. }
  16213. this.boundingBox._update(world);
  16214. this.boundingSphere._update(world);
  16215. };
  16216. /**
  16217. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16218. * @param center New center of the bounding info
  16219. * @param extend New extend of the bounding info
  16220. */
  16221. BoundingInfo.prototype.centerOn = function (center, extend) {
  16222. this.minimum = center.subtract(extend);
  16223. this.maximum = center.add(extend);
  16224. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16225. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16226. return this;
  16227. };
  16228. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16229. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16230. return false;
  16231. return this.boundingBox.isInFrustum(frustumPlanes);
  16232. };
  16233. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16234. /**
  16235. * Gets the world distance between the min and max points of the bounding box
  16236. */
  16237. get: function () {
  16238. var boundingBox = this.boundingBox;
  16239. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16240. return size.length();
  16241. },
  16242. enumerable: true,
  16243. configurable: true
  16244. });
  16245. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16246. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16247. };
  16248. BoundingInfo.prototype._checkCollision = function (collider) {
  16249. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16250. };
  16251. BoundingInfo.prototype.intersectsPoint = function (point) {
  16252. if (!this.boundingSphere.centerWorld) {
  16253. return false;
  16254. }
  16255. if (!this.boundingSphere.intersectsPoint(point)) {
  16256. return false;
  16257. }
  16258. if (!this.boundingBox.intersectsPoint(point)) {
  16259. return false;
  16260. }
  16261. return true;
  16262. };
  16263. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16264. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16265. return false;
  16266. }
  16267. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16268. return false;
  16269. }
  16270. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16271. return false;
  16272. }
  16273. if (!precise) {
  16274. return true;
  16275. }
  16276. var box0 = this.boundingBox;
  16277. var box1 = boundingInfo.boundingBox;
  16278. if (!axisOverlap(box0.directions[0], box0, box1))
  16279. return false;
  16280. if (!axisOverlap(box0.directions[1], box0, box1))
  16281. return false;
  16282. if (!axisOverlap(box0.directions[2], box0, box1))
  16283. return false;
  16284. if (!axisOverlap(box1.directions[0], box0, box1))
  16285. return false;
  16286. if (!axisOverlap(box1.directions[1], box0, box1))
  16287. return false;
  16288. if (!axisOverlap(box1.directions[2], box0, box1))
  16289. return false;
  16290. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16291. return false;
  16292. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16293. return false;
  16294. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16295. return false;
  16296. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16297. return false;
  16298. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16299. return false;
  16300. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16301. return false;
  16302. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16303. return false;
  16304. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16305. return false;
  16306. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16307. return false;
  16308. return true;
  16309. };
  16310. return BoundingInfo;
  16311. }());
  16312. BABYLON.BoundingInfo = BoundingInfo;
  16313. })(BABYLON || (BABYLON = {}));
  16314. //# sourceMappingURL=babylon.boundingInfo.js.map
  16315. var BABYLON;
  16316. (function (BABYLON) {
  16317. var TransformNode = /** @class */ (function (_super) {
  16318. __extends(TransformNode, _super);
  16319. function TransformNode(name, scene, isPure) {
  16320. if (scene === void 0) { scene = null; }
  16321. if (isPure === void 0) { isPure = true; }
  16322. var _this = _super.call(this, name, scene) || this;
  16323. // Properties
  16324. _this._rotation = BABYLON.Vector3.Zero();
  16325. _this._scaling = BABYLON.Vector3.One();
  16326. _this._isDirty = false;
  16327. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16328. _this.scalingDeterminant = 1;
  16329. _this.infiniteDistance = false;
  16330. _this.position = BABYLON.Vector3.Zero();
  16331. _this._localWorld = BABYLON.Matrix.Zero();
  16332. _this._worldMatrix = BABYLON.Matrix.Zero();
  16333. _this._worldMatrixDeterminant = 0;
  16334. _this._absolutePosition = BABYLON.Vector3.Zero();
  16335. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16336. _this._postMultiplyPivotMatrix = false;
  16337. _this._isWorldMatrixFrozen = false;
  16338. /**
  16339. * An event triggered after the world matrix is updated
  16340. * @type {BABYLON.Observable}
  16341. */
  16342. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16343. _this._nonUniformScaling = false;
  16344. if (isPure) {
  16345. _this.getScene().addTransformNode(_this);
  16346. }
  16347. return _this;
  16348. }
  16349. Object.defineProperty(TransformNode.prototype, "rotation", {
  16350. /**
  16351. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16352. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16353. * Default : (0.0, 0.0, 0.0)
  16354. */
  16355. get: function () {
  16356. return this._rotation;
  16357. },
  16358. set: function (newRotation) {
  16359. this._rotation = newRotation;
  16360. },
  16361. enumerable: true,
  16362. configurable: true
  16363. });
  16364. Object.defineProperty(TransformNode.prototype, "scaling", {
  16365. /**
  16366. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16367. * Default : (1.0, 1.0, 1.0)
  16368. */
  16369. get: function () {
  16370. return this._scaling;
  16371. },
  16372. /**
  16373. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16374. * Default : (1.0, 1.0, 1.0)
  16375. */
  16376. set: function (newScaling) {
  16377. this._scaling = newScaling;
  16378. },
  16379. enumerable: true,
  16380. configurable: true
  16381. });
  16382. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16383. /**
  16384. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16385. * It's null by default.
  16386. * 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)
  16387. */
  16388. get: function () {
  16389. return this._rotationQuaternion;
  16390. },
  16391. set: function (quaternion) {
  16392. this._rotationQuaternion = quaternion;
  16393. //reset the rotation vector.
  16394. if (quaternion && this.rotation.length()) {
  16395. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16396. }
  16397. },
  16398. enumerable: true,
  16399. configurable: true
  16400. });
  16401. /**
  16402. * Returns the latest update of the World matrix
  16403. * Returns a Matrix.
  16404. */
  16405. TransformNode.prototype.getWorldMatrix = function () {
  16406. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16407. this.computeWorldMatrix();
  16408. }
  16409. return this._worldMatrix;
  16410. };
  16411. /**
  16412. * Returns the latest update of the World matrix determinant.
  16413. */
  16414. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16415. return this._worldMatrixDeterminant;
  16416. };
  16417. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16418. /**
  16419. * Returns directly the latest state of the mesh World matrix.
  16420. * A Matrix is returned.
  16421. */
  16422. get: function () {
  16423. return this._worldMatrix;
  16424. },
  16425. enumerable: true,
  16426. configurable: true
  16427. });
  16428. /**
  16429. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16430. * Returns the AbstractMesh.
  16431. */
  16432. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16433. this._poseMatrix.copyFrom(matrix);
  16434. return this;
  16435. };
  16436. /**
  16437. * Returns the mesh Pose matrix.
  16438. * Returned object : Matrix
  16439. */
  16440. TransformNode.prototype.getPoseMatrix = function () {
  16441. return this._poseMatrix;
  16442. };
  16443. TransformNode.prototype._isSynchronized = function () {
  16444. if (this._isDirty) {
  16445. return false;
  16446. }
  16447. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16448. return false;
  16449. if (this._cache.pivotMatrixUpdated) {
  16450. return false;
  16451. }
  16452. if (this.infiniteDistance) {
  16453. return false;
  16454. }
  16455. if (!this._cache.position.equals(this.position))
  16456. return false;
  16457. if (this.rotationQuaternion) {
  16458. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16459. return false;
  16460. }
  16461. if (!this._cache.rotation.equals(this.rotation))
  16462. return false;
  16463. if (!this._cache.scaling.equals(this.scaling))
  16464. return false;
  16465. return true;
  16466. };
  16467. TransformNode.prototype._initCache = function () {
  16468. _super.prototype._initCache.call(this);
  16469. this._cache.localMatrixUpdated = false;
  16470. this._cache.position = BABYLON.Vector3.Zero();
  16471. this._cache.scaling = BABYLON.Vector3.Zero();
  16472. this._cache.rotation = BABYLON.Vector3.Zero();
  16473. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16474. this._cache.billboardMode = -1;
  16475. };
  16476. TransformNode.prototype.markAsDirty = function (property) {
  16477. if (property === "rotation") {
  16478. this.rotationQuaternion = null;
  16479. }
  16480. this._currentRenderId = Number.MAX_VALUE;
  16481. this._isDirty = true;
  16482. return this;
  16483. };
  16484. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16485. /**
  16486. * Returns the current mesh absolute position.
  16487. * Retuns a Vector3.
  16488. */
  16489. get: function () {
  16490. return this._absolutePosition;
  16491. },
  16492. enumerable: true,
  16493. configurable: true
  16494. });
  16495. /**
  16496. * Sets a new matrix to apply before all other transformation
  16497. * @param matrix defines the transform matrix
  16498. * @returns the current TransformNode
  16499. */
  16500. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16501. return this.setPivotMatrix(matrix, false);
  16502. };
  16503. /**
  16504. * Sets a new pivot matrix to the current node
  16505. * @param matrix defines the new pivot matrix to use
  16506. * @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
  16507. * @returns the current TransformNode
  16508. */
  16509. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16510. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16511. this._pivotMatrix = matrix.clone();
  16512. this._cache.pivotMatrixUpdated = true;
  16513. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16514. if (this._postMultiplyPivotMatrix) {
  16515. if (!this._pivotMatrixInverse) {
  16516. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16517. }
  16518. else {
  16519. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16520. }
  16521. }
  16522. return this;
  16523. };
  16524. /**
  16525. * Returns the mesh pivot matrix.
  16526. * Default : Identity.
  16527. * A Matrix is returned.
  16528. */
  16529. TransformNode.prototype.getPivotMatrix = function () {
  16530. return this._pivotMatrix;
  16531. };
  16532. /**
  16533. * Prevents the World matrix to be computed any longer.
  16534. * Returns the AbstractMesh.
  16535. */
  16536. TransformNode.prototype.freezeWorldMatrix = function () {
  16537. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16538. this.computeWorldMatrix(true);
  16539. this._isWorldMatrixFrozen = true;
  16540. return this;
  16541. };
  16542. /**
  16543. * Allows back the World matrix computation.
  16544. * Returns the AbstractMesh.
  16545. */
  16546. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16547. this._isWorldMatrixFrozen = false;
  16548. this.computeWorldMatrix(true);
  16549. return this;
  16550. };
  16551. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16552. /**
  16553. * True if the World matrix has been frozen.
  16554. * Returns a boolean.
  16555. */
  16556. get: function () {
  16557. return this._isWorldMatrixFrozen;
  16558. },
  16559. enumerable: true,
  16560. configurable: true
  16561. });
  16562. /**
  16563. * Retuns the mesh absolute position in the World.
  16564. * Returns a Vector3.
  16565. */
  16566. TransformNode.prototype.getAbsolutePosition = function () {
  16567. this.computeWorldMatrix();
  16568. return this._absolutePosition;
  16569. };
  16570. /**
  16571. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16572. * Returns the AbstractMesh.
  16573. */
  16574. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16575. if (!absolutePosition) {
  16576. return this;
  16577. }
  16578. var absolutePositionX;
  16579. var absolutePositionY;
  16580. var absolutePositionZ;
  16581. if (absolutePosition.x === undefined) {
  16582. if (arguments.length < 3) {
  16583. return this;
  16584. }
  16585. absolutePositionX = arguments[0];
  16586. absolutePositionY = arguments[1];
  16587. absolutePositionZ = arguments[2];
  16588. }
  16589. else {
  16590. absolutePositionX = absolutePosition.x;
  16591. absolutePositionY = absolutePosition.y;
  16592. absolutePositionZ = absolutePosition.z;
  16593. }
  16594. if (this.parent) {
  16595. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16596. invertParentWorldMatrix.invert();
  16597. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16598. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16599. }
  16600. else {
  16601. this.position.x = absolutePositionX;
  16602. this.position.y = absolutePositionY;
  16603. this.position.z = absolutePositionZ;
  16604. }
  16605. return this;
  16606. };
  16607. /**
  16608. * Sets the mesh position in its local space.
  16609. * Returns the AbstractMesh.
  16610. */
  16611. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16612. this.computeWorldMatrix();
  16613. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16614. return this;
  16615. };
  16616. /**
  16617. * Returns the mesh position in the local space from the current World matrix values.
  16618. * Returns a new Vector3.
  16619. */
  16620. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16621. this.computeWorldMatrix();
  16622. var invLocalWorldMatrix = this._localWorld.clone();
  16623. invLocalWorldMatrix.invert();
  16624. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16625. };
  16626. /**
  16627. * Translates the mesh along the passed Vector3 in its local space.
  16628. * Returns the AbstractMesh.
  16629. */
  16630. TransformNode.prototype.locallyTranslate = function (vector3) {
  16631. this.computeWorldMatrix(true);
  16632. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16633. return this;
  16634. };
  16635. /**
  16636. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16637. * @param targetPoint the position (must be in same space as current mesh) to look at
  16638. * @param yawCor optional yaw (y-axis) correction in radians
  16639. * @param pitchCor optional pitch (x-axis) correction in radians
  16640. * @param rollCor optional roll (z-axis) correction in radians
  16641. * @param space the choosen space of the target
  16642. * @returns the TransformNode.
  16643. */
  16644. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16645. if (yawCor === void 0) { yawCor = 0; }
  16646. if (pitchCor === void 0) { pitchCor = 0; }
  16647. if (rollCor === void 0) { rollCor = 0; }
  16648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16649. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16650. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16651. targetPoint.subtractToRef(pos, dv);
  16652. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16653. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16654. var pitch = Math.atan2(dv.y, len);
  16655. if (this.rotationQuaternion) {
  16656. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16657. }
  16658. else {
  16659. this.rotation.x = pitch + pitchCor;
  16660. this.rotation.y = yaw + yawCor;
  16661. this.rotation.z = rollCor;
  16662. }
  16663. return this;
  16664. };
  16665. /**
  16666. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16667. * This Vector3 is expressed in the World space.
  16668. */
  16669. TransformNode.prototype.getDirection = function (localAxis) {
  16670. var result = BABYLON.Vector3.Zero();
  16671. this.getDirectionToRef(localAxis, result);
  16672. return result;
  16673. };
  16674. /**
  16675. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16676. * localAxis is expressed in the mesh local space.
  16677. * result is computed in the Wordl space from the mesh World matrix.
  16678. * Returns the AbstractMesh.
  16679. */
  16680. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16681. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16682. return this;
  16683. };
  16684. /**
  16685. * Sets a new pivot point to the current node
  16686. * @param point defines the new pivot point to use
  16687. * @param space defines if the point is in world or local space (local by default)
  16688. * @returns the current TransformNode
  16689. */
  16690. TransformNode.prototype.setPivotPoint = function (point, space) {
  16691. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16692. if (this.getScene().getRenderId() == 0) {
  16693. this.computeWorldMatrix(true);
  16694. }
  16695. var wm = this.getWorldMatrix();
  16696. if (space == BABYLON.Space.WORLD) {
  16697. var tmat = BABYLON.Tmp.Matrix[0];
  16698. wm.invertToRef(tmat);
  16699. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16700. }
  16701. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16702. };
  16703. /**
  16704. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16705. */
  16706. TransformNode.prototype.getPivotPoint = function () {
  16707. var point = BABYLON.Vector3.Zero();
  16708. this.getPivotPointToRef(point);
  16709. return point;
  16710. };
  16711. /**
  16712. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16713. * Returns the AbstractMesh.
  16714. */
  16715. TransformNode.prototype.getPivotPointToRef = function (result) {
  16716. result.x = -this._pivotMatrix.m[12];
  16717. result.y = -this._pivotMatrix.m[13];
  16718. result.z = -this._pivotMatrix.m[14];
  16719. return this;
  16720. };
  16721. /**
  16722. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16723. */
  16724. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16725. var point = BABYLON.Vector3.Zero();
  16726. this.getAbsolutePivotPointToRef(point);
  16727. return point;
  16728. };
  16729. /**
  16730. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16731. * Returns the AbstractMesh.
  16732. */
  16733. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16734. result.x = this._pivotMatrix.m[12];
  16735. result.y = this._pivotMatrix.m[13];
  16736. result.z = this._pivotMatrix.m[14];
  16737. this.getPivotPointToRef(result);
  16738. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16739. return this;
  16740. };
  16741. /**
  16742. * Defines the passed node as the parent of the current node.
  16743. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16744. * Returns the TransformNode.
  16745. */
  16746. TransformNode.prototype.setParent = function (node) {
  16747. if (node === null) {
  16748. var rotation = BABYLON.Tmp.Quaternion[0];
  16749. var position = BABYLON.Tmp.Vector3[0];
  16750. var scale = BABYLON.Tmp.Vector3[1];
  16751. if (this.parent && this.parent.computeWorldMatrix) {
  16752. this.parent.computeWorldMatrix(true);
  16753. }
  16754. this.computeWorldMatrix(true);
  16755. this.getWorldMatrix().decompose(scale, rotation, position);
  16756. if (this.rotationQuaternion) {
  16757. this.rotationQuaternion.copyFrom(rotation);
  16758. }
  16759. else {
  16760. rotation.toEulerAnglesToRef(this.rotation);
  16761. }
  16762. this.scaling.x = scale.x;
  16763. this.scaling.y = scale.y;
  16764. this.scaling.z = scale.z;
  16765. this.position.x = position.x;
  16766. this.position.y = position.y;
  16767. this.position.z = position.z;
  16768. }
  16769. else {
  16770. var rotation = BABYLON.Tmp.Quaternion[0];
  16771. var position = BABYLON.Tmp.Vector3[0];
  16772. var scale = BABYLON.Tmp.Vector3[1];
  16773. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16774. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16775. this.computeWorldMatrix(true);
  16776. node.computeWorldMatrix(true);
  16777. node.getWorldMatrix().invertToRef(invParentMatrix);
  16778. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16779. diffMatrix.decompose(scale, rotation, position);
  16780. if (this.rotationQuaternion) {
  16781. this.rotationQuaternion.copyFrom(rotation);
  16782. }
  16783. else {
  16784. rotation.toEulerAnglesToRef(this.rotation);
  16785. }
  16786. this.position.x = position.x;
  16787. this.position.y = position.y;
  16788. this.position.z = position.z;
  16789. this.scaling.x = scale.x;
  16790. this.scaling.y = scale.y;
  16791. this.scaling.z = scale.z;
  16792. }
  16793. this.parent = node;
  16794. return this;
  16795. };
  16796. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16797. get: function () {
  16798. return this._nonUniformScaling;
  16799. },
  16800. enumerable: true,
  16801. configurable: true
  16802. });
  16803. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16804. if (this._nonUniformScaling === value) {
  16805. return false;
  16806. }
  16807. this._nonUniformScaling = true;
  16808. return true;
  16809. };
  16810. /**
  16811. * Attach the current TransformNode to another TransformNode associated with a bone
  16812. * @param bone Bone affecting the TransformNode
  16813. * @param affectedTransformNode TransformNode associated with the bone
  16814. */
  16815. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16816. this._transformToBoneReferal = affectedTransformNode;
  16817. this.parent = bone;
  16818. if (bone.getWorldMatrix().determinant() < 0) {
  16819. this.scalingDeterminant *= -1;
  16820. }
  16821. return this;
  16822. };
  16823. TransformNode.prototype.detachFromBone = function () {
  16824. if (!this.parent) {
  16825. return this;
  16826. }
  16827. if (this.parent.getWorldMatrix().determinant() < 0) {
  16828. this.scalingDeterminant *= -1;
  16829. }
  16830. this._transformToBoneReferal = null;
  16831. this.parent = null;
  16832. return this;
  16833. };
  16834. /**
  16835. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16836. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16837. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16838. * The passed axis is also normalized.
  16839. * Returns the AbstractMesh.
  16840. */
  16841. TransformNode.prototype.rotate = function (axis, amount, space) {
  16842. axis.normalize();
  16843. if (!this.rotationQuaternion) {
  16844. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16845. this.rotation = BABYLON.Vector3.Zero();
  16846. }
  16847. var rotationQuaternion;
  16848. if (!space || space === BABYLON.Space.LOCAL) {
  16849. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16850. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16851. }
  16852. else {
  16853. if (this.parent) {
  16854. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16855. invertParentWorldMatrix.invert();
  16856. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16857. }
  16858. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16859. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16860. }
  16861. return this;
  16862. };
  16863. /**
  16864. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16865. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16866. * The passed axis is also normalized.
  16867. * Returns the AbstractMesh.
  16868. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16869. */
  16870. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16871. axis.normalize();
  16872. if (!this.rotationQuaternion) {
  16873. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16874. this.rotation.copyFromFloats(0, 0, 0);
  16875. }
  16876. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16877. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16878. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16879. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16880. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16881. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16882. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16883. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16884. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16885. return this;
  16886. };
  16887. /**
  16888. * Translates the mesh along the axis vector for the passed distance in the given space.
  16889. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16890. * Returns the AbstractMesh.
  16891. */
  16892. TransformNode.prototype.translate = function (axis, distance, space) {
  16893. var displacementVector = axis.scale(distance);
  16894. if (!space || space === BABYLON.Space.LOCAL) {
  16895. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16896. this.setPositionWithLocalVector(tempV3);
  16897. }
  16898. else {
  16899. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16900. }
  16901. return this;
  16902. };
  16903. /**
  16904. * Adds a rotation step to the mesh current rotation.
  16905. * x, y, z are Euler angles expressed in radians.
  16906. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16907. * This means this rotation is made in the mesh local space only.
  16908. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16909. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16910. * ```javascript
  16911. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16912. * ```
  16913. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16914. * 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.
  16915. * Returns the AbstractMesh.
  16916. */
  16917. TransformNode.prototype.addRotation = function (x, y, z) {
  16918. var rotationQuaternion;
  16919. if (this.rotationQuaternion) {
  16920. rotationQuaternion = this.rotationQuaternion;
  16921. }
  16922. else {
  16923. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16924. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16925. }
  16926. var accumulation = BABYLON.Tmp.Quaternion[0];
  16927. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16928. rotationQuaternion.multiplyInPlace(accumulation);
  16929. if (!this.rotationQuaternion) {
  16930. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16931. }
  16932. return this;
  16933. };
  16934. /**
  16935. * Computes the mesh World matrix and returns it.
  16936. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16937. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16938. * If the parameter `force`is set to `true`, the actual computation is done.
  16939. * Returns the mesh World Matrix.
  16940. */
  16941. TransformNode.prototype.computeWorldMatrix = function (force) {
  16942. if (this._isWorldMatrixFrozen) {
  16943. return this._worldMatrix;
  16944. }
  16945. if (!force && this.isSynchronized(true)) {
  16946. return this._worldMatrix;
  16947. }
  16948. this._cache.position.copyFrom(this.position);
  16949. this._cache.scaling.copyFrom(this.scaling);
  16950. this._cache.pivotMatrixUpdated = false;
  16951. this._cache.billboardMode = this.billboardMode;
  16952. this._currentRenderId = this.getScene().getRenderId();
  16953. this._isDirty = false;
  16954. // Scaling
  16955. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16956. // Rotation
  16957. //rotate, if quaternion is set and rotation was used
  16958. if (this.rotationQuaternion) {
  16959. var len = this.rotation.length();
  16960. if (len) {
  16961. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16962. this.rotation.copyFromFloats(0, 0, 0);
  16963. }
  16964. }
  16965. if (this.rotationQuaternion) {
  16966. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16967. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16968. }
  16969. else {
  16970. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16971. this._cache.rotation.copyFrom(this.rotation);
  16972. }
  16973. // Translation
  16974. var camera = this.getScene().activeCamera;
  16975. if (this.infiniteDistance && !this.parent && camera) {
  16976. var cameraWorldMatrix = camera.getWorldMatrix();
  16977. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16978. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16979. }
  16980. else {
  16981. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16982. }
  16983. // Composing transformations
  16984. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16985. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16986. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16987. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16988. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16989. // Need to decompose each rotation here
  16990. var currentPosition = BABYLON.Tmp.Vector3[3];
  16991. if (this.parent && this.parent.getWorldMatrix) {
  16992. if (this._transformToBoneReferal) {
  16993. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16994. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16995. }
  16996. else {
  16997. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16998. }
  16999. }
  17000. else {
  17001. currentPosition.copyFrom(this.position);
  17002. }
  17003. currentPosition.subtractInPlace(camera.globalPosition);
  17004. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17005. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17006. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17007. }
  17008. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17009. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17010. }
  17011. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17012. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17013. }
  17014. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17015. }
  17016. else {
  17017. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17018. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17019. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17020. }
  17021. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17022. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17023. }
  17024. // Local world
  17025. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17026. // Parent
  17027. if (this.parent && this.parent.getWorldMatrix) {
  17028. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17029. if (this._transformToBoneReferal) {
  17030. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17031. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17032. }
  17033. else {
  17034. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17035. }
  17036. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17037. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17038. this._worldMatrix.copyFrom(this._localWorld);
  17039. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17040. }
  17041. else {
  17042. if (this._transformToBoneReferal) {
  17043. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17044. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17045. }
  17046. else {
  17047. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17048. }
  17049. }
  17050. this._markSyncedWithParent();
  17051. }
  17052. else {
  17053. this._worldMatrix.copyFrom(this._localWorld);
  17054. }
  17055. // Post multiply inverse of pivotMatrix
  17056. if (this._postMultiplyPivotMatrix) {
  17057. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17058. }
  17059. // Normal matrix
  17060. if (this.scaling.isNonUniform) {
  17061. this._updateNonUniformScalingState(true);
  17062. }
  17063. else if (this.parent && this.parent._nonUniformScaling) {
  17064. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17065. }
  17066. else {
  17067. this._updateNonUniformScalingState(false);
  17068. }
  17069. this._afterComputeWorldMatrix();
  17070. // Absolute position
  17071. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17072. // Callbacks
  17073. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17074. if (!this._poseMatrix) {
  17075. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17076. }
  17077. // Cache the determinant
  17078. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17079. return this._worldMatrix;
  17080. };
  17081. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17082. };
  17083. /**
  17084. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17085. * @param func: callback function to add
  17086. *
  17087. * Returns the TransformNode.
  17088. */
  17089. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17090. this.onAfterWorldMatrixUpdateObservable.add(func);
  17091. return this;
  17092. };
  17093. /**
  17094. * Removes a registered callback function.
  17095. * Returns the TransformNode.
  17096. */
  17097. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17098. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17099. return this;
  17100. };
  17101. /**
  17102. * Clone the current transform node
  17103. * Returns the new transform node
  17104. * @param name Name of the new clone
  17105. * @param newParent New parent for the clone
  17106. * @param doNotCloneChildren Do not clone children hierarchy
  17107. */
  17108. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17109. var _this = this;
  17110. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17111. result.name = name;
  17112. result.id = name;
  17113. if (newParent) {
  17114. result.parent = newParent;
  17115. }
  17116. if (!doNotCloneChildren) {
  17117. // Children
  17118. var directDescendants = this.getDescendants(true);
  17119. for (var index = 0; index < directDescendants.length; index++) {
  17120. var child = directDescendants[index];
  17121. if (child.clone) {
  17122. child.clone(name + "." + child.name, result);
  17123. }
  17124. }
  17125. }
  17126. return result;
  17127. };
  17128. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17129. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17130. serializationObject.type = this.getClassName();
  17131. // Parent
  17132. if (this.parent) {
  17133. serializationObject.parentId = this.parent.id;
  17134. }
  17135. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17136. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17137. }
  17138. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17139. serializationObject.isEnabled = this.isEnabled();
  17140. // Parent
  17141. if (this.parent) {
  17142. serializationObject.parentId = this.parent.id;
  17143. }
  17144. return serializationObject;
  17145. };
  17146. // Statics
  17147. /**
  17148. * Returns a new TransformNode object parsed from the source provided.
  17149. * The parameter `parsedMesh` is the source.
  17150. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17151. */
  17152. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17153. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17154. if (BABYLON.Tags) {
  17155. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17156. }
  17157. if (parsedTransformNode.localMatrix) {
  17158. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17159. }
  17160. else if (parsedTransformNode.pivotMatrix) {
  17161. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17162. }
  17163. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17164. // Parent
  17165. if (parsedTransformNode.parentId) {
  17166. transformNode._waitingParentId = parsedTransformNode.parentId;
  17167. }
  17168. return transformNode;
  17169. };
  17170. /**
  17171. * Disposes the TransformNode.
  17172. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17173. * Returns nothing.
  17174. */
  17175. TransformNode.prototype.dispose = function (doNotRecurse) {
  17176. // Animations
  17177. this.getScene().stopAnimation(this);
  17178. // Remove from scene
  17179. this.getScene().removeTransformNode(this);
  17180. if (!doNotRecurse) {
  17181. // Children
  17182. var objects = this.getDescendants(true);
  17183. for (var index = 0; index < objects.length; index++) {
  17184. objects[index].dispose();
  17185. }
  17186. }
  17187. else {
  17188. var childMeshes = this.getChildMeshes(true);
  17189. for (index = 0; index < childMeshes.length; index++) {
  17190. var child = childMeshes[index];
  17191. child.parent = null;
  17192. child.computeWorldMatrix(true);
  17193. }
  17194. }
  17195. this.onAfterWorldMatrixUpdateObservable.clear();
  17196. _super.prototype.dispose.call(this);
  17197. };
  17198. // Statics
  17199. TransformNode.BILLBOARDMODE_NONE = 0;
  17200. TransformNode.BILLBOARDMODE_X = 1;
  17201. TransformNode.BILLBOARDMODE_Y = 2;
  17202. TransformNode.BILLBOARDMODE_Z = 4;
  17203. TransformNode.BILLBOARDMODE_ALL = 7;
  17204. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17205. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17206. __decorate([
  17207. BABYLON.serializeAsVector3()
  17208. ], TransformNode.prototype, "_rotation", void 0);
  17209. __decorate([
  17210. BABYLON.serializeAsQuaternion()
  17211. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17212. __decorate([
  17213. BABYLON.serializeAsVector3()
  17214. ], TransformNode.prototype, "_scaling", void 0);
  17215. __decorate([
  17216. BABYLON.serialize()
  17217. ], TransformNode.prototype, "billboardMode", void 0);
  17218. __decorate([
  17219. BABYLON.serialize()
  17220. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17221. __decorate([
  17222. BABYLON.serialize()
  17223. ], TransformNode.prototype, "infiniteDistance", void 0);
  17224. __decorate([
  17225. BABYLON.serializeAsVector3()
  17226. ], TransformNode.prototype, "position", void 0);
  17227. return TransformNode;
  17228. }(BABYLON.Node));
  17229. BABYLON.TransformNode = TransformNode;
  17230. })(BABYLON || (BABYLON = {}));
  17231. //# sourceMappingURL=babylon.transformNode.js.map
  17232. var BABYLON;
  17233. (function (BABYLON) {
  17234. var AbstractMesh = /** @class */ (function (_super) {
  17235. __extends(AbstractMesh, _super);
  17236. // Constructor
  17237. function AbstractMesh(name, scene) {
  17238. if (scene === void 0) { scene = null; }
  17239. var _this = _super.call(this, name, scene, false) || this;
  17240. _this._facetNb = 0; // facet number
  17241. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17242. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17243. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17244. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17245. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17246. _this._subDiv = {
  17247. max: 1,
  17248. X: 1,
  17249. Y: 1,
  17250. Z: 1
  17251. };
  17252. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17253. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17254. // Events
  17255. /**
  17256. * An event triggered when this mesh collides with another one
  17257. * @type {BABYLON.Observable}
  17258. */
  17259. _this.onCollideObservable = new BABYLON.Observable();
  17260. /**
  17261. * An event triggered when the collision's position changes
  17262. * @type {BABYLON.Observable}
  17263. */
  17264. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17265. /**
  17266. * An event triggered when material is changed
  17267. * @type {BABYLON.Observable}
  17268. */
  17269. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17270. // Properties
  17271. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17272. /**
  17273. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17274. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17275. * or
  17276. * 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.
  17277. * for more info check WebGl documentations
  17278. */
  17279. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17280. /**
  17281. * 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:
  17282. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17283. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17284. * 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.
  17285. */
  17286. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17287. /**
  17288. * 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.
  17289. * The default value is -1 which means don't break the query and wait till the result.
  17290. */
  17291. _this.occlusionRetryCount = -1;
  17292. _this._occlusionInternalRetryCounter = 0;
  17293. _this._isOccluded = false;
  17294. _this._isOcclusionQueryInProgress = false;
  17295. _this._visibility = 1.0;
  17296. _this.alphaIndex = Number.MAX_VALUE;
  17297. _this.isVisible = true;
  17298. _this.isPickable = true;
  17299. _this.showBoundingBox = false;
  17300. _this.showSubMeshesBoundingBox = false;
  17301. _this.isBlocker = false;
  17302. _this.enablePointerMoveEvents = false;
  17303. _this.renderingGroupId = 0;
  17304. _this._receiveShadows = false;
  17305. _this.renderOutline = false;
  17306. _this.outlineColor = BABYLON.Color3.Red();
  17307. _this.outlineWidth = 0.02;
  17308. _this.renderOverlay = false;
  17309. _this.overlayColor = BABYLON.Color3.Red();
  17310. _this.overlayAlpha = 0.5;
  17311. _this._hasVertexAlpha = false;
  17312. _this._useVertexColors = true;
  17313. _this._computeBonesUsingShaders = true;
  17314. _this._numBoneInfluencers = 4;
  17315. _this._applyFog = true;
  17316. _this.useOctreeForRenderingSelection = true;
  17317. _this.useOctreeForPicking = true;
  17318. _this.useOctreeForCollisions = true;
  17319. _this._layerMask = 0x0FFFFFFF;
  17320. /**
  17321. * True if the mesh must be rendered in any case.
  17322. */
  17323. _this.alwaysSelectAsActiveMesh = false;
  17324. /**
  17325. * This scene's action manager
  17326. * @type {BABYLON.ActionManager}
  17327. */
  17328. _this.actionManager = null;
  17329. // Physics
  17330. _this.physicsImpostor = null;
  17331. // Collisions
  17332. _this._checkCollisions = false;
  17333. _this._collisionMask = -1;
  17334. _this._collisionGroup = -1;
  17335. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17336. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17337. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17338. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17339. // Edges
  17340. _this.edgesWidth = 1;
  17341. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17342. // Cache
  17343. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17344. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17345. _this._renderId = 0;
  17346. _this._intersectionsInProgress = new Array();
  17347. _this._unIndexed = false;
  17348. _this._lightSources = new Array();
  17349. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17350. if (collidedMesh === void 0) { collidedMesh = null; }
  17351. //TODO move this to the collision coordinator!
  17352. if (_this.getScene().workerCollisions)
  17353. newPosition.multiplyInPlace(_this._collider._radius);
  17354. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17355. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17356. _this.position.addInPlace(_this._diffPositionForCollisions);
  17357. }
  17358. if (collidedMesh) {
  17359. _this.onCollideObservable.notifyObservers(collidedMesh);
  17360. }
  17361. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17362. };
  17363. _this.getScene().addMesh(_this);
  17364. _this._resyncLightSources();
  17365. return _this;
  17366. }
  17367. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17368. get: function () {
  17369. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17370. },
  17371. enumerable: true,
  17372. configurable: true
  17373. });
  17374. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17375. get: function () {
  17376. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17377. },
  17378. enumerable: true,
  17379. configurable: true
  17380. });
  17381. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17382. get: function () {
  17383. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17384. },
  17385. enumerable: true,
  17386. configurable: true
  17387. });
  17388. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17389. get: function () {
  17390. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17391. },
  17392. enumerable: true,
  17393. configurable: true
  17394. });
  17395. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17396. get: function () {
  17397. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17398. },
  17399. enumerable: true,
  17400. configurable: true
  17401. });
  17402. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17403. /**
  17404. * Read-only : the number of facets in the mesh
  17405. */
  17406. get: function () {
  17407. return this._facetNb;
  17408. },
  17409. enumerable: true,
  17410. configurable: true
  17411. });
  17412. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17413. /**
  17414. * The number (integer) of subdivisions per axis in the partioning space
  17415. */
  17416. get: function () {
  17417. return this._partitioningSubdivisions;
  17418. },
  17419. set: function (nb) {
  17420. this._partitioningSubdivisions = nb;
  17421. },
  17422. enumerable: true,
  17423. configurable: true
  17424. });
  17425. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17426. /**
  17427. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17428. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17429. */
  17430. get: function () {
  17431. return this._partitioningBBoxRatio;
  17432. },
  17433. set: function (ratio) {
  17434. this._partitioningBBoxRatio = ratio;
  17435. },
  17436. enumerable: true,
  17437. configurable: true
  17438. });
  17439. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17440. /**
  17441. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17442. * Works only for updatable meshes.
  17443. * Doesn't work with multi-materials.
  17444. */
  17445. get: function () {
  17446. return this._facetDepthSort;
  17447. },
  17448. set: function (sort) {
  17449. this._facetDepthSort = sort;
  17450. },
  17451. enumerable: true,
  17452. configurable: true
  17453. });
  17454. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17455. /**
  17456. * The location (Vector3) where the facet depth sort must be computed from.
  17457. * By default, the active camera position.
  17458. * Used only when facet depth sort is enabled.
  17459. */
  17460. get: function () {
  17461. return this._facetDepthSortFrom;
  17462. },
  17463. set: function (location) {
  17464. this._facetDepthSortFrom = location;
  17465. },
  17466. enumerable: true,
  17467. configurable: true
  17468. });
  17469. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17470. /**
  17471. * Read-only boolean : is the feature facetData enabled ?
  17472. */
  17473. get: function () {
  17474. return this._facetDataEnabled;
  17475. },
  17476. enumerable: true,
  17477. configurable: true
  17478. });
  17479. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17480. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17481. return false;
  17482. }
  17483. this._markSubMeshesAsMiscDirty();
  17484. return true;
  17485. };
  17486. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17487. set: function (callback) {
  17488. if (this._onCollideObserver) {
  17489. this.onCollideObservable.remove(this._onCollideObserver);
  17490. }
  17491. this._onCollideObserver = this.onCollideObservable.add(callback);
  17492. },
  17493. enumerable: true,
  17494. configurable: true
  17495. });
  17496. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17497. set: function (callback) {
  17498. if (this._onCollisionPositionChangeObserver) {
  17499. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17500. }
  17501. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17502. },
  17503. enumerable: true,
  17504. configurable: true
  17505. });
  17506. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17507. /**
  17508. * 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.
  17509. */
  17510. get: function () {
  17511. return this._isOccluded;
  17512. },
  17513. set: function (value) {
  17514. this._isOccluded = value;
  17515. },
  17516. enumerable: true,
  17517. configurable: true
  17518. });
  17519. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17520. /**
  17521. * Flag to check the progress status of the query
  17522. */
  17523. get: function () {
  17524. return this._isOcclusionQueryInProgress;
  17525. },
  17526. enumerable: true,
  17527. configurable: true
  17528. });
  17529. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17530. /**
  17531. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17532. */
  17533. get: function () {
  17534. return this._visibility;
  17535. },
  17536. /**
  17537. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17538. */
  17539. set: function (value) {
  17540. if (this._visibility === value) {
  17541. return;
  17542. }
  17543. this._visibility = value;
  17544. this._markSubMeshesAsMiscDirty();
  17545. },
  17546. enumerable: true,
  17547. configurable: true
  17548. });
  17549. Object.defineProperty(AbstractMesh.prototype, "material", {
  17550. get: function () {
  17551. return this._material;
  17552. },
  17553. set: function (value) {
  17554. if (this._material === value) {
  17555. return;
  17556. }
  17557. this._material = value;
  17558. if (this.onMaterialChangedObservable.hasObservers) {
  17559. this.onMaterialChangedObservable.notifyObservers(this);
  17560. }
  17561. if (!this.subMeshes) {
  17562. return;
  17563. }
  17564. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17565. var subMesh = _a[_i];
  17566. subMesh.setEffect(null);
  17567. }
  17568. },
  17569. enumerable: true,
  17570. configurable: true
  17571. });
  17572. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17573. get: function () {
  17574. return this._receiveShadows;
  17575. },
  17576. set: function (value) {
  17577. if (this._receiveShadows === value) {
  17578. return;
  17579. }
  17580. this._receiveShadows = value;
  17581. this._markSubMeshesAsLightDirty();
  17582. },
  17583. enumerable: true,
  17584. configurable: true
  17585. });
  17586. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17587. get: function () {
  17588. return this._hasVertexAlpha;
  17589. },
  17590. set: function (value) {
  17591. if (this._hasVertexAlpha === value) {
  17592. return;
  17593. }
  17594. this._hasVertexAlpha = value;
  17595. this._markSubMeshesAsAttributesDirty();
  17596. this._markSubMeshesAsMiscDirty();
  17597. },
  17598. enumerable: true,
  17599. configurable: true
  17600. });
  17601. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17602. get: function () {
  17603. return this._useVertexColors;
  17604. },
  17605. set: function (value) {
  17606. if (this._useVertexColors === value) {
  17607. return;
  17608. }
  17609. this._useVertexColors = value;
  17610. this._markSubMeshesAsAttributesDirty();
  17611. },
  17612. enumerable: true,
  17613. configurable: true
  17614. });
  17615. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17616. get: function () {
  17617. return this._computeBonesUsingShaders;
  17618. },
  17619. set: function (value) {
  17620. if (this._computeBonesUsingShaders === value) {
  17621. return;
  17622. }
  17623. this._computeBonesUsingShaders = value;
  17624. this._markSubMeshesAsAttributesDirty();
  17625. },
  17626. enumerable: true,
  17627. configurable: true
  17628. });
  17629. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17630. get: function () {
  17631. return this._numBoneInfluencers;
  17632. },
  17633. set: function (value) {
  17634. if (this._numBoneInfluencers === value) {
  17635. return;
  17636. }
  17637. this._numBoneInfluencers = value;
  17638. this._markSubMeshesAsAttributesDirty();
  17639. },
  17640. enumerable: true,
  17641. configurable: true
  17642. });
  17643. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17644. get: function () {
  17645. return this._applyFog;
  17646. },
  17647. set: function (value) {
  17648. if (this._applyFog === value) {
  17649. return;
  17650. }
  17651. this._applyFog = value;
  17652. this._markSubMeshesAsMiscDirty();
  17653. },
  17654. enumerable: true,
  17655. configurable: true
  17656. });
  17657. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17658. get: function () {
  17659. return this._layerMask;
  17660. },
  17661. set: function (value) {
  17662. if (value === this._layerMask) {
  17663. return;
  17664. }
  17665. this._layerMask = value;
  17666. this._resyncLightSources();
  17667. },
  17668. enumerable: true,
  17669. configurable: true
  17670. });
  17671. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17672. get: function () {
  17673. return this._collisionMask;
  17674. },
  17675. set: function (mask) {
  17676. this._collisionMask = !isNaN(mask) ? mask : -1;
  17677. },
  17678. enumerable: true,
  17679. configurable: true
  17680. });
  17681. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17682. get: function () {
  17683. return this._collisionGroup;
  17684. },
  17685. set: function (mask) {
  17686. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17687. },
  17688. enumerable: true,
  17689. configurable: true
  17690. });
  17691. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17692. get: function () {
  17693. return null;
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17699. get: function () {
  17700. return this._skeleton;
  17701. },
  17702. set: function (value) {
  17703. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17704. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17705. }
  17706. if (value && value.needInitialSkinMatrix) {
  17707. value._registerMeshWithPoseMatrix(this);
  17708. }
  17709. this._skeleton = value;
  17710. if (!this._skeleton) {
  17711. this._bonesTransformMatrices = null;
  17712. }
  17713. this._markSubMeshesAsAttributesDirty();
  17714. },
  17715. enumerable: true,
  17716. configurable: true
  17717. });
  17718. /**
  17719. * Returns the string "AbstractMesh"
  17720. */
  17721. AbstractMesh.prototype.getClassName = function () {
  17722. return "AbstractMesh";
  17723. };
  17724. /**
  17725. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17726. */
  17727. AbstractMesh.prototype.toString = function (fullDetails) {
  17728. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17729. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17730. if (this._skeleton) {
  17731. ret += ", skeleton: " + this._skeleton.name;
  17732. }
  17733. if (fullDetails) {
  17734. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17735. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17736. }
  17737. return ret;
  17738. };
  17739. AbstractMesh.prototype._rebuild = function () {
  17740. if (this._occlusionQuery) {
  17741. this._occlusionQuery = null;
  17742. }
  17743. if (this._edgesRenderer) {
  17744. this._edgesRenderer._rebuild();
  17745. }
  17746. if (!this.subMeshes) {
  17747. return;
  17748. }
  17749. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17750. var subMesh = _a[_i];
  17751. subMesh._rebuild();
  17752. }
  17753. };
  17754. AbstractMesh.prototype._resyncLightSources = function () {
  17755. this._lightSources.length = 0;
  17756. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17757. var light = _a[_i];
  17758. if (!light.isEnabled()) {
  17759. continue;
  17760. }
  17761. if (light.canAffectMesh(this)) {
  17762. this._lightSources.push(light);
  17763. }
  17764. }
  17765. this._markSubMeshesAsLightDirty();
  17766. };
  17767. AbstractMesh.prototype._resyncLighSource = function (light) {
  17768. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17769. var index = this._lightSources.indexOf(light);
  17770. if (index === -1) {
  17771. if (!isIn) {
  17772. return;
  17773. }
  17774. this._lightSources.push(light);
  17775. }
  17776. else {
  17777. if (isIn) {
  17778. return;
  17779. }
  17780. this._lightSources.splice(index, 1);
  17781. }
  17782. this._markSubMeshesAsLightDirty();
  17783. };
  17784. AbstractMesh.prototype._removeLightSource = function (light) {
  17785. var index = this._lightSources.indexOf(light);
  17786. if (index === -1) {
  17787. return;
  17788. }
  17789. this._lightSources.splice(index, 1);
  17790. this._markSubMeshesAsLightDirty();
  17791. };
  17792. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17793. if (!this.subMeshes) {
  17794. return;
  17795. }
  17796. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17797. var subMesh = _a[_i];
  17798. if (subMesh._materialDefines) {
  17799. func(subMesh._materialDefines);
  17800. }
  17801. }
  17802. };
  17803. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17804. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17805. };
  17806. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17807. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17808. };
  17809. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17810. if (!this.subMeshes) {
  17811. return;
  17812. }
  17813. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17814. var subMesh = _a[_i];
  17815. var material = subMesh.getMaterial();
  17816. if (material) {
  17817. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17818. }
  17819. }
  17820. };
  17821. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17822. /**
  17823. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17824. * Default : (1.0, 1.0, 1.0)
  17825. */
  17826. get: function () {
  17827. return this._scaling;
  17828. },
  17829. /**
  17830. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17831. * Default : (1.0, 1.0, 1.0)
  17832. */
  17833. set: function (newScaling) {
  17834. this._scaling = newScaling;
  17835. if (this.physicsImpostor) {
  17836. this.physicsImpostor.forceUpdate();
  17837. }
  17838. },
  17839. enumerable: true,
  17840. configurable: true
  17841. });
  17842. // Methods
  17843. /**
  17844. * Disables the mesh edger rendering mode.
  17845. * Returns the AbstractMesh.
  17846. */
  17847. AbstractMesh.prototype.disableEdgesRendering = function () {
  17848. if (this._edgesRenderer) {
  17849. this._edgesRenderer.dispose();
  17850. this._edgesRenderer = null;
  17851. }
  17852. return this;
  17853. };
  17854. /**
  17855. * Enables the edge rendering mode on the mesh.
  17856. * This mode makes the mesh edges visible.
  17857. * Returns the AbstractMesh.
  17858. */
  17859. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17860. if (epsilon === void 0) { epsilon = 0.95; }
  17861. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17862. this.disableEdgesRendering();
  17863. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17864. return this;
  17865. };
  17866. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17867. /**
  17868. * Returns true if the mesh is blocked. Used by the class Mesh.
  17869. * Returns the boolean `false` by default.
  17870. */
  17871. get: function () {
  17872. return false;
  17873. },
  17874. enumerable: true,
  17875. configurable: true
  17876. });
  17877. /**
  17878. * Returns the mesh itself by default, used by the class Mesh.
  17879. * Returned type : AbstractMesh
  17880. */
  17881. AbstractMesh.prototype.getLOD = function (camera) {
  17882. return this;
  17883. };
  17884. /**
  17885. * Returns 0 by default, used by the class Mesh.
  17886. * Returns an integer.
  17887. */
  17888. AbstractMesh.prototype.getTotalVertices = function () {
  17889. return 0;
  17890. };
  17891. /**
  17892. * Returns null by default, used by the class Mesh.
  17893. * Returned type : integer array
  17894. */
  17895. AbstractMesh.prototype.getIndices = function () {
  17896. return null;
  17897. };
  17898. /**
  17899. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17900. * Returned type : float array or Float32Array
  17901. */
  17902. AbstractMesh.prototype.getVerticesData = function (kind) {
  17903. return null;
  17904. };
  17905. /**
  17906. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17907. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17908. * The `data` are either a numeric array either a Float32Array.
  17909. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17910. * 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).
  17911. * Note that a new underlying VertexBuffer object is created each call.
  17912. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17913. *
  17914. * Possible `kind` values :
  17915. * - BABYLON.VertexBuffer.PositionKind
  17916. * - BABYLON.VertexBuffer.UVKind
  17917. * - BABYLON.VertexBuffer.UV2Kind
  17918. * - BABYLON.VertexBuffer.UV3Kind
  17919. * - BABYLON.VertexBuffer.UV4Kind
  17920. * - BABYLON.VertexBuffer.UV5Kind
  17921. * - BABYLON.VertexBuffer.UV6Kind
  17922. * - BABYLON.VertexBuffer.ColorKind
  17923. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17924. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17925. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17926. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17927. *
  17928. * Returns the Mesh.
  17929. */
  17930. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17931. return this;
  17932. };
  17933. /**
  17934. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17935. * If the mesh has no geometry, it is simply returned as it is.
  17936. * The `data` are either a numeric array either a Float32Array.
  17937. * No new underlying VertexBuffer object is created.
  17938. * 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.
  17939. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17940. *
  17941. * Possible `kind` values :
  17942. * - BABYLON.VertexBuffer.PositionKind
  17943. * - BABYLON.VertexBuffer.UVKind
  17944. * - BABYLON.VertexBuffer.UV2Kind
  17945. * - BABYLON.VertexBuffer.UV3Kind
  17946. * - BABYLON.VertexBuffer.UV4Kind
  17947. * - BABYLON.VertexBuffer.UV5Kind
  17948. * - BABYLON.VertexBuffer.UV6Kind
  17949. * - BABYLON.VertexBuffer.ColorKind
  17950. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17951. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17952. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17953. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17954. *
  17955. * Returns the Mesh.
  17956. */
  17957. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17958. return this;
  17959. };
  17960. /**
  17961. * Sets the mesh indices.
  17962. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17963. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17964. * This method creates a new index buffer each call.
  17965. * Returns the Mesh.
  17966. */
  17967. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17968. return this;
  17969. };
  17970. /** Returns false by default, used by the class Mesh.
  17971. * Returns a boolean
  17972. */
  17973. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17974. return false;
  17975. };
  17976. /**
  17977. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17978. * Returns a BoundingInfo
  17979. */
  17980. AbstractMesh.prototype.getBoundingInfo = function () {
  17981. if (this._masterMesh) {
  17982. return this._masterMesh.getBoundingInfo();
  17983. }
  17984. if (!this._boundingInfo) {
  17985. // this._boundingInfo is being created here
  17986. this._updateBoundingInfo();
  17987. }
  17988. // cannot be null.
  17989. return this._boundingInfo;
  17990. };
  17991. /**
  17992. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17993. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17994. */
  17995. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17996. if (includeDescendants === void 0) { includeDescendants = true; }
  17997. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17998. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17999. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18000. if (maxDimension === 0) {
  18001. return this;
  18002. }
  18003. var scale = 1 / maxDimension;
  18004. this.scaling.scaleInPlace(scale);
  18005. return this;
  18006. };
  18007. /**
  18008. * Sets a mesh new object BoundingInfo.
  18009. * Returns the AbstractMesh.
  18010. */
  18011. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18012. this._boundingInfo = boundingInfo;
  18013. return this;
  18014. };
  18015. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18016. get: function () {
  18017. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18018. },
  18019. enumerable: true,
  18020. configurable: true
  18021. });
  18022. AbstractMesh.prototype._preActivate = function () {
  18023. };
  18024. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18025. };
  18026. AbstractMesh.prototype._activate = function (renderId) {
  18027. this._renderId = renderId;
  18028. };
  18029. /**
  18030. * Returns the latest update of the World matrix
  18031. * Returns a Matrix.
  18032. */
  18033. AbstractMesh.prototype.getWorldMatrix = function () {
  18034. if (this._masterMesh) {
  18035. return this._masterMesh.getWorldMatrix();
  18036. }
  18037. return _super.prototype.getWorldMatrix.call(this);
  18038. };
  18039. /**
  18040. * Returns the latest update of the World matrix determinant.
  18041. */
  18042. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18043. if (this._masterMesh) {
  18044. return this._masterMesh._getWorldMatrixDeterminant();
  18045. }
  18046. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18047. };
  18048. // ================================== Point of View Movement =================================
  18049. /**
  18050. * Perform relative position change from the point of view of behind the front of the mesh.
  18051. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18052. * Supports definition of mesh facing forward or backward.
  18053. * @param {number} amountRight
  18054. * @param {number} amountUp
  18055. * @param {number} amountForward
  18056. *
  18057. * Returns the AbstractMesh.
  18058. */
  18059. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18060. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18061. return this;
  18062. };
  18063. /**
  18064. * Calculate relative position change from the point of view of behind the front of the mesh.
  18065. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18066. * Supports definition of mesh facing forward or backward.
  18067. * @param {number} amountRight
  18068. * @param {number} amountUp
  18069. * @param {number} amountForward
  18070. *
  18071. * Returns a new Vector3.
  18072. */
  18073. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18074. var rotMatrix = new BABYLON.Matrix();
  18075. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18076. rotQuaternion.toRotationMatrix(rotMatrix);
  18077. var translationDelta = BABYLON.Vector3.Zero();
  18078. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18079. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18080. return translationDelta;
  18081. };
  18082. // ================================== Point of View Rotation =================================
  18083. /**
  18084. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18085. * Supports definition of mesh facing forward or backward.
  18086. * @param {number} flipBack
  18087. * @param {number} twirlClockwise
  18088. * @param {number} tiltRight
  18089. *
  18090. * Returns the AbstractMesh.
  18091. */
  18092. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18093. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18094. return this;
  18095. };
  18096. /**
  18097. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18098. * Supports definition of mesh facing forward or backward.
  18099. * @param {number} flipBack
  18100. * @param {number} twirlClockwise
  18101. * @param {number} tiltRight
  18102. *
  18103. * Returns a new Vector3.
  18104. */
  18105. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18106. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18107. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18108. };
  18109. /**
  18110. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18111. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18112. */
  18113. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18114. if (includeDescendants === void 0) { includeDescendants = true; }
  18115. this.computeWorldMatrix(true);
  18116. var min;
  18117. var max;
  18118. var boundingInfo = this.getBoundingInfo();
  18119. if (!this.subMeshes) {
  18120. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18121. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18122. }
  18123. else {
  18124. min = boundingInfo.boundingBox.minimumWorld;
  18125. max = boundingInfo.boundingBox.maximumWorld;
  18126. }
  18127. if (includeDescendants) {
  18128. var descendants = this.getDescendants(false);
  18129. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18130. var descendant = descendants_1[_i];
  18131. var childMesh = descendant;
  18132. childMesh.computeWorldMatrix(true);
  18133. //make sure we have the needed params to get mix and max
  18134. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18135. continue;
  18136. }
  18137. var childBoundingInfo = childMesh.getBoundingInfo();
  18138. var boundingBox = childBoundingInfo.boundingBox;
  18139. var minBox = boundingBox.minimumWorld;
  18140. var maxBox = boundingBox.maximumWorld;
  18141. BABYLON.Tools.CheckExtends(minBox, min, max);
  18142. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18143. }
  18144. }
  18145. return {
  18146. min: min,
  18147. max: max
  18148. };
  18149. };
  18150. /**
  18151. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18152. * Returns the AbstractMesh.
  18153. */
  18154. AbstractMesh.prototype._updateBoundingInfo = function () {
  18155. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18156. this._boundingInfo.update(this.worldMatrixFromCache);
  18157. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18158. return this;
  18159. };
  18160. /**
  18161. * Update a mesh's children BoundingInfo objects only.
  18162. * Returns the AbstractMesh.
  18163. */
  18164. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18165. if (!this.subMeshes) {
  18166. return this;
  18167. }
  18168. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18169. var subMesh = this.subMeshes[subIndex];
  18170. if (!subMesh.IsGlobal) {
  18171. subMesh.updateBoundingInfo(matrix);
  18172. }
  18173. }
  18174. return this;
  18175. };
  18176. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18177. // Bounding info
  18178. this._updateBoundingInfo();
  18179. };
  18180. /**
  18181. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18182. * A mesh is in the frustum if its bounding box intersects the frustum.
  18183. * Boolean returned.
  18184. */
  18185. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18186. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18187. };
  18188. /**
  18189. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18190. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18191. * Boolean returned.
  18192. */
  18193. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18194. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18195. ;
  18196. };
  18197. /**
  18198. * True if the mesh intersects another mesh or a SolidParticle object.
  18199. * 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)
  18200. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18201. * Returns a boolean.
  18202. */
  18203. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18204. if (precise === void 0) { precise = false; }
  18205. if (!this._boundingInfo || !mesh._boundingInfo) {
  18206. return false;
  18207. }
  18208. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18209. return true;
  18210. }
  18211. if (includeDescendants) {
  18212. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18213. var child = _a[_i];
  18214. if (child.intersectsMesh(mesh, precise, true)) {
  18215. return true;
  18216. }
  18217. }
  18218. }
  18219. return false;
  18220. };
  18221. /**
  18222. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18223. * Returns a boolean.
  18224. */
  18225. AbstractMesh.prototype.intersectsPoint = function (point) {
  18226. if (!this._boundingInfo) {
  18227. return false;
  18228. }
  18229. return this._boundingInfo.intersectsPoint(point);
  18230. };
  18231. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18232. return this.physicsImpostor;
  18233. };
  18234. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18235. if (camera === void 0) { camera = null; }
  18236. if (!camera) {
  18237. camera = this.getScene().activeCamera;
  18238. }
  18239. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18240. };
  18241. /**
  18242. * Returns the distance from the mesh to the active camera.
  18243. * Returns a float.
  18244. */
  18245. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18246. if (camera === void 0) { camera = null; }
  18247. if (!camera) {
  18248. camera = this.getScene().activeCamera;
  18249. }
  18250. return this.absolutePosition.subtract(camera.position).length();
  18251. };
  18252. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18253. if (!this.physicsImpostor) {
  18254. return this;
  18255. }
  18256. this.physicsImpostor.applyImpulse(force, contactPoint);
  18257. return this;
  18258. };
  18259. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18260. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18261. return this;
  18262. }
  18263. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18264. mainPivot: pivot1,
  18265. connectedPivot: pivot2,
  18266. nativeParams: options
  18267. });
  18268. return this;
  18269. };
  18270. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18271. // Collisions
  18272. /**
  18273. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18274. * Default `false`.
  18275. */
  18276. get: function () {
  18277. return this._checkCollisions;
  18278. },
  18279. set: function (collisionEnabled) {
  18280. this._checkCollisions = collisionEnabled;
  18281. if (this.getScene().workerCollisions) {
  18282. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18283. }
  18284. },
  18285. enumerable: true,
  18286. configurable: true
  18287. });
  18288. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18289. /**
  18290. * Gets Collider object used to compute collisions (not physics)
  18291. */
  18292. get: function () {
  18293. return this._collider;
  18294. },
  18295. enumerable: true,
  18296. configurable: true
  18297. });
  18298. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18299. var globalPosition = this.getAbsolutePosition();
  18300. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18301. if (!this._collider) {
  18302. this._collider = new BABYLON.Collider();
  18303. }
  18304. this._collider._radius = this.ellipsoid;
  18305. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18306. return this;
  18307. };
  18308. // Submeshes octree
  18309. /**
  18310. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18311. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18312. * Returns an Octree of submeshes.
  18313. */
  18314. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18315. if (maxCapacity === void 0) { maxCapacity = 64; }
  18316. if (maxDepth === void 0) { maxDepth = 2; }
  18317. if (!this._submeshesOctree) {
  18318. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18319. }
  18320. this.computeWorldMatrix(true);
  18321. var boundingInfo = this.getBoundingInfo();
  18322. // Update octree
  18323. var bbox = boundingInfo.boundingBox;
  18324. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18325. return this._submeshesOctree;
  18326. };
  18327. // Collisions
  18328. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18329. this._generatePointsArray();
  18330. if (!this._positions) {
  18331. return this;
  18332. }
  18333. // Transformation
  18334. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18335. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18336. subMesh._lastColliderWorldVertices = [];
  18337. subMesh._trianglePlanes = [];
  18338. var start = subMesh.verticesStart;
  18339. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18340. for (var i = start; i < end; i++) {
  18341. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18342. }
  18343. }
  18344. // Collide
  18345. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18346. if (collider.collisionFound) {
  18347. collider.collidedMesh = this;
  18348. }
  18349. return this;
  18350. };
  18351. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18352. var subMeshes;
  18353. var len;
  18354. // Octrees
  18355. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18356. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18357. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18358. len = intersections.length;
  18359. subMeshes = intersections.data;
  18360. }
  18361. else {
  18362. subMeshes = this.subMeshes;
  18363. len = subMeshes.length;
  18364. }
  18365. for (var index = 0; index < len; index++) {
  18366. var subMesh = subMeshes[index];
  18367. // Bounding test
  18368. if (len > 1 && !subMesh._checkCollision(collider))
  18369. continue;
  18370. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18371. }
  18372. return this;
  18373. };
  18374. AbstractMesh.prototype._checkCollision = function (collider) {
  18375. // Bounding box test
  18376. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18377. return this;
  18378. // Transformation matrix
  18379. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18380. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18381. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18382. return this;
  18383. };
  18384. // Picking
  18385. AbstractMesh.prototype._generatePointsArray = function () {
  18386. return false;
  18387. };
  18388. /**
  18389. * Checks if the passed Ray intersects with the mesh.
  18390. * Returns an object PickingInfo.
  18391. */
  18392. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18393. var pickingInfo = new BABYLON.PickingInfo();
  18394. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18395. return pickingInfo;
  18396. }
  18397. if (!this._generatePointsArray()) {
  18398. return pickingInfo;
  18399. }
  18400. var intersectInfo = null;
  18401. // Octrees
  18402. var subMeshes;
  18403. var len;
  18404. if (this._submeshesOctree && this.useOctreeForPicking) {
  18405. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18406. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18407. len = intersections.length;
  18408. subMeshes = intersections.data;
  18409. }
  18410. else {
  18411. subMeshes = this.subMeshes;
  18412. len = subMeshes.length;
  18413. }
  18414. for (var index = 0; index < len; index++) {
  18415. var subMesh = subMeshes[index];
  18416. // Bounding test
  18417. if (len > 1 && !subMesh.canIntersects(ray))
  18418. continue;
  18419. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18420. if (currentIntersectInfo) {
  18421. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18422. intersectInfo = currentIntersectInfo;
  18423. intersectInfo.subMeshId = index;
  18424. if (fastCheck) {
  18425. break;
  18426. }
  18427. }
  18428. }
  18429. }
  18430. if (intersectInfo) {
  18431. // Get picked point
  18432. var world = this.getWorldMatrix();
  18433. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18434. var direction = ray.direction.clone();
  18435. direction = direction.scale(intersectInfo.distance);
  18436. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18437. var pickedPoint = worldOrigin.add(worldDirection);
  18438. // Return result
  18439. pickingInfo.hit = true;
  18440. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18441. pickingInfo.pickedPoint = pickedPoint;
  18442. pickingInfo.pickedMesh = this;
  18443. pickingInfo.bu = intersectInfo.bu || 0;
  18444. pickingInfo.bv = intersectInfo.bv || 0;
  18445. pickingInfo.faceId = intersectInfo.faceId;
  18446. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18447. return pickingInfo;
  18448. }
  18449. return pickingInfo;
  18450. };
  18451. /**
  18452. * Clones the mesh, used by the class Mesh.
  18453. * Just returns `null` for an AbstractMesh.
  18454. */
  18455. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18456. return null;
  18457. };
  18458. /**
  18459. * Disposes all the mesh submeshes.
  18460. * Returns the AbstractMesh.
  18461. */
  18462. AbstractMesh.prototype.releaseSubMeshes = function () {
  18463. if (this.subMeshes) {
  18464. while (this.subMeshes.length) {
  18465. this.subMeshes[0].dispose();
  18466. }
  18467. }
  18468. else {
  18469. this.subMeshes = new Array();
  18470. }
  18471. return this;
  18472. };
  18473. /**
  18474. * Disposes the AbstractMesh.
  18475. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18476. * Returns nothing.
  18477. */
  18478. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18479. var _this = this;
  18480. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18481. var index;
  18482. // Action manager
  18483. if (this.actionManager !== undefined && this.actionManager !== null) {
  18484. this.actionManager.dispose();
  18485. this.actionManager = null;
  18486. }
  18487. // Skeleton
  18488. this.skeleton = null;
  18489. // Physics
  18490. if (this.physicsImpostor) {
  18491. this.physicsImpostor.dispose();
  18492. }
  18493. // Intersections in progress
  18494. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18495. var other = this._intersectionsInProgress[index];
  18496. var pos = other._intersectionsInProgress.indexOf(this);
  18497. other._intersectionsInProgress.splice(pos, 1);
  18498. }
  18499. this._intersectionsInProgress = [];
  18500. // Lights
  18501. var lights = this.getScene().lights;
  18502. lights.forEach(function (light) {
  18503. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18504. if (meshIndex !== -1) {
  18505. light.includedOnlyMeshes.splice(meshIndex, 1);
  18506. }
  18507. meshIndex = light.excludedMeshes.indexOf(_this);
  18508. if (meshIndex !== -1) {
  18509. light.excludedMeshes.splice(meshIndex, 1);
  18510. }
  18511. // Shadow generators
  18512. var generator = light.getShadowGenerator();
  18513. if (generator) {
  18514. var shadowMap = generator.getShadowMap();
  18515. if (shadowMap && shadowMap.renderList) {
  18516. meshIndex = shadowMap.renderList.indexOf(_this);
  18517. if (meshIndex !== -1) {
  18518. shadowMap.renderList.splice(meshIndex, 1);
  18519. }
  18520. }
  18521. }
  18522. });
  18523. // Edges
  18524. if (this._edgesRenderer) {
  18525. this._edgesRenderer.dispose();
  18526. this._edgesRenderer = null;
  18527. }
  18528. // SubMeshes
  18529. if (this.getClassName() !== "InstancedMesh") {
  18530. this.releaseSubMeshes();
  18531. }
  18532. // Octree
  18533. var sceneOctree = this.getScene().selectionOctree;
  18534. if (sceneOctree !== undefined && sceneOctree !== null) {
  18535. var index = sceneOctree.dynamicContent.indexOf(this);
  18536. if (index !== -1) {
  18537. sceneOctree.dynamicContent.splice(index, 1);
  18538. }
  18539. }
  18540. // Query
  18541. var engine = this.getScene().getEngine();
  18542. if (this._occlusionQuery) {
  18543. this._isOcclusionQueryInProgress = false;
  18544. engine.deleteQuery(this._occlusionQuery);
  18545. this._occlusionQuery = null;
  18546. }
  18547. // Engine
  18548. engine.wipeCaches();
  18549. // Remove from scene
  18550. this.getScene().removeMesh(this);
  18551. if (disposeMaterialAndTextures) {
  18552. if (this.material) {
  18553. this.material.dispose(false, true);
  18554. }
  18555. }
  18556. if (!doNotRecurse) {
  18557. // Particles
  18558. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18559. if (this.getScene().particleSystems[index].emitter === this) {
  18560. this.getScene().particleSystems[index].dispose();
  18561. index--;
  18562. }
  18563. }
  18564. }
  18565. // facet data
  18566. if (this._facetDataEnabled) {
  18567. this.disableFacetData();
  18568. }
  18569. this.onAfterWorldMatrixUpdateObservable.clear();
  18570. this.onCollideObservable.clear();
  18571. this.onCollisionPositionChangeObservable.clear();
  18572. _super.prototype.dispose.call(this, doNotRecurse);
  18573. };
  18574. /**
  18575. * Adds the passed mesh as a child to the current mesh.
  18576. * Returns the AbstractMesh.
  18577. */
  18578. AbstractMesh.prototype.addChild = function (mesh) {
  18579. mesh.setParent(this);
  18580. return this;
  18581. };
  18582. /**
  18583. * Removes the passed mesh from the current mesh children list.
  18584. * Returns the AbstractMesh.
  18585. */
  18586. AbstractMesh.prototype.removeChild = function (mesh) {
  18587. mesh.setParent(null);
  18588. return this;
  18589. };
  18590. // Facet data
  18591. /**
  18592. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18593. * Returns the AbstractMesh.
  18594. */
  18595. AbstractMesh.prototype._initFacetData = function () {
  18596. if (!this._facetNormals) {
  18597. this._facetNormals = new Array();
  18598. }
  18599. if (!this._facetPositions) {
  18600. this._facetPositions = new Array();
  18601. }
  18602. if (!this._facetPartitioning) {
  18603. this._facetPartitioning = new Array();
  18604. }
  18605. this._facetNb = (this.getIndices().length / 3) | 0;
  18606. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18607. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18608. for (var f = 0; f < this._facetNb; f++) {
  18609. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18610. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18611. }
  18612. this._facetDataEnabled = true;
  18613. return this;
  18614. };
  18615. /**
  18616. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18617. * This method can be called within the render loop.
  18618. * 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.
  18619. * Returns the AbstractMesh.
  18620. */
  18621. AbstractMesh.prototype.updateFacetData = function () {
  18622. if (!this._facetDataEnabled) {
  18623. this._initFacetData();
  18624. }
  18625. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18626. var indices = this.getIndices();
  18627. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18628. var bInfo = this.getBoundingInfo();
  18629. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18630. // init arrays, matrix and sort function on first call
  18631. this._facetDepthSortEnabled = true;
  18632. if (indices instanceof Uint16Array) {
  18633. this._depthSortedIndices = new Uint16Array(indices);
  18634. }
  18635. else if (indices instanceof Uint32Array) {
  18636. this._depthSortedIndices = new Uint32Array(indices);
  18637. }
  18638. else {
  18639. var needs32bits = false;
  18640. for (var i = 0; i < indices.length; i++) {
  18641. if (indices[i] > 65535) {
  18642. needs32bits = true;
  18643. break;
  18644. }
  18645. }
  18646. if (needs32bits) {
  18647. this._depthSortedIndices = new Uint32Array(indices);
  18648. }
  18649. else {
  18650. this._depthSortedIndices = new Uint16Array(indices);
  18651. }
  18652. }
  18653. this._facetDepthSortFunction = function (f1, f2) {
  18654. return (f2.sqDistance - f1.sqDistance);
  18655. };
  18656. if (!this._facetDepthSortFrom) {
  18657. var camera = this.getScene().activeCamera;
  18658. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18659. }
  18660. this._depthSortedFacets = [];
  18661. for (var f = 0; f < this._facetNb; f++) {
  18662. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18663. this._depthSortedFacets.push(depthSortedFacet);
  18664. }
  18665. this._invertedMatrix = BABYLON.Matrix.Identity();
  18666. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18667. }
  18668. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18669. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18670. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18671. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18672. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18673. this._subDiv.max = this._partitioningSubdivisions;
  18674. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18675. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18676. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18677. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18678. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18679. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18680. // set the parameters for ComputeNormals()
  18681. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18682. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18683. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18684. this._facetParameters.bInfo = bInfo;
  18685. this._facetParameters.bbSize = this._bbSize;
  18686. this._facetParameters.subDiv = this._subDiv;
  18687. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18688. this._facetParameters.depthSort = this._facetDepthSort;
  18689. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18690. this.computeWorldMatrix(true);
  18691. this._worldMatrix.invertToRef(this._invertedMatrix);
  18692. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18693. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18694. }
  18695. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18696. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18697. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18698. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18699. var l = (this._depthSortedIndices.length / 3) | 0;
  18700. for (var f = 0; f < l; f++) {
  18701. var sind = this._depthSortedFacets[f].ind;
  18702. this._depthSortedIndices[f * 3] = indices[sind];
  18703. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18704. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18705. }
  18706. this.updateIndices(this._depthSortedIndices);
  18707. }
  18708. return this;
  18709. };
  18710. /**
  18711. * Returns the facetLocalNormals array.
  18712. * The normals are expressed in the mesh local space.
  18713. */
  18714. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18715. if (!this._facetNormals) {
  18716. this.updateFacetData();
  18717. }
  18718. return this._facetNormals;
  18719. };
  18720. /**
  18721. * Returns the facetLocalPositions array.
  18722. * The facet positions are expressed in the mesh local space.
  18723. */
  18724. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18725. if (!this._facetPositions) {
  18726. this.updateFacetData();
  18727. }
  18728. return this._facetPositions;
  18729. };
  18730. /**
  18731. * Returns the facetLocalPartioning array.
  18732. */
  18733. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18734. if (!this._facetPartitioning) {
  18735. this.updateFacetData();
  18736. }
  18737. return this._facetPartitioning;
  18738. };
  18739. /**
  18740. * Returns the i-th facet position in the world system.
  18741. * This method allocates a new Vector3 per call.
  18742. */
  18743. AbstractMesh.prototype.getFacetPosition = function (i) {
  18744. var pos = BABYLON.Vector3.Zero();
  18745. this.getFacetPositionToRef(i, pos);
  18746. return pos;
  18747. };
  18748. /**
  18749. * Sets the reference Vector3 with the i-th facet position in the world system.
  18750. * Returns the AbstractMesh.
  18751. */
  18752. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18753. var localPos = (this.getFacetLocalPositions())[i];
  18754. var world = this.getWorldMatrix();
  18755. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18756. return this;
  18757. };
  18758. /**
  18759. * Returns the i-th facet normal in the world system.
  18760. * This method allocates a new Vector3 per call.
  18761. */
  18762. AbstractMesh.prototype.getFacetNormal = function (i) {
  18763. var norm = BABYLON.Vector3.Zero();
  18764. this.getFacetNormalToRef(i, norm);
  18765. return norm;
  18766. };
  18767. /**
  18768. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18769. * Returns the AbstractMesh.
  18770. */
  18771. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18772. var localNorm = (this.getFacetLocalNormals())[i];
  18773. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18774. return this;
  18775. };
  18776. /**
  18777. * 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).
  18778. */
  18779. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18780. var bInfo = this.getBoundingInfo();
  18781. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18782. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18783. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18784. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18785. return null;
  18786. }
  18787. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18788. };
  18789. /**
  18790. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18791. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18792. * 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.
  18793. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18794. * 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.
  18795. */
  18796. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18797. if (checkFace === void 0) { checkFace = false; }
  18798. if (facing === void 0) { facing = true; }
  18799. var world = this.getWorldMatrix();
  18800. var invMat = BABYLON.Tmp.Matrix[5];
  18801. world.invertToRef(invMat);
  18802. var invVect = BABYLON.Tmp.Vector3[8];
  18803. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18804. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18805. if (projected) {
  18806. // tranform the local computed projected vector to world coordinates
  18807. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18808. }
  18809. return closest;
  18810. };
  18811. /**
  18812. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18813. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18814. * 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.
  18815. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18816. * 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.
  18817. */
  18818. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18819. if (checkFace === void 0) { checkFace = false; }
  18820. if (facing === void 0) { facing = true; }
  18821. var closest = null;
  18822. var tmpx = 0.0;
  18823. var tmpy = 0.0;
  18824. var tmpz = 0.0;
  18825. var d = 0.0; // tmp dot facet normal * facet position
  18826. var t0 = 0.0;
  18827. var projx = 0.0;
  18828. var projy = 0.0;
  18829. var projz = 0.0;
  18830. // Get all the facets in the same partitioning block than (x, y, z)
  18831. var facetPositions = this.getFacetLocalPositions();
  18832. var facetNormals = this.getFacetLocalNormals();
  18833. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18834. if (!facetsInBlock) {
  18835. return null;
  18836. }
  18837. // Get the closest facet to (x, y, z)
  18838. var shortest = Number.MAX_VALUE; // init distance vars
  18839. var tmpDistance = shortest;
  18840. var fib; // current facet in the block
  18841. var norm; // current facet normal
  18842. var p0; // current facet barycenter position
  18843. // loop on all the facets in the current partitioning block
  18844. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18845. fib = facetsInBlock[idx];
  18846. norm = facetNormals[fib];
  18847. p0 = facetPositions[fib];
  18848. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18849. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18850. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18851. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18852. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18853. projx = x + norm.x * t0;
  18854. projy = y + norm.y * t0;
  18855. projz = z + norm.z * t0;
  18856. tmpx = projx - x;
  18857. tmpy = projy - y;
  18858. tmpz = projz - z;
  18859. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18860. if (tmpDistance < shortest) {
  18861. shortest = tmpDistance;
  18862. closest = fib;
  18863. if (projected) {
  18864. projected.x = projx;
  18865. projected.y = projy;
  18866. projected.z = projz;
  18867. }
  18868. }
  18869. }
  18870. }
  18871. return closest;
  18872. };
  18873. /**
  18874. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18875. */
  18876. AbstractMesh.prototype.getFacetDataParameters = function () {
  18877. return this._facetParameters;
  18878. };
  18879. /**
  18880. * Disables the feature FacetData and frees the related memory.
  18881. * Returns the AbstractMesh.
  18882. */
  18883. AbstractMesh.prototype.disableFacetData = function () {
  18884. if (this._facetDataEnabled) {
  18885. this._facetDataEnabled = false;
  18886. this._facetPositions = new Array();
  18887. this._facetNormals = new Array();
  18888. this._facetPartitioning = new Array();
  18889. this._facetParameters = null;
  18890. this._depthSortedIndices = new Uint32Array(0);
  18891. }
  18892. return this;
  18893. };
  18894. /**
  18895. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18896. * Returns the mesh.
  18897. */
  18898. AbstractMesh.prototype.updateIndices = function (indices) {
  18899. return this;
  18900. };
  18901. /**
  18902. * The mesh Geometry. Actually used by the Mesh object.
  18903. * Returns a blank geometry object.
  18904. */
  18905. /**
  18906. * Creates new normals data for the mesh.
  18907. * @param updatable.
  18908. */
  18909. AbstractMesh.prototype.createNormals = function (updatable) {
  18910. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18911. var indices = this.getIndices();
  18912. var normals;
  18913. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18914. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18915. }
  18916. else {
  18917. normals = [];
  18918. }
  18919. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18920. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18921. };
  18922. /**
  18923. * Align the mesh with a normal.
  18924. * Returns the mesh.
  18925. */
  18926. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18927. if (!upDirection) {
  18928. upDirection = BABYLON.Axis.Y;
  18929. }
  18930. var axisX = BABYLON.Tmp.Vector3[0];
  18931. var axisZ = BABYLON.Tmp.Vector3[1];
  18932. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18933. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18934. if (this.rotationQuaternion) {
  18935. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18936. }
  18937. else {
  18938. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18939. }
  18940. return this;
  18941. };
  18942. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18943. var engine = this.getEngine();
  18944. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18945. this._isOccluded = false;
  18946. return;
  18947. }
  18948. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18949. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18950. if (isOcclusionQueryAvailable) {
  18951. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18952. this._isOcclusionQueryInProgress = false;
  18953. this._occlusionInternalRetryCounter = 0;
  18954. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18955. }
  18956. else {
  18957. this._occlusionInternalRetryCounter++;
  18958. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18959. this._isOcclusionQueryInProgress = false;
  18960. this._occlusionInternalRetryCounter = 0;
  18961. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18962. // if strict continue the last state of the object.
  18963. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18964. }
  18965. else {
  18966. return;
  18967. }
  18968. }
  18969. }
  18970. var scene = this.getScene();
  18971. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18972. if (!this._occlusionQuery) {
  18973. this._occlusionQuery = engine.createQuery();
  18974. }
  18975. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18976. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18977. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18978. this._isOcclusionQueryInProgress = true;
  18979. };
  18980. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18981. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18982. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18983. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18984. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18985. return AbstractMesh;
  18986. }(BABYLON.TransformNode));
  18987. BABYLON.AbstractMesh = AbstractMesh;
  18988. })(BABYLON || (BABYLON = {}));
  18989. //# sourceMappingURL=babylon.abstractMesh.js.map
  18990. var BABYLON;
  18991. (function (BABYLON) {
  18992. /**
  18993. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18994. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18995. * 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.
  18996. */
  18997. var Light = /** @class */ (function (_super) {
  18998. __extends(Light, _super);
  18999. /**
  19000. * Creates a Light object in the scene.
  19001. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19002. * @param name The firendly name of the light
  19003. * @param scene The scene the light belongs too
  19004. */
  19005. function Light(name, scene) {
  19006. var _this = _super.call(this, name, scene) || this;
  19007. /**
  19008. * Diffuse gives the basic color to an object.
  19009. */
  19010. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19011. /**
  19012. * Specular produces a highlight color on an object.
  19013. * Note: This is note affecting PBR materials.
  19014. */
  19015. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19016. /**
  19017. * Strength of the light.
  19018. * Note: By default it is define in the framework own unit.
  19019. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19020. */
  19021. _this.intensity = 1.0;
  19022. /**
  19023. * Defines how far from the source the light is impacting in scene units.
  19024. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19025. */
  19026. _this.range = Number.MAX_VALUE;
  19027. /**
  19028. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19029. * of light.
  19030. */
  19031. _this._photometricScale = 1.0;
  19032. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19033. _this._radius = 0.00001;
  19034. /**
  19035. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19036. * exceeding the number allowed of the materials.
  19037. */
  19038. _this.renderPriority = 0;
  19039. /**
  19040. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19041. * the current shadow generator.
  19042. */
  19043. _this.shadowEnabled = true;
  19044. _this._excludeWithLayerMask = 0;
  19045. _this._includeOnlyWithLayerMask = 0;
  19046. _this._lightmapMode = 0;
  19047. /**
  19048. * @ignore Internal use only.
  19049. */
  19050. _this._excludedMeshesIds = new Array();
  19051. /**
  19052. * @ignore Internal use only.
  19053. */
  19054. _this._includedOnlyMeshesIds = new Array();
  19055. _this.getScene().addLight(_this);
  19056. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19057. _this._buildUniformLayout();
  19058. _this.includedOnlyMeshes = new Array();
  19059. _this.excludedMeshes = new Array();
  19060. _this._resyncMeshes();
  19061. return _this;
  19062. }
  19063. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19064. /**
  19065. * If every light affecting the material is in this lightmapMode,
  19066. * material.lightmapTexture adds or multiplies
  19067. * (depends on material.useLightmapAsShadowmap)
  19068. * after every other light calculations.
  19069. */
  19070. get: function () {
  19071. return Light._LIGHTMAP_DEFAULT;
  19072. },
  19073. enumerable: true,
  19074. configurable: true
  19075. });
  19076. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19077. /**
  19078. * material.lightmapTexture as only diffuse lighting from this light
  19079. * adds only specular lighting from this light
  19080. * adds dynamic shadows
  19081. */
  19082. get: function () {
  19083. return Light._LIGHTMAP_SPECULAR;
  19084. },
  19085. enumerable: true,
  19086. configurable: true
  19087. });
  19088. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19089. /**
  19090. * material.lightmapTexture as only lighting
  19091. * no light calculation from this light
  19092. * only adds dynamic shadows from this light
  19093. */
  19094. get: function () {
  19095. return Light._LIGHTMAP_SHADOWSONLY;
  19096. },
  19097. enumerable: true,
  19098. configurable: true
  19099. });
  19100. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19101. /**
  19102. * Each light type uses the default quantity according to its type:
  19103. * point/spot lights use luminous intensity
  19104. * directional lights use illuminance
  19105. */
  19106. get: function () {
  19107. return Light._INTENSITYMODE_AUTOMATIC;
  19108. },
  19109. enumerable: true,
  19110. configurable: true
  19111. });
  19112. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19113. /**
  19114. * lumen (lm)
  19115. */
  19116. get: function () {
  19117. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19118. },
  19119. enumerable: true,
  19120. configurable: true
  19121. });
  19122. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19123. /**
  19124. * candela (lm/sr)
  19125. */
  19126. get: function () {
  19127. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19128. },
  19129. enumerable: true,
  19130. configurable: true
  19131. });
  19132. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19133. /**
  19134. * lux (lm/m^2)
  19135. */
  19136. get: function () {
  19137. return Light._INTENSITYMODE_ILLUMINANCE;
  19138. },
  19139. enumerable: true,
  19140. configurable: true
  19141. });
  19142. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19143. /**
  19144. * nit (cd/m^2)
  19145. */
  19146. get: function () {
  19147. return Light._INTENSITYMODE_LUMINANCE;
  19148. },
  19149. enumerable: true,
  19150. configurable: true
  19151. });
  19152. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19153. /**
  19154. * Light type const id of the point light.
  19155. */
  19156. get: function () {
  19157. return Light._LIGHTTYPEID_POINTLIGHT;
  19158. },
  19159. enumerable: true,
  19160. configurable: true
  19161. });
  19162. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19163. /**
  19164. * Light type const id of the directional light.
  19165. */
  19166. get: function () {
  19167. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19168. },
  19169. enumerable: true,
  19170. configurable: true
  19171. });
  19172. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19173. /**
  19174. * Light type const id of the spot light.
  19175. */
  19176. get: function () {
  19177. return Light._LIGHTTYPEID_SPOTLIGHT;
  19178. },
  19179. enumerable: true,
  19180. configurable: true
  19181. });
  19182. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19183. /**
  19184. * Light type const id of the hemispheric light.
  19185. */
  19186. get: function () {
  19187. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19188. },
  19189. enumerable: true,
  19190. configurable: true
  19191. });
  19192. Object.defineProperty(Light.prototype, "intensityMode", {
  19193. /**
  19194. * Gets the photometric scale used to interpret the intensity.
  19195. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19196. */
  19197. get: function () {
  19198. return this._intensityMode;
  19199. },
  19200. /**
  19201. * Sets the photometric scale used to interpret the intensity.
  19202. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19203. */
  19204. set: function (value) {
  19205. this._intensityMode = value;
  19206. this._computePhotometricScale();
  19207. },
  19208. enumerable: true,
  19209. configurable: true
  19210. });
  19211. ;
  19212. ;
  19213. Object.defineProperty(Light.prototype, "radius", {
  19214. /**
  19215. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19216. */
  19217. get: function () {
  19218. return this._radius;
  19219. },
  19220. /**
  19221. * sets the light radius used by PBR Materials to simulate soft area lights.
  19222. */
  19223. set: function (value) {
  19224. this._radius = value;
  19225. this._computePhotometricScale();
  19226. },
  19227. enumerable: true,
  19228. configurable: true
  19229. });
  19230. ;
  19231. ;
  19232. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19233. /**
  19234. * Gets the only meshes impacted by this light.
  19235. */
  19236. get: function () {
  19237. return this._includedOnlyMeshes;
  19238. },
  19239. /**
  19240. * Sets the only meshes impacted by this light.
  19241. */
  19242. set: function (value) {
  19243. this._includedOnlyMeshes = value;
  19244. this._hookArrayForIncludedOnly(value);
  19245. },
  19246. enumerable: true,
  19247. configurable: true
  19248. });
  19249. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19250. /**
  19251. * Gets the meshes not impacted by this light.
  19252. */
  19253. get: function () {
  19254. return this._excludedMeshes;
  19255. },
  19256. /**
  19257. * Sets the meshes not impacted by this light.
  19258. */
  19259. set: function (value) {
  19260. this._excludedMeshes = value;
  19261. this._hookArrayForExcluded(value);
  19262. },
  19263. enumerable: true,
  19264. configurable: true
  19265. });
  19266. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19267. /**
  19268. * Gets the layer id use to find what meshes are not impacted by the light.
  19269. * Inactive if 0
  19270. */
  19271. get: function () {
  19272. return this._excludeWithLayerMask;
  19273. },
  19274. /**
  19275. * Sets the layer id use to find what meshes are not impacted by the light.
  19276. * Inactive if 0
  19277. */
  19278. set: function (value) {
  19279. this._excludeWithLayerMask = value;
  19280. this._resyncMeshes();
  19281. },
  19282. enumerable: true,
  19283. configurable: true
  19284. });
  19285. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19286. /**
  19287. * Gets the layer id use to find what meshes are impacted by the light.
  19288. * Inactive if 0
  19289. */
  19290. get: function () {
  19291. return this._includeOnlyWithLayerMask;
  19292. },
  19293. /**
  19294. * Sets the layer id use to find what meshes are impacted by the light.
  19295. * Inactive if 0
  19296. */
  19297. set: function (value) {
  19298. this._includeOnlyWithLayerMask = value;
  19299. this._resyncMeshes();
  19300. },
  19301. enumerable: true,
  19302. configurable: true
  19303. });
  19304. Object.defineProperty(Light.prototype, "lightmapMode", {
  19305. /**
  19306. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19307. */
  19308. get: function () {
  19309. return this._lightmapMode;
  19310. },
  19311. /**
  19312. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19313. */
  19314. set: function (value) {
  19315. if (this._lightmapMode === value) {
  19316. return;
  19317. }
  19318. this._lightmapMode = value;
  19319. this._markMeshesAsLightDirty();
  19320. },
  19321. enumerable: true,
  19322. configurable: true
  19323. });
  19324. /**
  19325. * Returns the string "Light".
  19326. * @returns the class name
  19327. */
  19328. Light.prototype.getClassName = function () {
  19329. return "Light";
  19330. };
  19331. /**
  19332. * Converts the light information to a readable string for debug purpose.
  19333. * @param fullDetails Supports for multiple levels of logging within scene loading
  19334. * @returns the human readable light info
  19335. */
  19336. Light.prototype.toString = function (fullDetails) {
  19337. var ret = "Name: " + this.name;
  19338. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19339. if (this.animations) {
  19340. for (var i = 0; i < this.animations.length; i++) {
  19341. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19342. }
  19343. }
  19344. if (fullDetails) {
  19345. }
  19346. return ret;
  19347. };
  19348. /**
  19349. * Set the enabled state of this node.
  19350. * @param value - the new enabled state
  19351. * @see isEnabled
  19352. */
  19353. Light.prototype.setEnabled = function (value) {
  19354. _super.prototype.setEnabled.call(this, value);
  19355. this._resyncMeshes();
  19356. };
  19357. /**
  19358. * Returns the Light associated shadow generator if any.
  19359. * @return the associated shadow generator.
  19360. */
  19361. Light.prototype.getShadowGenerator = function () {
  19362. return this._shadowGenerator;
  19363. };
  19364. /**
  19365. * Returns a Vector3, the absolute light position in the World.
  19366. * @returns the world space position of the light
  19367. */
  19368. Light.prototype.getAbsolutePosition = function () {
  19369. return BABYLON.Vector3.Zero();
  19370. };
  19371. /**
  19372. * Specifies if the light will affect the passed mesh.
  19373. * @param mesh The mesh to test against the light
  19374. * @return true the mesh is affected otherwise, false.
  19375. */
  19376. Light.prototype.canAffectMesh = function (mesh) {
  19377. if (!mesh) {
  19378. return true;
  19379. }
  19380. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19381. return false;
  19382. }
  19383. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19384. return false;
  19385. }
  19386. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19387. return false;
  19388. }
  19389. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19390. return false;
  19391. }
  19392. return true;
  19393. };
  19394. /**
  19395. * Computes and Returns the light World matrix.
  19396. * @returns the world matrix
  19397. */
  19398. Light.prototype.getWorldMatrix = function () {
  19399. this._currentRenderId = this.getScene().getRenderId();
  19400. var worldMatrix = this._getWorldMatrix();
  19401. if (this.parent && this.parent.getWorldMatrix) {
  19402. if (!this._parentedWorldMatrix) {
  19403. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19404. }
  19405. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19406. this._markSyncedWithParent();
  19407. return this._parentedWorldMatrix;
  19408. }
  19409. return worldMatrix;
  19410. };
  19411. /**
  19412. * Sort function to order lights for rendering.
  19413. * @param a First Light object to compare to second.
  19414. * @param b Second Light object to compare first.
  19415. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19416. */
  19417. Light.CompareLightsPriority = function (a, b) {
  19418. //shadow-casting lights have priority over non-shadow-casting lights
  19419. //the renderPrioirty is a secondary sort criterion
  19420. if (a.shadowEnabled !== b.shadowEnabled) {
  19421. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19422. }
  19423. return b.renderPriority - a.renderPriority;
  19424. };
  19425. /**
  19426. * Disposes the light.
  19427. */
  19428. Light.prototype.dispose = function () {
  19429. if (this._shadowGenerator) {
  19430. this._shadowGenerator.dispose();
  19431. this._shadowGenerator = null;
  19432. }
  19433. // Animations
  19434. this.getScene().stopAnimation(this);
  19435. // Remove from meshes
  19436. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19437. var mesh = _a[_i];
  19438. mesh._removeLightSource(this);
  19439. }
  19440. this._uniformBuffer.dispose();
  19441. // Remove from scene
  19442. this.getScene().removeLight(this);
  19443. _super.prototype.dispose.call(this);
  19444. };
  19445. /**
  19446. * Returns the light type ID (integer).
  19447. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19448. */
  19449. Light.prototype.getTypeID = function () {
  19450. return 0;
  19451. };
  19452. /**
  19453. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19454. * @returns the scaled intensity in intensity mode unit
  19455. */
  19456. Light.prototype.getScaledIntensity = function () {
  19457. return this._photometricScale * this.intensity;
  19458. };
  19459. /**
  19460. * Returns a new Light object, named "name", from the current one.
  19461. * @param name The name of the cloned light
  19462. * @returns the new created light
  19463. */
  19464. Light.prototype.clone = function (name) {
  19465. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19466. if (!constructor) {
  19467. return null;
  19468. }
  19469. return BABYLON.SerializationHelper.Clone(constructor, this);
  19470. };
  19471. /**
  19472. * Serializes the current light into a Serialization object.
  19473. * @returns the serialized object.
  19474. */
  19475. Light.prototype.serialize = function () {
  19476. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19477. // Type
  19478. serializationObject.type = this.getTypeID();
  19479. // Parent
  19480. if (this.parent) {
  19481. serializationObject.parentId = this.parent.id;
  19482. }
  19483. // Inclusion / exclusions
  19484. if (this.excludedMeshes.length > 0) {
  19485. serializationObject.excludedMeshesIds = [];
  19486. this.excludedMeshes.forEach(function (mesh) {
  19487. serializationObject.excludedMeshesIds.push(mesh.id);
  19488. });
  19489. }
  19490. if (this.includedOnlyMeshes.length > 0) {
  19491. serializationObject.includedOnlyMeshesIds = [];
  19492. this.includedOnlyMeshes.forEach(function (mesh) {
  19493. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19494. });
  19495. }
  19496. // Animations
  19497. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19498. serializationObject.ranges = this.serializeAnimationRanges();
  19499. return serializationObject;
  19500. };
  19501. /**
  19502. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19503. * This new light is named "name" and added to the passed scene.
  19504. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19505. * @param name The friendly name of the light
  19506. * @param scene The scene the new light will belong to
  19507. * @returns the constructor function
  19508. */
  19509. Light.GetConstructorFromName = function (type, name, scene) {
  19510. switch (type) {
  19511. case 0:
  19512. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19513. case 1:
  19514. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19515. case 2:
  19516. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19517. case 3:
  19518. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19519. }
  19520. return null;
  19521. };
  19522. /**
  19523. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19524. * @param parsedLight The JSON representation of the light
  19525. * @param scene The scene to create the parsed light in
  19526. * @returns the created light after parsing
  19527. */
  19528. Light.Parse = function (parsedLight, scene) {
  19529. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19530. if (!constructor) {
  19531. return null;
  19532. }
  19533. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19534. // Inclusion / exclusions
  19535. if (parsedLight.excludedMeshesIds) {
  19536. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19537. }
  19538. if (parsedLight.includedOnlyMeshesIds) {
  19539. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19540. }
  19541. // Parent
  19542. if (parsedLight.parentId) {
  19543. light._waitingParentId = parsedLight.parentId;
  19544. }
  19545. // Animations
  19546. if (parsedLight.animations) {
  19547. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19548. var parsedAnimation = parsedLight.animations[animationIndex];
  19549. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19550. }
  19551. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19552. }
  19553. if (parsedLight.autoAnimate) {
  19554. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19555. }
  19556. return light;
  19557. };
  19558. Light.prototype._hookArrayForExcluded = function (array) {
  19559. var _this = this;
  19560. var oldPush = array.push;
  19561. array.push = function () {
  19562. var items = [];
  19563. for (var _i = 0; _i < arguments.length; _i++) {
  19564. items[_i] = arguments[_i];
  19565. }
  19566. var result = oldPush.apply(array, items);
  19567. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19568. var item = items_1[_a];
  19569. item._resyncLighSource(_this);
  19570. }
  19571. return result;
  19572. };
  19573. var oldSplice = array.splice;
  19574. array.splice = function (index, deleteCount) {
  19575. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19576. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19577. var item = deleted_1[_i];
  19578. item._resyncLighSource(_this);
  19579. }
  19580. return deleted;
  19581. };
  19582. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19583. var item = array_1[_i];
  19584. item._resyncLighSource(this);
  19585. }
  19586. };
  19587. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19588. var _this = this;
  19589. var oldPush = array.push;
  19590. array.push = function () {
  19591. var items = [];
  19592. for (var _i = 0; _i < arguments.length; _i++) {
  19593. items[_i] = arguments[_i];
  19594. }
  19595. var result = oldPush.apply(array, items);
  19596. _this._resyncMeshes();
  19597. return result;
  19598. };
  19599. var oldSplice = array.splice;
  19600. array.splice = function (index, deleteCount) {
  19601. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19602. _this._resyncMeshes();
  19603. return deleted;
  19604. };
  19605. this._resyncMeshes();
  19606. };
  19607. Light.prototype._resyncMeshes = function () {
  19608. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19609. var mesh = _a[_i];
  19610. mesh._resyncLighSource(this);
  19611. }
  19612. };
  19613. /**
  19614. * Forces the meshes to update their light related information in their rendering used effects
  19615. * @ignore Internal Use Only
  19616. */
  19617. Light.prototype._markMeshesAsLightDirty = function () {
  19618. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19619. var mesh = _a[_i];
  19620. if (mesh._lightSources.indexOf(this) !== -1) {
  19621. mesh._markSubMeshesAsLightDirty();
  19622. }
  19623. }
  19624. };
  19625. /**
  19626. * Recomputes the cached photometric scale if needed.
  19627. */
  19628. Light.prototype._computePhotometricScale = function () {
  19629. this._photometricScale = this._getPhotometricScale();
  19630. this.getScene().resetCachedMaterial();
  19631. };
  19632. /**
  19633. * Returns the Photometric Scale according to the light type and intensity mode.
  19634. */
  19635. Light.prototype._getPhotometricScale = function () {
  19636. var photometricScale = 0.0;
  19637. var lightTypeID = this.getTypeID();
  19638. //get photometric mode
  19639. var photometricMode = this.intensityMode;
  19640. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19641. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19642. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19643. }
  19644. else {
  19645. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19646. }
  19647. }
  19648. //compute photometric scale
  19649. switch (lightTypeID) {
  19650. case Light.LIGHTTYPEID_POINTLIGHT:
  19651. case Light.LIGHTTYPEID_SPOTLIGHT:
  19652. switch (photometricMode) {
  19653. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19654. photometricScale = 1.0 / (4.0 * Math.PI);
  19655. break;
  19656. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19657. photometricScale = 1.0;
  19658. break;
  19659. case Light.INTENSITYMODE_LUMINANCE:
  19660. photometricScale = this.radius * this.radius;
  19661. break;
  19662. }
  19663. break;
  19664. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19665. switch (photometricMode) {
  19666. case Light.INTENSITYMODE_ILLUMINANCE:
  19667. photometricScale = 1.0;
  19668. break;
  19669. case Light.INTENSITYMODE_LUMINANCE:
  19670. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19671. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19672. var apexAngleRadians = this.radius;
  19673. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19674. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19675. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19676. photometricScale = solidAngle;
  19677. break;
  19678. }
  19679. break;
  19680. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19681. // No fall off in hemisperic light.
  19682. photometricScale = 1.0;
  19683. break;
  19684. }
  19685. return photometricScale;
  19686. };
  19687. /**
  19688. * Reorder the light in the scene according to their defined priority.
  19689. * @ignore Internal Use Only
  19690. */
  19691. Light.prototype._reorderLightsInScene = function () {
  19692. var scene = this.getScene();
  19693. if (this._renderPriority != 0) {
  19694. scene.requireLightSorting = true;
  19695. }
  19696. this.getScene().sortLightsByPriority();
  19697. };
  19698. //lightmapMode Consts
  19699. Light._LIGHTMAP_DEFAULT = 0;
  19700. Light._LIGHTMAP_SPECULAR = 1;
  19701. Light._LIGHTMAP_SHADOWSONLY = 2;
  19702. // Intensity Mode Consts
  19703. Light._INTENSITYMODE_AUTOMATIC = 0;
  19704. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19705. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19706. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19707. Light._INTENSITYMODE_LUMINANCE = 4;
  19708. // Light types ids const.
  19709. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19710. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19711. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19712. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19713. __decorate([
  19714. BABYLON.serializeAsColor3()
  19715. ], Light.prototype, "diffuse", void 0);
  19716. __decorate([
  19717. BABYLON.serializeAsColor3()
  19718. ], Light.prototype, "specular", void 0);
  19719. __decorate([
  19720. BABYLON.serialize()
  19721. ], Light.prototype, "intensity", void 0);
  19722. __decorate([
  19723. BABYLON.serialize()
  19724. ], Light.prototype, "range", void 0);
  19725. __decorate([
  19726. BABYLON.serialize()
  19727. ], Light.prototype, "intensityMode", null);
  19728. __decorate([
  19729. BABYLON.serialize()
  19730. ], Light.prototype, "radius", null);
  19731. __decorate([
  19732. BABYLON.serialize()
  19733. ], Light.prototype, "_renderPriority", void 0);
  19734. __decorate([
  19735. BABYLON.expandToProperty("_reorderLightsInScene")
  19736. ], Light.prototype, "renderPriority", void 0);
  19737. __decorate([
  19738. BABYLON.serialize()
  19739. ], Light.prototype, "shadowEnabled", void 0);
  19740. __decorate([
  19741. BABYLON.serialize("excludeWithLayerMask")
  19742. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19743. __decorate([
  19744. BABYLON.serialize("includeOnlyWithLayerMask")
  19745. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19746. __decorate([
  19747. BABYLON.serialize("lightmapMode")
  19748. ], Light.prototype, "_lightmapMode", void 0);
  19749. return Light;
  19750. }(BABYLON.Node));
  19751. BABYLON.Light = Light;
  19752. })(BABYLON || (BABYLON = {}));
  19753. //# sourceMappingURL=babylon.light.js.map
  19754. var BABYLON;
  19755. (function (BABYLON) {
  19756. var Camera = /** @class */ (function (_super) {
  19757. __extends(Camera, _super);
  19758. function Camera(name, position, scene) {
  19759. var _this = _super.call(this, name, scene) || this;
  19760. /**
  19761. * The vector the camera should consider as up.
  19762. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19763. */
  19764. _this.upVector = BABYLON.Vector3.Up();
  19765. _this.orthoLeft = null;
  19766. _this.orthoRight = null;
  19767. _this.orthoBottom = null;
  19768. _this.orthoTop = null;
  19769. /**
  19770. * FOV is set in Radians. (default is 0.8)
  19771. */
  19772. _this.fov = 0.8;
  19773. _this.minZ = 1;
  19774. _this.maxZ = 10000.0;
  19775. _this.inertia = 0.9;
  19776. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19777. _this.isIntermediate = false;
  19778. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19779. /**
  19780. * Restricts the camera to viewing objects with the same layerMask.
  19781. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19782. */
  19783. _this.layerMask = 0x0FFFFFFF;
  19784. /**
  19785. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19786. */
  19787. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19788. // Camera rig members
  19789. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19790. _this._rigCameras = new Array();
  19791. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19792. _this._skipRendering = false;
  19793. _this.customRenderTargets = new Array();
  19794. // Observables
  19795. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19796. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19797. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19798. _this.onRestoreStateObservable = new BABYLON.Observable();
  19799. // Cache
  19800. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19801. _this._projectionMatrix = new BABYLON.Matrix();
  19802. _this._doNotComputeProjectionMatrix = false;
  19803. _this._postProcesses = new Array();
  19804. _this._transformMatrix = BABYLON.Matrix.Zero();
  19805. _this._activeMeshes = new BABYLON.SmartArray(256);
  19806. _this._globalPosition = BABYLON.Vector3.Zero();
  19807. _this._refreshFrustumPlanes = true;
  19808. _this.getScene().addCamera(_this);
  19809. if (!_this.getScene().activeCamera) {
  19810. _this.getScene().activeCamera = _this;
  19811. }
  19812. _this.position = position;
  19813. return _this;
  19814. }
  19815. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19816. get: function () {
  19817. return Camera._PERSPECTIVE_CAMERA;
  19818. },
  19819. enumerable: true,
  19820. configurable: true
  19821. });
  19822. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19823. get: function () {
  19824. return Camera._ORTHOGRAPHIC_CAMERA;
  19825. },
  19826. enumerable: true,
  19827. configurable: true
  19828. });
  19829. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19830. /**
  19831. * This is the default FOV mode for perspective cameras.
  19832. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19833. *
  19834. */
  19835. get: function () {
  19836. return Camera._FOVMODE_VERTICAL_FIXED;
  19837. },
  19838. enumerable: true,
  19839. configurable: true
  19840. });
  19841. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19842. /**
  19843. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19844. *
  19845. */
  19846. get: function () {
  19847. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19853. get: function () {
  19854. return Camera._RIG_MODE_NONE;
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19860. get: function () {
  19861. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19862. },
  19863. enumerable: true,
  19864. configurable: true
  19865. });
  19866. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19867. get: function () {
  19868. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19869. },
  19870. enumerable: true,
  19871. configurable: true
  19872. });
  19873. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19874. get: function () {
  19875. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19876. },
  19877. enumerable: true,
  19878. configurable: true
  19879. });
  19880. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19881. get: function () {
  19882. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19883. },
  19884. enumerable: true,
  19885. configurable: true
  19886. });
  19887. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19888. get: function () {
  19889. return Camera._RIG_MODE_VR;
  19890. },
  19891. enumerable: true,
  19892. configurable: true
  19893. });
  19894. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19895. get: function () {
  19896. return Camera._RIG_MODE_WEBVR;
  19897. },
  19898. enumerable: true,
  19899. configurable: true
  19900. });
  19901. /**
  19902. * Store current camera state (fov, position, etc..)
  19903. */
  19904. Camera.prototype.storeState = function () {
  19905. this._stateStored = true;
  19906. this._storedFov = this.fov;
  19907. return this;
  19908. };
  19909. /**
  19910. * Restores the camera state values if it has been stored. You must call storeState() first
  19911. */
  19912. Camera.prototype._restoreStateValues = function () {
  19913. if (!this._stateStored) {
  19914. return false;
  19915. }
  19916. this.fov = this._storedFov;
  19917. return true;
  19918. };
  19919. /**
  19920. * Restored camera state. You must call storeState() first
  19921. */
  19922. Camera.prototype.restoreState = function () {
  19923. if (this._restoreStateValues()) {
  19924. this.onRestoreStateObservable.notifyObservers(this);
  19925. return true;
  19926. }
  19927. return false;
  19928. };
  19929. Camera.prototype.getClassName = function () {
  19930. return "Camera";
  19931. };
  19932. /**
  19933. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19934. */
  19935. Camera.prototype.toString = function (fullDetails) {
  19936. var ret = "Name: " + this.name;
  19937. ret += ", type: " + this.getClassName();
  19938. if (this.animations) {
  19939. for (var i = 0; i < this.animations.length; i++) {
  19940. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19941. }
  19942. }
  19943. if (fullDetails) {
  19944. }
  19945. return ret;
  19946. };
  19947. Object.defineProperty(Camera.prototype, "globalPosition", {
  19948. get: function () {
  19949. return this._globalPosition;
  19950. },
  19951. enumerable: true,
  19952. configurable: true
  19953. });
  19954. Camera.prototype.getActiveMeshes = function () {
  19955. return this._activeMeshes;
  19956. };
  19957. Camera.prototype.isActiveMesh = function (mesh) {
  19958. return (this._activeMeshes.indexOf(mesh) !== -1);
  19959. };
  19960. //Cache
  19961. Camera.prototype._initCache = function () {
  19962. _super.prototype._initCache.call(this);
  19963. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19964. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19965. this._cache.mode = undefined;
  19966. this._cache.minZ = undefined;
  19967. this._cache.maxZ = undefined;
  19968. this._cache.fov = undefined;
  19969. this._cache.fovMode = undefined;
  19970. this._cache.aspectRatio = undefined;
  19971. this._cache.orthoLeft = undefined;
  19972. this._cache.orthoRight = undefined;
  19973. this._cache.orthoBottom = undefined;
  19974. this._cache.orthoTop = undefined;
  19975. this._cache.renderWidth = undefined;
  19976. this._cache.renderHeight = undefined;
  19977. };
  19978. Camera.prototype._updateCache = function (ignoreParentClass) {
  19979. if (!ignoreParentClass) {
  19980. _super.prototype._updateCache.call(this);
  19981. }
  19982. this._cache.position.copyFrom(this.position);
  19983. this._cache.upVector.copyFrom(this.upVector);
  19984. };
  19985. // Synchronized
  19986. Camera.prototype._isSynchronized = function () {
  19987. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19988. };
  19989. Camera.prototype._isSynchronizedViewMatrix = function () {
  19990. if (!_super.prototype._isSynchronized.call(this))
  19991. return false;
  19992. return this._cache.position.equals(this.position)
  19993. && this._cache.upVector.equals(this.upVector)
  19994. && this.isSynchronizedWithParent();
  19995. };
  19996. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19997. var check = this._cache.mode === this.mode
  19998. && this._cache.minZ === this.minZ
  19999. && this._cache.maxZ === this.maxZ;
  20000. if (!check) {
  20001. return false;
  20002. }
  20003. var engine = this.getEngine();
  20004. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20005. check = this._cache.fov === this.fov
  20006. && this._cache.fovMode === this.fovMode
  20007. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20008. }
  20009. else {
  20010. check = this._cache.orthoLeft === this.orthoLeft
  20011. && this._cache.orthoRight === this.orthoRight
  20012. && this._cache.orthoBottom === this.orthoBottom
  20013. && this._cache.orthoTop === this.orthoTop
  20014. && this._cache.renderWidth === engine.getRenderWidth()
  20015. && this._cache.renderHeight === engine.getRenderHeight();
  20016. }
  20017. return check;
  20018. };
  20019. // Controls
  20020. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20021. };
  20022. Camera.prototype.detachControl = function (element) {
  20023. };
  20024. Camera.prototype.update = function () {
  20025. this._checkInputs();
  20026. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20027. this._updateRigCameras();
  20028. }
  20029. };
  20030. Camera.prototype._checkInputs = function () {
  20031. this.onAfterCheckInputsObservable.notifyObservers(this);
  20032. };
  20033. Object.defineProperty(Camera.prototype, "rigCameras", {
  20034. get: function () {
  20035. return this._rigCameras;
  20036. },
  20037. enumerable: true,
  20038. configurable: true
  20039. });
  20040. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20041. get: function () {
  20042. return this._rigPostProcess;
  20043. },
  20044. enumerable: true,
  20045. configurable: true
  20046. });
  20047. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20048. // invalidate framebuffer
  20049. if (this._postProcesses.length > 0) {
  20050. this._postProcesses[0].markTextureDirty();
  20051. }
  20052. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20053. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20054. var cam = this._rigCameras[i];
  20055. var rigPostProcess = cam._rigPostProcess;
  20056. // for VR rig, there does not have to be a post process
  20057. if (rigPostProcess) {
  20058. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20059. if (isPass) {
  20060. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20061. cam.isIntermediate = this._postProcesses.length === 0;
  20062. }
  20063. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20064. rigPostProcess.markTextureDirty();
  20065. }
  20066. else {
  20067. cam._postProcesses = this._postProcesses.slice(0);
  20068. }
  20069. }
  20070. };
  20071. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20072. if (insertAt === void 0) { insertAt = null; }
  20073. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20074. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20075. return 0;
  20076. }
  20077. if (insertAt == null || insertAt < 0) {
  20078. this._postProcesses.push(postProcess);
  20079. }
  20080. else {
  20081. this._postProcesses.splice(insertAt, 0, postProcess);
  20082. }
  20083. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20084. return this._postProcesses.indexOf(postProcess);
  20085. };
  20086. Camera.prototype.detachPostProcess = function (postProcess) {
  20087. var idx = this._postProcesses.indexOf(postProcess);
  20088. if (idx !== -1) {
  20089. this._postProcesses.splice(idx, 1);
  20090. }
  20091. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20092. };
  20093. Camera.prototype.getWorldMatrix = function () {
  20094. if (!this._worldMatrix) {
  20095. this._worldMatrix = BABYLON.Matrix.Identity();
  20096. }
  20097. var viewMatrix = this.getViewMatrix();
  20098. viewMatrix.invertToRef(this._worldMatrix);
  20099. return this._worldMatrix;
  20100. };
  20101. Camera.prototype._getViewMatrix = function () {
  20102. return BABYLON.Matrix.Identity();
  20103. };
  20104. Camera.prototype.getViewMatrix = function (force) {
  20105. if (!force && this._isSynchronizedViewMatrix()) {
  20106. return this._computedViewMatrix;
  20107. }
  20108. this.updateCache();
  20109. this._computedViewMatrix = this._getViewMatrix();
  20110. this._currentRenderId = this.getScene().getRenderId();
  20111. this._refreshFrustumPlanes = true;
  20112. if (!this.parent || !this.parent.getWorldMatrix) {
  20113. this._globalPosition.copyFrom(this.position);
  20114. }
  20115. else {
  20116. if (!this._worldMatrix) {
  20117. this._worldMatrix = BABYLON.Matrix.Identity();
  20118. }
  20119. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20120. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20121. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20122. this._computedViewMatrix.invert();
  20123. this._markSyncedWithParent();
  20124. }
  20125. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20126. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20127. }
  20128. this.onViewMatrixChangedObservable.notifyObservers(this);
  20129. return this._computedViewMatrix;
  20130. };
  20131. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20132. this._doNotComputeProjectionMatrix = true;
  20133. if (projection !== undefined) {
  20134. this._projectionMatrix = projection;
  20135. }
  20136. };
  20137. ;
  20138. Camera.prototype.unfreezeProjectionMatrix = function () {
  20139. this._doNotComputeProjectionMatrix = false;
  20140. };
  20141. ;
  20142. Camera.prototype.getProjectionMatrix = function (force) {
  20143. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20144. return this._projectionMatrix;
  20145. }
  20146. // Cache
  20147. this._cache.mode = this.mode;
  20148. this._cache.minZ = this.minZ;
  20149. this._cache.maxZ = this.maxZ;
  20150. // Matrix
  20151. this._refreshFrustumPlanes = true;
  20152. var engine = this.getEngine();
  20153. var scene = this.getScene();
  20154. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20155. this._cache.fov = this.fov;
  20156. this._cache.fovMode = this.fovMode;
  20157. this._cache.aspectRatio = engine.getAspectRatio(this);
  20158. if (this.minZ <= 0) {
  20159. this.minZ = 0.1;
  20160. }
  20161. if (scene.useRightHandedSystem) {
  20162. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20163. }
  20164. else {
  20165. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20166. }
  20167. }
  20168. else {
  20169. var halfWidth = engine.getRenderWidth() / 2.0;
  20170. var halfHeight = engine.getRenderHeight() / 2.0;
  20171. if (scene.useRightHandedSystem) {
  20172. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20173. }
  20174. else {
  20175. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20176. }
  20177. this._cache.orthoLeft = this.orthoLeft;
  20178. this._cache.orthoRight = this.orthoRight;
  20179. this._cache.orthoBottom = this.orthoBottom;
  20180. this._cache.orthoTop = this.orthoTop;
  20181. this._cache.renderWidth = engine.getRenderWidth();
  20182. this._cache.renderHeight = engine.getRenderHeight();
  20183. }
  20184. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20185. return this._projectionMatrix;
  20186. };
  20187. Camera.prototype.getTranformationMatrix = function () {
  20188. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20189. return this._transformMatrix;
  20190. };
  20191. Camera.prototype.updateFrustumPlanes = function () {
  20192. if (!this._refreshFrustumPlanes) {
  20193. return;
  20194. }
  20195. this.getTranformationMatrix();
  20196. if (!this._frustumPlanes) {
  20197. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20198. }
  20199. else {
  20200. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20201. }
  20202. this._refreshFrustumPlanes = false;
  20203. };
  20204. Camera.prototype.isInFrustum = function (target) {
  20205. this.updateFrustumPlanes();
  20206. return target.isInFrustum(this._frustumPlanes);
  20207. };
  20208. Camera.prototype.isCompletelyInFrustum = function (target) {
  20209. this.updateFrustumPlanes();
  20210. return target.isCompletelyInFrustum(this._frustumPlanes);
  20211. };
  20212. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20213. if (length === void 0) { length = 100; }
  20214. if (!transform) {
  20215. transform = this.getWorldMatrix();
  20216. }
  20217. if (!origin) {
  20218. origin = this.position;
  20219. }
  20220. var forward = new BABYLON.Vector3(0, 0, 1);
  20221. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20222. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20223. return new BABYLON.Ray(origin, direction, length);
  20224. };
  20225. Camera.prototype.dispose = function () {
  20226. // Observables
  20227. this.onViewMatrixChangedObservable.clear();
  20228. this.onProjectionMatrixChangedObservable.clear();
  20229. this.onAfterCheckInputsObservable.clear();
  20230. this.onRestoreStateObservable.clear();
  20231. // Inputs
  20232. if (this.inputs) {
  20233. this.inputs.clear();
  20234. }
  20235. // Animations
  20236. this.getScene().stopAnimation(this);
  20237. // Remove from scene
  20238. this.getScene().removeCamera(this);
  20239. while (this._rigCameras.length > 0) {
  20240. var camera = this._rigCameras.pop();
  20241. if (camera) {
  20242. camera.dispose();
  20243. }
  20244. }
  20245. // Postprocesses
  20246. if (this._rigPostProcess) {
  20247. this._rigPostProcess.dispose(this);
  20248. this._rigPostProcess = null;
  20249. this._postProcesses = [];
  20250. }
  20251. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20252. this._rigPostProcess = null;
  20253. this._postProcesses = [];
  20254. }
  20255. else {
  20256. var i = this._postProcesses.length;
  20257. while (--i >= 0) {
  20258. this._postProcesses[i].dispose(this);
  20259. }
  20260. }
  20261. // Render targets
  20262. var i = this.customRenderTargets.length;
  20263. while (--i >= 0) {
  20264. this.customRenderTargets[i].dispose();
  20265. }
  20266. this.customRenderTargets = [];
  20267. // Active Meshes
  20268. this._activeMeshes.dispose();
  20269. _super.prototype.dispose.call(this);
  20270. };
  20271. Object.defineProperty(Camera.prototype, "leftCamera", {
  20272. // ---- Camera rigs section ----
  20273. get: function () {
  20274. if (this._rigCameras.length < 1) {
  20275. return null;
  20276. }
  20277. return this._rigCameras[0];
  20278. },
  20279. enumerable: true,
  20280. configurable: true
  20281. });
  20282. Object.defineProperty(Camera.prototype, "rightCamera", {
  20283. get: function () {
  20284. if (this._rigCameras.length < 2) {
  20285. return null;
  20286. }
  20287. return this._rigCameras[1];
  20288. },
  20289. enumerable: true,
  20290. configurable: true
  20291. });
  20292. Camera.prototype.getLeftTarget = function () {
  20293. if (this._rigCameras.length < 1) {
  20294. return null;
  20295. }
  20296. return this._rigCameras[0].getTarget();
  20297. };
  20298. Camera.prototype.getRightTarget = function () {
  20299. if (this._rigCameras.length < 2) {
  20300. return null;
  20301. }
  20302. return this._rigCameras[1].getTarget();
  20303. };
  20304. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20305. if (this.cameraRigMode === mode) {
  20306. return;
  20307. }
  20308. while (this._rigCameras.length > 0) {
  20309. var camera = this._rigCameras.pop();
  20310. if (camera) {
  20311. camera.dispose();
  20312. }
  20313. }
  20314. this.cameraRigMode = mode;
  20315. this._cameraRigParams = {};
  20316. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20317. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20318. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20319. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20320. // create the rig cameras, unless none
  20321. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20322. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20323. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20324. if (leftCamera && rightCamera) {
  20325. this._rigCameras.push(leftCamera);
  20326. this._rigCameras.push(rightCamera);
  20327. }
  20328. }
  20329. switch (this.cameraRigMode) {
  20330. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20331. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20332. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20333. break;
  20334. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20335. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20336. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20337. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20338. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20339. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20340. break;
  20341. case Camera.RIG_MODE_VR:
  20342. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20343. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20344. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20345. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20346. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20347. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20348. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20349. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20350. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20351. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20352. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20353. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20354. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20355. if (metrics.compensateDistortion) {
  20356. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20357. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20358. }
  20359. break;
  20360. case Camera.RIG_MODE_WEBVR:
  20361. if (rigParams.vrDisplay) {
  20362. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20363. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20364. //Left eye
  20365. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20366. this._rigCameras[0].setCameraRigParameter("left", true);
  20367. //leaving this for future reference
  20368. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20369. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20370. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20371. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20372. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20373. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20374. this._rigCameras[0].parent = this;
  20375. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20376. //Right eye
  20377. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20378. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20379. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20380. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20381. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20382. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20383. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20384. this._rigCameras[1].parent = this;
  20385. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20386. if (Camera.UseAlternateWebVRRendering) {
  20387. this._rigCameras[1]._skipRendering = true;
  20388. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20389. }
  20390. }
  20391. break;
  20392. }
  20393. this._cascadePostProcessesToRigCams();
  20394. this.update();
  20395. };
  20396. Camera.prototype._getVRProjectionMatrix = function () {
  20397. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20398. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20399. return this._projectionMatrix;
  20400. };
  20401. Camera.prototype._updateCameraRotationMatrix = function () {
  20402. //Here for WebVR
  20403. };
  20404. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20405. //Here for WebVR
  20406. };
  20407. /**
  20408. * This function MUST be overwritten by the different WebVR cameras available.
  20409. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20410. */
  20411. Camera.prototype._getWebVRProjectionMatrix = function () {
  20412. return BABYLON.Matrix.Identity();
  20413. };
  20414. /**
  20415. * This function MUST be overwritten by the different WebVR cameras available.
  20416. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20417. */
  20418. Camera.prototype._getWebVRViewMatrix = function () {
  20419. return BABYLON.Matrix.Identity();
  20420. };
  20421. Camera.prototype.setCameraRigParameter = function (name, value) {
  20422. if (!this._cameraRigParams) {
  20423. this._cameraRigParams = {};
  20424. }
  20425. this._cameraRigParams[name] = value;
  20426. //provisionnally:
  20427. if (name === "interaxialDistance") {
  20428. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20429. }
  20430. };
  20431. /**
  20432. * needs to be overridden by children so sub has required properties to be copied
  20433. */
  20434. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20435. return null;
  20436. };
  20437. /**
  20438. * May need to be overridden by children
  20439. */
  20440. Camera.prototype._updateRigCameras = function () {
  20441. for (var i = 0; i < this._rigCameras.length; i++) {
  20442. this._rigCameras[i].minZ = this.minZ;
  20443. this._rigCameras[i].maxZ = this.maxZ;
  20444. this._rigCameras[i].fov = this.fov;
  20445. }
  20446. // only update viewport when ANAGLYPH
  20447. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20448. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20449. }
  20450. };
  20451. Camera.prototype._setupInputs = function () {
  20452. };
  20453. Camera.prototype.serialize = function () {
  20454. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20455. // Type
  20456. serializationObject.type = this.getClassName();
  20457. // Parent
  20458. if (this.parent) {
  20459. serializationObject.parentId = this.parent.id;
  20460. }
  20461. if (this.inputs) {
  20462. this.inputs.serialize(serializationObject);
  20463. }
  20464. // Animations
  20465. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20466. serializationObject.ranges = this.serializeAnimationRanges();
  20467. return serializationObject;
  20468. };
  20469. Camera.prototype.clone = function (name) {
  20470. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20471. };
  20472. Camera.prototype.getDirection = function (localAxis) {
  20473. var result = BABYLON.Vector3.Zero();
  20474. this.getDirectionToRef(localAxis, result);
  20475. return result;
  20476. };
  20477. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20478. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20479. };
  20480. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20481. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20482. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20483. switch (type) {
  20484. case "ArcRotateCamera":
  20485. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20486. case "DeviceOrientationCamera":
  20487. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20488. case "FollowCamera":
  20489. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20490. case "ArcFollowCamera":
  20491. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20492. case "GamepadCamera":
  20493. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20494. case "TouchCamera":
  20495. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20496. case "VirtualJoysticksCamera":
  20497. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20498. case "WebVRFreeCamera":
  20499. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20500. case "WebVRGamepadCamera":
  20501. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20502. case "VRDeviceOrientationFreeCamera":
  20503. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20504. case "VRDeviceOrientationGamepadCamera":
  20505. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20506. case "AnaglyphArcRotateCamera":
  20507. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20508. case "AnaglyphFreeCamera":
  20509. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20510. case "AnaglyphGamepadCamera":
  20511. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20512. case "AnaglyphUniversalCamera":
  20513. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20514. case "StereoscopicArcRotateCamera":
  20515. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20516. case "StereoscopicFreeCamera":
  20517. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20518. case "StereoscopicGamepadCamera":
  20519. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20520. case "StereoscopicUniversalCamera":
  20521. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20522. case "FreeCamera":// Forcing Universal here
  20523. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20524. default:// Universal Camera is the default value
  20525. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20526. }
  20527. };
  20528. Camera.prototype.computeWorldMatrix = function () {
  20529. return this.getWorldMatrix();
  20530. };
  20531. Camera.Parse = function (parsedCamera, scene) {
  20532. var type = parsedCamera.type;
  20533. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20534. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20535. // Parent
  20536. if (parsedCamera.parentId) {
  20537. camera._waitingParentId = parsedCamera.parentId;
  20538. }
  20539. //If camera has an input manager, let it parse inputs settings
  20540. if (camera.inputs) {
  20541. camera.inputs.parse(parsedCamera);
  20542. camera._setupInputs();
  20543. }
  20544. if (camera.setPosition) {
  20545. camera.position.copyFromFloats(0, 0, 0);
  20546. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20547. }
  20548. // Target
  20549. if (parsedCamera.target) {
  20550. if (camera.setTarget) {
  20551. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20552. }
  20553. }
  20554. // Apply 3d rig, when found
  20555. if (parsedCamera.cameraRigMode) {
  20556. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20557. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20558. }
  20559. // Animations
  20560. if (parsedCamera.animations) {
  20561. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20562. var parsedAnimation = parsedCamera.animations[animationIndex];
  20563. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20564. }
  20565. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20566. }
  20567. if (parsedCamera.autoAnimate) {
  20568. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20569. }
  20570. return camera;
  20571. };
  20572. // Statics
  20573. Camera._PERSPECTIVE_CAMERA = 0;
  20574. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20575. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20576. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20577. Camera._RIG_MODE_NONE = 0;
  20578. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20579. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20580. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20581. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20582. Camera._RIG_MODE_VR = 20;
  20583. Camera._RIG_MODE_WEBVR = 21;
  20584. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20585. Camera.UseAlternateWebVRRendering = false;
  20586. __decorate([
  20587. BABYLON.serializeAsVector3()
  20588. ], Camera.prototype, "position", void 0);
  20589. __decorate([
  20590. BABYLON.serializeAsVector3()
  20591. ], Camera.prototype, "upVector", void 0);
  20592. __decorate([
  20593. BABYLON.serialize()
  20594. ], Camera.prototype, "orthoLeft", void 0);
  20595. __decorate([
  20596. BABYLON.serialize()
  20597. ], Camera.prototype, "orthoRight", void 0);
  20598. __decorate([
  20599. BABYLON.serialize()
  20600. ], Camera.prototype, "orthoBottom", void 0);
  20601. __decorate([
  20602. BABYLON.serialize()
  20603. ], Camera.prototype, "orthoTop", void 0);
  20604. __decorate([
  20605. BABYLON.serialize()
  20606. ], Camera.prototype, "fov", void 0);
  20607. __decorate([
  20608. BABYLON.serialize()
  20609. ], Camera.prototype, "minZ", void 0);
  20610. __decorate([
  20611. BABYLON.serialize()
  20612. ], Camera.prototype, "maxZ", void 0);
  20613. __decorate([
  20614. BABYLON.serialize()
  20615. ], Camera.prototype, "inertia", void 0);
  20616. __decorate([
  20617. BABYLON.serialize()
  20618. ], Camera.prototype, "mode", void 0);
  20619. __decorate([
  20620. BABYLON.serialize()
  20621. ], Camera.prototype, "layerMask", void 0);
  20622. __decorate([
  20623. BABYLON.serialize()
  20624. ], Camera.prototype, "fovMode", void 0);
  20625. __decorate([
  20626. BABYLON.serialize()
  20627. ], Camera.prototype, "cameraRigMode", void 0);
  20628. __decorate([
  20629. BABYLON.serialize()
  20630. ], Camera.prototype, "interaxialDistance", void 0);
  20631. __decorate([
  20632. BABYLON.serialize()
  20633. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20634. return Camera;
  20635. }(BABYLON.Node));
  20636. BABYLON.Camera = Camera;
  20637. })(BABYLON || (BABYLON = {}));
  20638. //# sourceMappingURL=babylon.camera.js.map
  20639. var BABYLON;
  20640. (function (BABYLON) {
  20641. var RenderingManager = /** @class */ (function () {
  20642. function RenderingManager(scene) {
  20643. this._renderingGroups = new Array();
  20644. this._autoClearDepthStencil = {};
  20645. this._customOpaqueSortCompareFn = {};
  20646. this._customAlphaTestSortCompareFn = {};
  20647. this._customTransparentSortCompareFn = {};
  20648. this._renderinGroupInfo = null;
  20649. this._scene = scene;
  20650. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20651. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20652. }
  20653. }
  20654. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20655. if (depth === void 0) { depth = true; }
  20656. if (stencil === void 0) { stencil = true; }
  20657. if (this._depthStencilBufferAlreadyCleaned) {
  20658. return;
  20659. }
  20660. this._scene.getEngine().clear(null, false, depth, stencil);
  20661. this._depthStencilBufferAlreadyCleaned = true;
  20662. };
  20663. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20664. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20665. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20666. var info = null;
  20667. if (observable) {
  20668. if (!this._renderinGroupInfo) {
  20669. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20670. }
  20671. info = this._renderinGroupInfo;
  20672. info.scene = this._scene;
  20673. info.camera = this._scene.activeCamera;
  20674. }
  20675. // Dispatch sprites
  20676. if (renderSprites) {
  20677. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20678. var manager = this._scene.spriteManagers[index];
  20679. this.dispatchSprites(manager);
  20680. }
  20681. }
  20682. // Render
  20683. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20684. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20685. var renderingGroup = this._renderingGroups[index];
  20686. if (!renderingGroup && !observable)
  20687. continue;
  20688. var renderingGroupMask = 0;
  20689. // Fire PRECLEAR stage
  20690. if (observable && info) {
  20691. renderingGroupMask = Math.pow(2, index);
  20692. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20693. info.renderingGroupId = index;
  20694. observable.notifyObservers(info, renderingGroupMask);
  20695. }
  20696. // Clear depth/stencil if needed
  20697. if (RenderingManager.AUTOCLEAR) {
  20698. var autoClear = this._autoClearDepthStencil[index];
  20699. if (autoClear && autoClear.autoClear) {
  20700. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20701. }
  20702. }
  20703. if (observable && info) {
  20704. // Fire PREOPAQUE stage
  20705. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20706. observable.notifyObservers(info, renderingGroupMask);
  20707. // Fire PRETRANSPARENT stage
  20708. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20709. observable.notifyObservers(info, renderingGroupMask);
  20710. }
  20711. if (renderingGroup)
  20712. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20713. // Fire POSTTRANSPARENT stage
  20714. if (observable && info) {
  20715. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20716. observable.notifyObservers(info, renderingGroupMask);
  20717. }
  20718. }
  20719. };
  20720. RenderingManager.prototype.reset = function () {
  20721. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20722. var renderingGroup = this._renderingGroups[index];
  20723. if (renderingGroup) {
  20724. renderingGroup.prepare();
  20725. }
  20726. }
  20727. };
  20728. RenderingManager.prototype.dispose = function () {
  20729. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20730. var renderingGroup = this._renderingGroups[index];
  20731. if (renderingGroup) {
  20732. renderingGroup.dispose();
  20733. }
  20734. }
  20735. this._renderingGroups.length = 0;
  20736. };
  20737. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20738. if (this._renderingGroups[renderingGroupId] === undefined) {
  20739. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20740. }
  20741. };
  20742. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20743. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20744. this._prepareRenderingGroup(renderingGroupId);
  20745. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20746. };
  20747. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20748. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20749. this._prepareRenderingGroup(renderingGroupId);
  20750. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20751. };
  20752. /**
  20753. * @param subMesh The submesh to dispatch
  20754. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20755. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20756. */
  20757. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20758. if (mesh === undefined) {
  20759. mesh = subMesh.getMesh();
  20760. }
  20761. var renderingGroupId = mesh.renderingGroupId || 0;
  20762. this._prepareRenderingGroup(renderingGroupId);
  20763. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20764. };
  20765. /**
  20766. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20767. * This allowed control for front to back rendering or reversly depending of the special needs.
  20768. *
  20769. * @param renderingGroupId The rendering group id corresponding to its index
  20770. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20771. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20772. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20773. */
  20774. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20775. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20776. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20777. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20778. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20779. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20780. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20781. if (this._renderingGroups[renderingGroupId]) {
  20782. var group = this._renderingGroups[renderingGroupId];
  20783. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20784. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20785. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20786. }
  20787. };
  20788. /**
  20789. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20790. *
  20791. * @param renderingGroupId The rendering group id corresponding to its index
  20792. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20793. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20794. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20795. */
  20796. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20797. if (depth === void 0) { depth = true; }
  20798. if (stencil === void 0) { stencil = true; }
  20799. this._autoClearDepthStencil[renderingGroupId] = {
  20800. autoClear: autoClearDepthStencil,
  20801. depth: depth,
  20802. stencil: stencil
  20803. };
  20804. };
  20805. /**
  20806. * The max id used for rendering groups (not included)
  20807. */
  20808. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20809. /**
  20810. * The min id used for rendering groups (included)
  20811. */
  20812. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20813. /**
  20814. * Used to globally prevent autoclearing scenes.
  20815. */
  20816. RenderingManager.AUTOCLEAR = true;
  20817. return RenderingManager;
  20818. }());
  20819. BABYLON.RenderingManager = RenderingManager;
  20820. })(BABYLON || (BABYLON = {}));
  20821. //# sourceMappingURL=babylon.renderingManager.js.map
  20822. var BABYLON;
  20823. (function (BABYLON) {
  20824. var RenderingGroup = /** @class */ (function () {
  20825. /**
  20826. * Creates a new rendering group.
  20827. * @param index The rendering group index
  20828. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20829. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20830. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20831. */
  20832. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20833. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20834. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20835. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20836. this.index = index;
  20837. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20838. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20839. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20840. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20841. this._particleSystems = new BABYLON.SmartArray(256);
  20842. this._spriteManagers = new BABYLON.SmartArray(256);
  20843. this._edgesRenderers = new BABYLON.SmartArray(16);
  20844. this._scene = scene;
  20845. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20846. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20847. this.transparentSortCompareFn = transparentSortCompareFn;
  20848. }
  20849. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20850. /**
  20851. * Set the opaque sort comparison function.
  20852. * If null the sub meshes will be render in the order they were created
  20853. */
  20854. set: function (value) {
  20855. this._opaqueSortCompareFn = value;
  20856. if (value) {
  20857. this._renderOpaque = this.renderOpaqueSorted;
  20858. }
  20859. else {
  20860. this._renderOpaque = RenderingGroup.renderUnsorted;
  20861. }
  20862. },
  20863. enumerable: true,
  20864. configurable: true
  20865. });
  20866. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20867. /**
  20868. * Set the alpha test sort comparison function.
  20869. * If null the sub meshes will be render in the order they were created
  20870. */
  20871. set: function (value) {
  20872. this._alphaTestSortCompareFn = value;
  20873. if (value) {
  20874. this._renderAlphaTest = this.renderAlphaTestSorted;
  20875. }
  20876. else {
  20877. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20878. }
  20879. },
  20880. enumerable: true,
  20881. configurable: true
  20882. });
  20883. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20884. /**
  20885. * Set the transparent sort comparison function.
  20886. * If null the sub meshes will be render in the order they were created
  20887. */
  20888. set: function (value) {
  20889. if (value) {
  20890. this._transparentSortCompareFn = value;
  20891. }
  20892. else {
  20893. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20894. }
  20895. this._renderTransparent = this.renderTransparentSorted;
  20896. },
  20897. enumerable: true,
  20898. configurable: true
  20899. });
  20900. /**
  20901. * Render all the sub meshes contained in the group.
  20902. * @param customRenderFunction Used to override the default render behaviour of the group.
  20903. * @returns true if rendered some submeshes.
  20904. */
  20905. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20906. if (customRenderFunction) {
  20907. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20908. return;
  20909. }
  20910. var engine = this._scene.getEngine();
  20911. // Depth only
  20912. if (this._depthOnlySubMeshes.length !== 0) {
  20913. engine.setColorWrite(false);
  20914. this._renderAlphaTest(this._depthOnlySubMeshes);
  20915. engine.setColorWrite(true);
  20916. }
  20917. // Opaque
  20918. if (this._opaqueSubMeshes.length !== 0) {
  20919. this._renderOpaque(this._opaqueSubMeshes);
  20920. }
  20921. // Alpha test
  20922. if (this._alphaTestSubMeshes.length !== 0) {
  20923. this._renderAlphaTest(this._alphaTestSubMeshes);
  20924. }
  20925. var stencilState = engine.getStencilBuffer();
  20926. engine.setStencilBuffer(false);
  20927. // Sprites
  20928. if (renderSprites) {
  20929. this._renderSprites();
  20930. }
  20931. // Particles
  20932. if (renderParticles) {
  20933. this._renderParticles(activeMeshes);
  20934. }
  20935. if (this.onBeforeTransparentRendering) {
  20936. this.onBeforeTransparentRendering();
  20937. }
  20938. // Transparent
  20939. if (this._transparentSubMeshes.length !== 0) {
  20940. this._renderTransparent(this._transparentSubMeshes);
  20941. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20942. }
  20943. // Set back stencil to false in case it changes before the edge renderer.
  20944. engine.setStencilBuffer(false);
  20945. // Edges
  20946. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20947. this._edgesRenderers.data[edgesRendererIndex].render();
  20948. }
  20949. // Restore Stencil state.
  20950. engine.setStencilBuffer(stencilState);
  20951. };
  20952. /**
  20953. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20954. * @param subMeshes The submeshes to render
  20955. */
  20956. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20957. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20958. };
  20959. /**
  20960. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20961. * @param subMeshes The submeshes to render
  20962. */
  20963. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20964. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20965. };
  20966. /**
  20967. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20968. * @param subMeshes The submeshes to render
  20969. */
  20970. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20971. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20972. };
  20973. /**
  20974. * Renders the submeshes in a specified order.
  20975. * @param subMeshes The submeshes to sort before render
  20976. * @param sortCompareFn The comparison function use to sort
  20977. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20978. * @param transparent Specifies to activate blending if true
  20979. */
  20980. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20981. var subIndex = 0;
  20982. var subMesh;
  20983. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20984. for (; subIndex < subMeshes.length; subIndex++) {
  20985. subMesh = subMeshes.data[subIndex];
  20986. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20987. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20988. }
  20989. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20990. if (sortCompareFn) {
  20991. sortedArray.sort(sortCompareFn);
  20992. }
  20993. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20994. subMesh = sortedArray[subIndex];
  20995. if (transparent) {
  20996. var material = subMesh.getMaterial();
  20997. if (material && material.needDepthPrePass) {
  20998. var engine = material.getScene().getEngine();
  20999. engine.setColorWrite(false);
  21000. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21001. subMesh.render(false);
  21002. engine.setColorWrite(true);
  21003. }
  21004. }
  21005. subMesh.render(transparent);
  21006. }
  21007. };
  21008. /**
  21009. * Renders the submeshes in the order they were dispatched (no sort applied).
  21010. * @param subMeshes The submeshes to render
  21011. */
  21012. RenderingGroup.renderUnsorted = function (subMeshes) {
  21013. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21014. var submesh = subMeshes.data[subIndex];
  21015. submesh.render(false);
  21016. }
  21017. };
  21018. /**
  21019. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21020. * are rendered back to front if in the same alpha index.
  21021. *
  21022. * @param a The first submesh
  21023. * @param b The second submesh
  21024. * @returns The result of the comparison
  21025. */
  21026. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21027. // Alpha index first
  21028. if (a._alphaIndex > b._alphaIndex) {
  21029. return 1;
  21030. }
  21031. if (a._alphaIndex < b._alphaIndex) {
  21032. return -1;
  21033. }
  21034. // Then distance to camera
  21035. return RenderingGroup.backToFrontSortCompare(a, b);
  21036. };
  21037. /**
  21038. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21039. * are rendered back to front.
  21040. *
  21041. * @param a The first submesh
  21042. * @param b The second submesh
  21043. * @returns The result of the comparison
  21044. */
  21045. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21046. // Then distance to camera
  21047. if (a._distanceToCamera < b._distanceToCamera) {
  21048. return 1;
  21049. }
  21050. if (a._distanceToCamera > b._distanceToCamera) {
  21051. return -1;
  21052. }
  21053. return 0;
  21054. };
  21055. /**
  21056. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21057. * are rendered front to back (prevent overdraw).
  21058. *
  21059. * @param a The first submesh
  21060. * @param b The second submesh
  21061. * @returns The result of the comparison
  21062. */
  21063. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21064. // Then distance to camera
  21065. if (a._distanceToCamera < b._distanceToCamera) {
  21066. return -1;
  21067. }
  21068. if (a._distanceToCamera > b._distanceToCamera) {
  21069. return 1;
  21070. }
  21071. return 0;
  21072. };
  21073. /**
  21074. * Resets the different lists of submeshes to prepare a new frame.
  21075. */
  21076. RenderingGroup.prototype.prepare = function () {
  21077. this._opaqueSubMeshes.reset();
  21078. this._transparentSubMeshes.reset();
  21079. this._alphaTestSubMeshes.reset();
  21080. this._depthOnlySubMeshes.reset();
  21081. this._particleSystems.reset();
  21082. this._spriteManagers.reset();
  21083. this._edgesRenderers.reset();
  21084. };
  21085. RenderingGroup.prototype.dispose = function () {
  21086. this._opaqueSubMeshes.dispose();
  21087. this._transparentSubMeshes.dispose();
  21088. this._alphaTestSubMeshes.dispose();
  21089. this._depthOnlySubMeshes.dispose();
  21090. this._particleSystems.dispose();
  21091. this._spriteManagers.dispose();
  21092. this._edgesRenderers.dispose();
  21093. };
  21094. /**
  21095. * Inserts the submesh in its correct queue depending on its material.
  21096. * @param subMesh The submesh to dispatch
  21097. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21098. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21099. */
  21100. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21101. // Get mesh and materials if not provided
  21102. if (mesh === undefined) {
  21103. mesh = subMesh.getMesh();
  21104. }
  21105. if (material === undefined) {
  21106. material = subMesh.getMaterial();
  21107. }
  21108. if (material === null || material === undefined) {
  21109. return;
  21110. }
  21111. if (material.needAlphaBlendingForMesh(mesh)) {
  21112. this._transparentSubMeshes.push(subMesh);
  21113. }
  21114. else if (material.needAlphaTesting()) {
  21115. if (material.needDepthPrePass) {
  21116. this._depthOnlySubMeshes.push(subMesh);
  21117. }
  21118. this._alphaTestSubMeshes.push(subMesh);
  21119. }
  21120. else {
  21121. if (material.needDepthPrePass) {
  21122. this._depthOnlySubMeshes.push(subMesh);
  21123. }
  21124. this._opaqueSubMeshes.push(subMesh); // Opaque
  21125. }
  21126. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21127. this._edgesRenderers.push(mesh._edgesRenderer);
  21128. }
  21129. };
  21130. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21131. this._spriteManagers.push(spriteManager);
  21132. };
  21133. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21134. this._particleSystems.push(particleSystem);
  21135. };
  21136. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21137. if (this._particleSystems.length === 0) {
  21138. return;
  21139. }
  21140. // Particles
  21141. var activeCamera = this._scene.activeCamera;
  21142. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21143. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21144. var particleSystem = this._particleSystems.data[particleIndex];
  21145. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21146. continue;
  21147. }
  21148. var emitter = particleSystem.emitter;
  21149. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21150. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21151. }
  21152. }
  21153. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21154. };
  21155. RenderingGroup.prototype._renderSprites = function () {
  21156. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21157. return;
  21158. }
  21159. // Sprites
  21160. var activeCamera = this._scene.activeCamera;
  21161. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21162. for (var id = 0; id < this._spriteManagers.length; id++) {
  21163. var spriteManager = this._spriteManagers.data[id];
  21164. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21165. spriteManager.render();
  21166. }
  21167. }
  21168. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21169. };
  21170. return RenderingGroup;
  21171. }());
  21172. BABYLON.RenderingGroup = RenderingGroup;
  21173. })(BABYLON || (BABYLON = {}));
  21174. //# sourceMappingURL=babylon.renderingGroup.js.map
  21175. var BABYLON;
  21176. (function (BABYLON) {
  21177. var ClickInfo = /** @class */ (function () {
  21178. function ClickInfo() {
  21179. this._singleClick = false;
  21180. this._doubleClick = false;
  21181. this._hasSwiped = false;
  21182. this._ignore = false;
  21183. }
  21184. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21185. get: function () {
  21186. return this._singleClick;
  21187. },
  21188. set: function (b) {
  21189. this._singleClick = b;
  21190. },
  21191. enumerable: true,
  21192. configurable: true
  21193. });
  21194. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21195. get: function () {
  21196. return this._doubleClick;
  21197. },
  21198. set: function (b) {
  21199. this._doubleClick = b;
  21200. },
  21201. enumerable: true,
  21202. configurable: true
  21203. });
  21204. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21205. get: function () {
  21206. return this._hasSwiped;
  21207. },
  21208. set: function (b) {
  21209. this._hasSwiped = b;
  21210. },
  21211. enumerable: true,
  21212. configurable: true
  21213. });
  21214. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21215. get: function () {
  21216. return this._ignore;
  21217. },
  21218. set: function (b) {
  21219. this._ignore = b;
  21220. },
  21221. enumerable: true,
  21222. configurable: true
  21223. });
  21224. return ClickInfo;
  21225. }());
  21226. /**
  21227. * This class is used by the onRenderingGroupObservable
  21228. */
  21229. var RenderingGroupInfo = /** @class */ (function () {
  21230. function RenderingGroupInfo() {
  21231. }
  21232. /**
  21233. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21234. * This stage will be fired no matter what
  21235. */
  21236. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21237. /**
  21238. * Called before opaque object are rendered.
  21239. * This stage will be fired only if there's 3D Opaque content to render
  21240. */
  21241. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21242. /**
  21243. * Called after the opaque objects are rendered and before the transparent ones
  21244. * This stage will be fired only if there's 3D transparent content to render
  21245. */
  21246. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21247. /**
  21248. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21249. * This stage will be fired no matter what
  21250. */
  21251. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21252. return RenderingGroupInfo;
  21253. }());
  21254. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21255. /**
  21256. * Represents a scene to be rendered by the engine.
  21257. * @see http://doc.babylonjs.com/page.php?p=21911
  21258. */
  21259. var Scene = /** @class */ (function () {
  21260. /**
  21261. * @constructor
  21262. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21263. */
  21264. function Scene(engine) {
  21265. // Members
  21266. this.autoClear = true;
  21267. this.autoClearDepthAndStencil = true;
  21268. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21269. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21270. this.forceWireframe = false;
  21271. this._forcePointsCloud = false;
  21272. this.forceShowBoundingBoxes = false;
  21273. this.animationsEnabled = true;
  21274. this.useConstantAnimationDeltaTime = false;
  21275. this.constantlyUpdateMeshUnderPointer = false;
  21276. this.hoverCursor = "pointer";
  21277. this.defaultCursor = "";
  21278. /**
  21279. * This is used to call preventDefault() on pointer down
  21280. * in order to block unwanted artifacts like system double clicks
  21281. */
  21282. this.preventDefaultOnPointerDown = true;
  21283. // Metadata
  21284. this.metadata = null;
  21285. /**
  21286. * An event triggered when the scene is disposed.
  21287. * @type {BABYLON.Observable}
  21288. */
  21289. this.onDisposeObservable = new BABYLON.Observable();
  21290. /**
  21291. * An event triggered before rendering the scene (right after animations and physics)
  21292. * @type {BABYLON.Observable}
  21293. */
  21294. this.onBeforeRenderObservable = new BABYLON.Observable();
  21295. /**
  21296. * An event triggered after rendering the scene
  21297. * @type {BABYLON.Observable}
  21298. */
  21299. this.onAfterRenderObservable = new BABYLON.Observable();
  21300. /**
  21301. * An event triggered before animating the scene
  21302. * @type {BABYLON.Observable}
  21303. */
  21304. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21305. /**
  21306. * An event triggered after animations processing
  21307. * @type {BABYLON.Observable}
  21308. */
  21309. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21310. /**
  21311. * An event triggered before draw calls are ready to be sent
  21312. * @type {BABYLON.Observable}
  21313. */
  21314. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21315. /**
  21316. * An event triggered after draw calls have been sent
  21317. * @type {BABYLON.Observable}
  21318. */
  21319. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21320. /**
  21321. * An event triggered when physic simulation is about to be run
  21322. * @type {BABYLON.Observable}
  21323. */
  21324. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21325. /**
  21326. * An event triggered when physic simulation has been done
  21327. * @type {BABYLON.Observable}
  21328. */
  21329. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21330. /**
  21331. * An event triggered when the scene is ready
  21332. * @type {BABYLON.Observable}
  21333. */
  21334. this.onReadyObservable = new BABYLON.Observable();
  21335. /**
  21336. * An event triggered before rendering a camera
  21337. * @type {BABYLON.Observable}
  21338. */
  21339. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21340. /**
  21341. * An event triggered after rendering a camera
  21342. * @type {BABYLON.Observable}
  21343. */
  21344. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21345. /**
  21346. * An event triggered when active meshes evaluation is about to start
  21347. * @type {BABYLON.Observable}
  21348. */
  21349. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21350. /**
  21351. * An event triggered when active meshes evaluation is done
  21352. * @type {BABYLON.Observable}
  21353. */
  21354. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21355. /**
  21356. * An event triggered when particles rendering is about to start
  21357. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21358. * @type {BABYLON.Observable}
  21359. */
  21360. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21361. /**
  21362. * An event triggered when particles rendering is done
  21363. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21364. * @type {BABYLON.Observable}
  21365. */
  21366. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21367. /**
  21368. * An event triggered when sprites rendering is about to start
  21369. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21370. * @type {BABYLON.Observable}
  21371. */
  21372. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21373. /**
  21374. * An event triggered when sprites rendering is done
  21375. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21376. * @type {BABYLON.Observable}
  21377. */
  21378. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21379. /**
  21380. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21381. * @type {BABYLON.Observable}
  21382. */
  21383. this.onDataLoadedObservable = new BABYLON.Observable();
  21384. /**
  21385. * An event triggered when a camera is created
  21386. * @type {BABYLON.Observable}
  21387. */
  21388. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21389. /**
  21390. * An event triggered when a camera is removed
  21391. * @type {BABYLON.Observable}
  21392. */
  21393. this.onCameraRemovedObservable = new BABYLON.Observable();
  21394. /**
  21395. * An event triggered when a light is created
  21396. * @type {BABYLON.Observable}
  21397. */
  21398. this.onNewLightAddedObservable = new BABYLON.Observable();
  21399. /**
  21400. * An event triggered when a light is removed
  21401. * @type {BABYLON.Observable}
  21402. */
  21403. this.onLightRemovedObservable = new BABYLON.Observable();
  21404. /**
  21405. * An event triggered when a geometry is created
  21406. * @type {BABYLON.Observable}
  21407. */
  21408. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21409. /**
  21410. * An event triggered when a geometry is removed
  21411. * @type {BABYLON.Observable}
  21412. */
  21413. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21414. /**
  21415. * An event triggered when a transform node is created
  21416. * @type {BABYLON.Observable}
  21417. */
  21418. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21419. /**
  21420. * An event triggered when a transform node is removed
  21421. * @type {BABYLON.Observable}
  21422. */
  21423. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21424. /**
  21425. * An event triggered when a mesh is created
  21426. * @type {BABYLON.Observable}
  21427. */
  21428. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21429. /**
  21430. * An event triggered when a mesh is removed
  21431. * @type {BABYLON.Observable}
  21432. */
  21433. this.onMeshRemovedObservable = new BABYLON.Observable();
  21434. /**
  21435. * An event triggered when render targets are about to be rendered
  21436. * Can happen multiple times per frame.
  21437. * @type {BABYLON.Observable}
  21438. */
  21439. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21440. /**
  21441. * An event triggered when render targets were rendered.
  21442. * Can happen multiple times per frame.
  21443. * @type {BABYLON.Observable}
  21444. */
  21445. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21446. /**
  21447. * An event triggered before calculating deterministic simulation step
  21448. * @type {BABYLON.Observable}
  21449. */
  21450. this.onBeforeStepObservable = new BABYLON.Observable();
  21451. /**
  21452. * An event triggered after calculating deterministic simulation step
  21453. * @type {BABYLON.Observable}
  21454. */
  21455. this.onAfterStepObservable = new BABYLON.Observable();
  21456. /**
  21457. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21458. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21459. * 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)
  21460. */
  21461. this.onRenderingGroupObservable = new BABYLON.Observable();
  21462. // Animations
  21463. this.animations = [];
  21464. /**
  21465. * 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).
  21466. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21467. */
  21468. this.onPrePointerObservable = new BABYLON.Observable();
  21469. /**
  21470. * Observable event triggered each time an input event is received from the rendering canvas
  21471. */
  21472. this.onPointerObservable = new BABYLON.Observable();
  21473. this._meshPickProceed = false;
  21474. this._currentPickResult = null;
  21475. this._previousPickResult = null;
  21476. this._totalPointersPressed = 0;
  21477. this._doubleClickOccured = false;
  21478. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21479. this.cameraToUseForPointers = null;
  21480. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21481. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21482. this._startingPointerTime = 0;
  21483. this._previousStartingPointerTime = 0;
  21484. // Deterministic lockstep
  21485. this._timeAccumulator = 0;
  21486. this._currentStepId = 0;
  21487. this._currentInternalStep = 0;
  21488. // Keyboard
  21489. /**
  21490. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21491. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21492. */
  21493. this.onPreKeyboardObservable = new BABYLON.Observable();
  21494. /**
  21495. * Observable event triggered each time an keyboard event is received from the hosting window
  21496. */
  21497. this.onKeyboardObservable = new BABYLON.Observable();
  21498. // Coordinate system
  21499. /**
  21500. * use right-handed coordinate system on this scene.
  21501. * @type {boolean}
  21502. */
  21503. this._useRightHandedSystem = false;
  21504. // Fog
  21505. this._fogEnabled = true;
  21506. this._fogMode = Scene.FOGMODE_NONE;
  21507. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21508. this.fogDensity = 0.1;
  21509. this.fogStart = 0;
  21510. this.fogEnd = 1000.0;
  21511. // Lights
  21512. /**
  21513. * is shadow enabled on this scene.
  21514. * @type {boolean}
  21515. */
  21516. this._shadowsEnabled = true;
  21517. /**
  21518. * is light enabled on this scene.
  21519. * @type {boolean}
  21520. */
  21521. this._lightsEnabled = true;
  21522. /**
  21523. * All of the lights added to this scene.
  21524. * @see BABYLON.Light
  21525. * @type {BABYLON.Light[]}
  21526. */
  21527. this.lights = new Array();
  21528. // Cameras
  21529. /** All of the cameras added to this scene. */
  21530. this.cameras = new Array();
  21531. /** All of the active cameras added to this scene. */
  21532. this.activeCameras = new Array();
  21533. // Meshes
  21534. /**
  21535. * All of the tranform nodes added to this scene.
  21536. * @see BABYLON.TransformNode
  21537. * @type {BABYLON.TransformNode[]}
  21538. */
  21539. this.transformNodes = new Array();
  21540. /**
  21541. * All of the (abstract) meshes added to this scene.
  21542. * @see BABYLON.AbstractMesh
  21543. * @type {BABYLON.AbstractMesh[]}
  21544. */
  21545. this.meshes = new Array();
  21546. /**
  21547. * All of the animation groups added to this scene.
  21548. * @see BABYLON.AnimationGroup
  21549. * @type {BABYLON.AnimationGroup[]}
  21550. */
  21551. this.animationGroups = new Array();
  21552. // Geometries
  21553. this._geometries = new Array();
  21554. this.materials = new Array();
  21555. this.multiMaterials = new Array();
  21556. // Textures
  21557. this._texturesEnabled = true;
  21558. this.textures = new Array();
  21559. // Particles
  21560. this.particlesEnabled = true;
  21561. this.particleSystems = new Array();
  21562. // Sprites
  21563. this.spritesEnabled = true;
  21564. this.spriteManagers = new Array();
  21565. /**
  21566. * The list of layers (background and foreground) of the scene.
  21567. */
  21568. this.layers = new Array();
  21569. /**
  21570. * The list of effect layers (highlights/glow) contained in the scene.
  21571. */
  21572. this.effectLayers = new Array();
  21573. // Skeletons
  21574. this._skeletonsEnabled = true;
  21575. this.skeletons = new Array();
  21576. // Morph targets
  21577. this.morphTargetManagers = new Array();
  21578. // Lens flares
  21579. this.lensFlaresEnabled = true;
  21580. this.lensFlareSystems = new Array();
  21581. // Collisions
  21582. this.collisionsEnabled = true;
  21583. /** Defines the gravity applied to this scene */
  21584. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21585. // Postprocesses
  21586. this.postProcesses = new Array();
  21587. this.postProcessesEnabled = true;
  21588. // Customs render targets
  21589. this.renderTargetsEnabled = true;
  21590. this.dumpNextRenderTargets = false;
  21591. this.customRenderTargets = new Array();
  21592. // Imported meshes
  21593. this.importedMeshesFiles = new Array();
  21594. // Probes
  21595. this.probesEnabled = true;
  21596. this.reflectionProbes = new Array();
  21597. this._actionManagers = new Array();
  21598. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21599. // Procedural textures
  21600. this.proceduralTexturesEnabled = true;
  21601. this._proceduralTextures = new Array();
  21602. this.soundTracks = new Array();
  21603. this._audioEnabled = true;
  21604. this._headphone = false;
  21605. // Performance counters
  21606. this._totalVertices = new BABYLON.PerfCounter();
  21607. this._activeIndices = new BABYLON.PerfCounter();
  21608. this._activeParticles = new BABYLON.PerfCounter();
  21609. this._activeBones = new BABYLON.PerfCounter();
  21610. this._animationTime = 0;
  21611. this.animationTimeScale = 1;
  21612. this._renderId = 0;
  21613. this._executeWhenReadyTimeoutId = -1;
  21614. this._intermediateRendering = false;
  21615. this._viewUpdateFlag = -1;
  21616. this._projectionUpdateFlag = -1;
  21617. this._alternateViewUpdateFlag = -1;
  21618. this._alternateProjectionUpdateFlag = -1;
  21619. this._toBeDisposed = new BABYLON.SmartArray(256);
  21620. this._activeRequests = new Array();
  21621. this._pendingData = new Array();
  21622. this._isDisposed = false;
  21623. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21624. this._activeMeshes = new BABYLON.SmartArray(256);
  21625. this._processedMaterials = new BABYLON.SmartArray(256);
  21626. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21627. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21628. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21629. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21630. this._activeAnimatables = new Array();
  21631. this._transformMatrix = BABYLON.Matrix.Zero();
  21632. this._useAlternateCameraConfiguration = false;
  21633. this._alternateRendering = false;
  21634. this.requireLightSorting = false;
  21635. this._depthRenderer = {};
  21636. this._activeMeshesFrozen = false;
  21637. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21638. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21639. this._engine.scenes.push(this);
  21640. this._uid = null;
  21641. this._renderingManager = new BABYLON.RenderingManager(this);
  21642. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21643. if (BABYLON.OutlineRenderer) {
  21644. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21645. }
  21646. if (BABYLON.Tools.IsWindowObjectExist()) {
  21647. this.attachControl();
  21648. }
  21649. //simplification queue
  21650. if (BABYLON.SimplificationQueue) {
  21651. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21652. }
  21653. //collision coordinator initialization. For now legacy per default.
  21654. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21655. // Uniform Buffer
  21656. this._createUbo();
  21657. // Default Image processing definition.
  21658. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21659. }
  21660. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21661. /** The fog is deactivated */
  21662. get: function () {
  21663. return Scene._FOGMODE_NONE;
  21664. },
  21665. enumerable: true,
  21666. configurable: true
  21667. });
  21668. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21669. /** The fog density is following an exponential function */
  21670. get: function () {
  21671. return Scene._FOGMODE_EXP;
  21672. },
  21673. enumerable: true,
  21674. configurable: true
  21675. });
  21676. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21677. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21678. get: function () {
  21679. return Scene._FOGMODE_EXP2;
  21680. },
  21681. enumerable: true,
  21682. configurable: true
  21683. });
  21684. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21685. /** The fog density is following a linear function. */
  21686. get: function () {
  21687. return Scene._FOGMODE_LINEAR;
  21688. },
  21689. enumerable: true,
  21690. configurable: true
  21691. });
  21692. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21693. /**
  21694. * Texture used in all pbr material as the reflection texture.
  21695. * As in the majority of the scene they are the same (exception for multi room and so on),
  21696. * this is easier to reference from here than from all the materials.
  21697. */
  21698. get: function () {
  21699. return this._environmentTexture;
  21700. },
  21701. /**
  21702. * Texture used in all pbr material as the reflection texture.
  21703. * As in the majority of the scene they are the same (exception for multi room and so on),
  21704. * this is easier to set here than in all the materials.
  21705. */
  21706. set: function (value) {
  21707. if (this._environmentTexture === value) {
  21708. return;
  21709. }
  21710. this._environmentTexture = value;
  21711. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21712. },
  21713. enumerable: true,
  21714. configurable: true
  21715. });
  21716. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21717. /**
  21718. * Default image processing configuration used either in the rendering
  21719. * Forward main pass or through the imageProcessingPostProcess if present.
  21720. * As in the majority of the scene they are the same (exception for multi camera),
  21721. * this is easier to reference from here than from all the materials and post process.
  21722. *
  21723. * No setter as we it is a shared configuration, you can set the values instead.
  21724. */
  21725. get: function () {
  21726. return this._imageProcessingConfiguration;
  21727. },
  21728. enumerable: true,
  21729. configurable: true
  21730. });
  21731. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21732. get: function () {
  21733. return this._forcePointsCloud;
  21734. },
  21735. set: function (value) {
  21736. if (this._forcePointsCloud === value) {
  21737. return;
  21738. }
  21739. this._forcePointsCloud = value;
  21740. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. Object.defineProperty(Scene.prototype, "onDispose", {
  21746. /** A function to be executed when this scene is disposed. */
  21747. set: function (callback) {
  21748. if (this._onDisposeObserver) {
  21749. this.onDisposeObservable.remove(this._onDisposeObserver);
  21750. }
  21751. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21752. },
  21753. enumerable: true,
  21754. configurable: true
  21755. });
  21756. Object.defineProperty(Scene.prototype, "beforeRender", {
  21757. /** A function to be executed before rendering this scene */
  21758. set: function (callback) {
  21759. if (this._onBeforeRenderObserver) {
  21760. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21761. }
  21762. if (callback) {
  21763. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21764. }
  21765. },
  21766. enumerable: true,
  21767. configurable: true
  21768. });
  21769. Object.defineProperty(Scene.prototype, "afterRender", {
  21770. /** A function to be executed after rendering this scene */
  21771. set: function (callback) {
  21772. if (this._onAfterRenderObserver) {
  21773. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21774. }
  21775. if (callback) {
  21776. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21777. }
  21778. },
  21779. enumerable: true,
  21780. configurable: true
  21781. });
  21782. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21783. set: function (callback) {
  21784. if (this._onBeforeCameraRenderObserver) {
  21785. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21786. }
  21787. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21788. },
  21789. enumerable: true,
  21790. configurable: true
  21791. });
  21792. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21793. set: function (callback) {
  21794. if (this._onAfterCameraRenderObserver) {
  21795. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21796. }
  21797. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21798. },
  21799. enumerable: true,
  21800. configurable: true
  21801. });
  21802. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21803. get: function () {
  21804. if (!this._gamepadManager) {
  21805. this._gamepadManager = new BABYLON.GamepadManager(this);
  21806. }
  21807. return this._gamepadManager;
  21808. },
  21809. enumerable: true,
  21810. configurable: true
  21811. });
  21812. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21813. get: function () {
  21814. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21815. },
  21816. enumerable: true,
  21817. configurable: true
  21818. });
  21819. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21820. get: function () {
  21821. return this._useRightHandedSystem;
  21822. },
  21823. set: function (value) {
  21824. if (this._useRightHandedSystem === value) {
  21825. return;
  21826. }
  21827. this._useRightHandedSystem = value;
  21828. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21829. },
  21830. enumerable: true,
  21831. configurable: true
  21832. });
  21833. Scene.prototype.setStepId = function (newStepId) {
  21834. this._currentStepId = newStepId;
  21835. };
  21836. ;
  21837. Scene.prototype.getStepId = function () {
  21838. return this._currentStepId;
  21839. };
  21840. ;
  21841. Scene.prototype.getInternalStep = function () {
  21842. return this._currentInternalStep;
  21843. };
  21844. ;
  21845. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21846. get: function () {
  21847. return this._fogEnabled;
  21848. },
  21849. /**
  21850. * is fog enabled on this scene.
  21851. */
  21852. set: function (value) {
  21853. if (this._fogEnabled === value) {
  21854. return;
  21855. }
  21856. this._fogEnabled = value;
  21857. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21858. },
  21859. enumerable: true,
  21860. configurable: true
  21861. });
  21862. Object.defineProperty(Scene.prototype, "fogMode", {
  21863. get: function () {
  21864. return this._fogMode;
  21865. },
  21866. set: function (value) {
  21867. if (this._fogMode === value) {
  21868. return;
  21869. }
  21870. this._fogMode = value;
  21871. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21872. },
  21873. enumerable: true,
  21874. configurable: true
  21875. });
  21876. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21877. get: function () {
  21878. return this._shadowsEnabled;
  21879. },
  21880. set: function (value) {
  21881. if (this._shadowsEnabled === value) {
  21882. return;
  21883. }
  21884. this._shadowsEnabled = value;
  21885. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21886. },
  21887. enumerable: true,
  21888. configurable: true
  21889. });
  21890. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21891. get: function () {
  21892. return this._lightsEnabled;
  21893. },
  21894. set: function (value) {
  21895. if (this._lightsEnabled === value) {
  21896. return;
  21897. }
  21898. this._lightsEnabled = value;
  21899. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21900. },
  21901. enumerable: true,
  21902. configurable: true
  21903. });
  21904. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21905. /** The default material used on meshes when no material is affected */
  21906. get: function () {
  21907. if (!this._defaultMaterial) {
  21908. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21909. }
  21910. return this._defaultMaterial;
  21911. },
  21912. /** The default material used on meshes when no material is affected */
  21913. set: function (value) {
  21914. this._defaultMaterial = value;
  21915. },
  21916. enumerable: true,
  21917. configurable: true
  21918. });
  21919. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21920. get: function () {
  21921. return this._texturesEnabled;
  21922. },
  21923. set: function (value) {
  21924. if (this._texturesEnabled === value) {
  21925. return;
  21926. }
  21927. this._texturesEnabled = value;
  21928. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21929. },
  21930. enumerable: true,
  21931. configurable: true
  21932. });
  21933. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21934. get: function () {
  21935. return this._skeletonsEnabled;
  21936. },
  21937. set: function (value) {
  21938. if (this._skeletonsEnabled === value) {
  21939. return;
  21940. }
  21941. this._skeletonsEnabled = value;
  21942. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21943. },
  21944. enumerable: true,
  21945. configurable: true
  21946. });
  21947. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21948. get: function () {
  21949. if (!this._postProcessRenderPipelineManager) {
  21950. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21951. }
  21952. return this._postProcessRenderPipelineManager;
  21953. },
  21954. enumerable: true,
  21955. configurable: true
  21956. });
  21957. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21958. get: function () {
  21959. if (!this._mainSoundTrack) {
  21960. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21961. }
  21962. return this._mainSoundTrack;
  21963. },
  21964. enumerable: true,
  21965. configurable: true
  21966. });
  21967. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21968. get: function () {
  21969. return this._alternateRendering;
  21970. },
  21971. enumerable: true,
  21972. configurable: true
  21973. });
  21974. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21975. get: function () {
  21976. return this._frustumPlanes;
  21977. },
  21978. enumerable: true,
  21979. configurable: true
  21980. });
  21981. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21982. /**
  21983. * Gets the current geometry buffer associated to the scene.
  21984. */
  21985. get: function () {
  21986. return this._geometryBufferRenderer;
  21987. },
  21988. /**
  21989. * Sets the current geometry buffer for the scene.
  21990. */
  21991. set: function (geometryBufferRenderer) {
  21992. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21993. this._geometryBufferRenderer = geometryBufferRenderer;
  21994. }
  21995. },
  21996. enumerable: true,
  21997. configurable: true
  21998. });
  21999. Object.defineProperty(Scene.prototype, "debugLayer", {
  22000. // Properties
  22001. get: function () {
  22002. if (!this._debugLayer) {
  22003. this._debugLayer = new BABYLON.DebugLayer(this);
  22004. }
  22005. return this._debugLayer;
  22006. },
  22007. enumerable: true,
  22008. configurable: true
  22009. });
  22010. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22011. get: function () {
  22012. return this._workerCollisions;
  22013. },
  22014. set: function (enabled) {
  22015. if (!BABYLON.CollisionCoordinatorLegacy) {
  22016. return;
  22017. }
  22018. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22019. this._workerCollisions = enabled;
  22020. if (this.collisionCoordinator) {
  22021. this.collisionCoordinator.destroy();
  22022. }
  22023. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22024. this.collisionCoordinator.init(this);
  22025. },
  22026. enumerable: true,
  22027. configurable: true
  22028. });
  22029. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22030. get: function () {
  22031. return this._selectionOctree;
  22032. },
  22033. enumerable: true,
  22034. configurable: true
  22035. });
  22036. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22037. /**
  22038. * The mesh that is currently under the pointer.
  22039. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22040. */
  22041. get: function () {
  22042. return this._pointerOverMesh;
  22043. },
  22044. enumerable: true,
  22045. configurable: true
  22046. });
  22047. Object.defineProperty(Scene.prototype, "pointerX", {
  22048. /**
  22049. * Current on-screen X position of the pointer
  22050. * @return {number} X position of the pointer
  22051. */
  22052. get: function () {
  22053. return this._pointerX;
  22054. },
  22055. enumerable: true,
  22056. configurable: true
  22057. });
  22058. Object.defineProperty(Scene.prototype, "pointerY", {
  22059. /**
  22060. * Current on-screen Y position of the pointer
  22061. * @return {number} Y position of the pointer
  22062. */
  22063. get: function () {
  22064. return this._pointerY;
  22065. },
  22066. enumerable: true,
  22067. configurable: true
  22068. });
  22069. Scene.prototype.getCachedMaterial = function () {
  22070. return this._cachedMaterial;
  22071. };
  22072. Scene.prototype.getCachedEffect = function () {
  22073. return this._cachedEffect;
  22074. };
  22075. Scene.prototype.getCachedVisibility = function () {
  22076. return this._cachedVisibility;
  22077. };
  22078. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22079. if (visibility === void 0) { visibility = 1; }
  22080. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22081. };
  22082. Scene.prototype.getBoundingBoxRenderer = function () {
  22083. if (!this._boundingBoxRenderer) {
  22084. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22085. }
  22086. return this._boundingBoxRenderer;
  22087. };
  22088. Scene.prototype.getOutlineRenderer = function () {
  22089. return this._outlineRenderer;
  22090. };
  22091. Scene.prototype.getEngine = function () {
  22092. return this._engine;
  22093. };
  22094. Scene.prototype.getTotalVertices = function () {
  22095. return this._totalVertices.current;
  22096. };
  22097. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22098. get: function () {
  22099. return this._totalVertices;
  22100. },
  22101. enumerable: true,
  22102. configurable: true
  22103. });
  22104. Scene.prototype.getActiveIndices = function () {
  22105. return this._activeIndices.current;
  22106. };
  22107. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22108. get: function () {
  22109. return this._activeIndices;
  22110. },
  22111. enumerable: true,
  22112. configurable: true
  22113. });
  22114. Scene.prototype.getActiveParticles = function () {
  22115. return this._activeParticles.current;
  22116. };
  22117. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22118. get: function () {
  22119. return this._activeParticles;
  22120. },
  22121. enumerable: true,
  22122. configurable: true
  22123. });
  22124. Scene.prototype.getActiveBones = function () {
  22125. return this._activeBones.current;
  22126. };
  22127. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22128. get: function () {
  22129. return this._activeBones;
  22130. },
  22131. enumerable: true,
  22132. configurable: true
  22133. });
  22134. // Stats
  22135. Scene.prototype.getInterFramePerfCounter = function () {
  22136. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22137. return 0;
  22138. };
  22139. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22140. get: function () {
  22141. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22142. return null;
  22143. },
  22144. enumerable: true,
  22145. configurable: true
  22146. });
  22147. Scene.prototype.getLastFrameDuration = function () {
  22148. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22149. return 0;
  22150. };
  22151. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22152. get: function () {
  22153. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22154. return null;
  22155. },
  22156. enumerable: true,
  22157. configurable: true
  22158. });
  22159. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22160. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22161. return 0;
  22162. };
  22163. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22164. get: function () {
  22165. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22166. return null;
  22167. },
  22168. enumerable: true,
  22169. configurable: true
  22170. });
  22171. Scene.prototype.getActiveMeshes = function () {
  22172. return this._activeMeshes;
  22173. };
  22174. Scene.prototype.getRenderTargetsDuration = function () {
  22175. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22176. return 0;
  22177. };
  22178. Scene.prototype.getRenderDuration = function () {
  22179. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22180. return 0;
  22181. };
  22182. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22183. get: function () {
  22184. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22185. return null;
  22186. },
  22187. enumerable: true,
  22188. configurable: true
  22189. });
  22190. Scene.prototype.getParticlesDuration = function () {
  22191. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22192. return 0;
  22193. };
  22194. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22195. get: function () {
  22196. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22197. return null;
  22198. },
  22199. enumerable: true,
  22200. configurable: true
  22201. });
  22202. Scene.prototype.getSpritesDuration = function () {
  22203. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22204. return 0;
  22205. };
  22206. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22207. get: function () {
  22208. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22209. return null;
  22210. },
  22211. enumerable: true,
  22212. configurable: true
  22213. });
  22214. Scene.prototype.getAnimationRatio = function () {
  22215. return this._animationRatio;
  22216. };
  22217. Scene.prototype.getRenderId = function () {
  22218. return this._renderId;
  22219. };
  22220. Scene.prototype.incrementRenderId = function () {
  22221. this._renderId++;
  22222. };
  22223. Scene.prototype._updatePointerPosition = function (evt) {
  22224. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22225. if (!canvasRect) {
  22226. return;
  22227. }
  22228. this._pointerX = evt.clientX - canvasRect.left;
  22229. this._pointerY = evt.clientY - canvasRect.top;
  22230. this._unTranslatedPointerX = this._pointerX;
  22231. this._unTranslatedPointerY = this._pointerY;
  22232. };
  22233. Scene.prototype._createUbo = function () {
  22234. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22235. this._sceneUbo.addUniform("viewProjection", 16);
  22236. this._sceneUbo.addUniform("view", 16);
  22237. };
  22238. Scene.prototype._createAlternateUbo = function () {
  22239. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22240. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22241. this._alternateSceneUbo.addUniform("view", 16);
  22242. };
  22243. // Pointers handling
  22244. /**
  22245. * Use this method to simulate a pointer move on a mesh
  22246. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22247. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22248. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22249. */
  22250. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22251. var evt = new PointerEvent("pointermove", pointerEventInit);
  22252. return this._processPointerMove(pickResult, evt);
  22253. };
  22254. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22255. var canvas = this._engine.getRenderingCanvas();
  22256. if (!canvas) {
  22257. return this;
  22258. }
  22259. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22260. this.setPointerOverSprite(null);
  22261. this.setPointerOverMesh(pickResult.pickedMesh);
  22262. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22263. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22264. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22265. }
  22266. else {
  22267. canvas.style.cursor = this.hoverCursor;
  22268. }
  22269. }
  22270. else {
  22271. canvas.style.cursor = this.defaultCursor;
  22272. }
  22273. }
  22274. else {
  22275. this.setPointerOverMesh(null);
  22276. // Sprites
  22277. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22278. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22279. this.setPointerOverSprite(pickResult.pickedSprite);
  22280. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22281. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22282. }
  22283. else {
  22284. canvas.style.cursor = this.hoverCursor;
  22285. }
  22286. }
  22287. else {
  22288. this.setPointerOverSprite(null);
  22289. // Restore pointer
  22290. canvas.style.cursor = this.defaultCursor;
  22291. }
  22292. }
  22293. if (pickResult) {
  22294. if (this.onPointerMove) {
  22295. this.onPointerMove(evt, pickResult);
  22296. }
  22297. if (this.onPointerObservable.hasObservers()) {
  22298. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22299. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22300. this.onPointerObservable.notifyObservers(pi, type);
  22301. }
  22302. }
  22303. return this;
  22304. };
  22305. /**
  22306. * Use this method to simulate a pointer down on a mesh
  22307. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22308. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22309. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22310. */
  22311. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22312. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22313. return this._processPointerDown(pickResult, evt);
  22314. };
  22315. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22316. var _this = this;
  22317. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22318. this._pickedDownMesh = pickResult.pickedMesh;
  22319. var actionManager = pickResult.pickedMesh.actionManager;
  22320. if (actionManager) {
  22321. if (actionManager.hasPickTriggers) {
  22322. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22323. switch (evt.button) {
  22324. case 0:
  22325. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22326. break;
  22327. case 1:
  22328. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22329. break;
  22330. case 2:
  22331. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22332. break;
  22333. }
  22334. }
  22335. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22336. window.setTimeout(function () {
  22337. 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);
  22338. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22339. if (_this._totalPointersPressed !== 0 &&
  22340. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22341. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22342. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22343. _this._startingPointerTime = 0;
  22344. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22345. }
  22346. }
  22347. }, Scene.LongPressDelay);
  22348. }
  22349. }
  22350. }
  22351. if (pickResult) {
  22352. if (this.onPointerDown) {
  22353. this.onPointerDown(evt, pickResult);
  22354. }
  22355. if (this.onPointerObservable.hasObservers()) {
  22356. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22357. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22358. this.onPointerObservable.notifyObservers(pi, type);
  22359. }
  22360. }
  22361. return this;
  22362. };
  22363. /**
  22364. * Use this method to simulate a pointer up on a mesh
  22365. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22366. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22367. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22368. */
  22369. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22370. var evt = new PointerEvent("pointerup", pointerEventInit);
  22371. var clickInfo = new ClickInfo();
  22372. clickInfo.singleClick = true;
  22373. clickInfo.ignore = true;
  22374. return this._processPointerUp(pickResult, evt, clickInfo);
  22375. };
  22376. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22377. if (pickResult && pickResult && pickResult.pickedMesh) {
  22378. this._pickedUpMesh = pickResult.pickedMesh;
  22379. if (this._pickedDownMesh === this._pickedUpMesh) {
  22380. if (this.onPointerPick) {
  22381. this.onPointerPick(evt, pickResult);
  22382. }
  22383. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22384. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22385. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22386. this.onPointerObservable.notifyObservers(pi, type);
  22387. }
  22388. }
  22389. if (pickResult.pickedMesh.actionManager) {
  22390. if (clickInfo.ignore) {
  22391. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22392. }
  22393. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22394. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22395. }
  22396. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22397. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22398. }
  22399. }
  22400. }
  22401. if (this._pickedDownMesh &&
  22402. this._pickedDownMesh.actionManager &&
  22403. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22404. this._pickedDownMesh !== this._pickedUpMesh) {
  22405. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22406. }
  22407. if (this.onPointerUp) {
  22408. this.onPointerUp(evt, pickResult);
  22409. }
  22410. if (this.onPointerObservable.hasObservers()) {
  22411. if (!clickInfo.ignore) {
  22412. if (!clickInfo.hasSwiped) {
  22413. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22414. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22415. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22416. this.onPointerObservable.notifyObservers(pi, type);
  22417. }
  22418. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22419. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22420. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22421. this.onPointerObservable.notifyObservers(pi, type);
  22422. }
  22423. }
  22424. }
  22425. else {
  22426. var type = BABYLON.PointerEventTypes.POINTERUP;
  22427. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22428. this.onPointerObservable.notifyObservers(pi, type);
  22429. }
  22430. }
  22431. return this;
  22432. };
  22433. /**
  22434. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22435. * @param attachUp defines if you want to attach events to pointerup
  22436. * @param attachDown defines if you want to attach events to pointerdown
  22437. * @param attachMove defines if you want to attach events to pointermove
  22438. */
  22439. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22440. var _this = this;
  22441. if (attachUp === void 0) { attachUp = true; }
  22442. if (attachDown === void 0) { attachDown = true; }
  22443. if (attachMove === void 0) { attachMove = true; }
  22444. this._initActionManager = function (act, clickInfo) {
  22445. if (!_this._meshPickProceed) {
  22446. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22447. _this._currentPickResult = pickResult;
  22448. if (pickResult) {
  22449. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22450. }
  22451. _this._meshPickProceed = true;
  22452. }
  22453. return act;
  22454. };
  22455. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22456. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22457. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22458. btn !== _this._previousButtonPressed) {
  22459. _this._doubleClickOccured = false;
  22460. clickInfo.singleClick = true;
  22461. clickInfo.ignore = false;
  22462. cb(clickInfo, _this._currentPickResult);
  22463. }
  22464. };
  22465. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22466. var clickInfo = new ClickInfo();
  22467. _this._currentPickResult = null;
  22468. var act = null;
  22469. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22470. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22471. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22472. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22473. act = _this._initActionManager(act, clickInfo);
  22474. if (act)
  22475. checkPicking = act.hasPickTriggers;
  22476. }
  22477. if (checkPicking) {
  22478. var btn = evt.button;
  22479. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22480. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22481. if (!clickInfo.hasSwiped) {
  22482. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22483. if (!checkSingleClickImmediately) {
  22484. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22485. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22486. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22487. act = _this._initActionManager(act, clickInfo);
  22488. if (act)
  22489. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22490. }
  22491. }
  22492. if (checkSingleClickImmediately) {
  22493. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22494. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22495. btn !== _this._previousButtonPressed) {
  22496. clickInfo.singleClick = true;
  22497. cb(clickInfo, _this._currentPickResult);
  22498. }
  22499. }
  22500. else {
  22501. // wait that no double click has been raised during the double click delay
  22502. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22503. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22504. }
  22505. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22506. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22507. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22508. act = _this._initActionManager(act, clickInfo);
  22509. if (act)
  22510. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22511. }
  22512. if (checkDoubleClick) {
  22513. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22514. if (btn === _this._previousButtonPressed &&
  22515. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22516. !_this._doubleClickOccured) {
  22517. // pointer has not moved for 2 clicks, it's a double click
  22518. if (!clickInfo.hasSwiped &&
  22519. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22520. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22521. _this._previousStartingPointerTime = 0;
  22522. _this._doubleClickOccured = true;
  22523. clickInfo.doubleClick = true;
  22524. clickInfo.ignore = false;
  22525. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22526. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22527. }
  22528. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22529. cb(clickInfo, _this._currentPickResult);
  22530. }
  22531. else {
  22532. _this._doubleClickOccured = false;
  22533. _this._previousStartingPointerTime = _this._startingPointerTime;
  22534. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22535. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22536. _this._previousButtonPressed = btn;
  22537. if (Scene.ExclusiveDoubleClickMode) {
  22538. if (_this._previousDelayedSimpleClickTimeout) {
  22539. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22540. }
  22541. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22542. cb(clickInfo, _this._previousPickResult);
  22543. }
  22544. else {
  22545. cb(clickInfo, _this._currentPickResult);
  22546. }
  22547. }
  22548. }
  22549. else {
  22550. _this._doubleClickOccured = false;
  22551. _this._previousStartingPointerTime = _this._startingPointerTime;
  22552. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22553. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22554. _this._previousButtonPressed = btn;
  22555. }
  22556. }
  22557. }
  22558. }
  22559. clickInfo.ignore = true;
  22560. cb(clickInfo, _this._currentPickResult);
  22561. };
  22562. this._spritePredicate = function (sprite) {
  22563. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22564. };
  22565. this._onPointerMove = function (evt) {
  22566. _this._updatePointerPosition(evt);
  22567. // PreObservable support
  22568. if (_this.onPrePointerObservable.hasObservers()) {
  22569. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22570. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22571. _this.onPrePointerObservable.notifyObservers(pi, type);
  22572. if (pi.skipOnPointerObservable) {
  22573. return;
  22574. }
  22575. }
  22576. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22577. return;
  22578. }
  22579. if (!_this.pointerMovePredicate) {
  22580. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22581. }
  22582. // Meshes
  22583. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22584. _this._processPointerMove(pickResult, evt);
  22585. };
  22586. this._onPointerDown = function (evt) {
  22587. _this._totalPointersPressed++;
  22588. _this._pickedDownMesh = null;
  22589. _this._meshPickProceed = false;
  22590. _this._updatePointerPosition(evt);
  22591. if (_this.preventDefaultOnPointerDown && canvas) {
  22592. evt.preventDefault();
  22593. canvas.focus();
  22594. }
  22595. // PreObservable support
  22596. if (_this.onPrePointerObservable.hasObservers()) {
  22597. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22598. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22599. _this.onPrePointerObservable.notifyObservers(pi, type);
  22600. if (pi.skipOnPointerObservable) {
  22601. return;
  22602. }
  22603. }
  22604. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22605. return;
  22606. }
  22607. _this._startingPointerPosition.x = _this._pointerX;
  22608. _this._startingPointerPosition.y = _this._pointerY;
  22609. _this._startingPointerTime = new Date().getTime();
  22610. if (!_this.pointerDownPredicate) {
  22611. _this.pointerDownPredicate = function (mesh) {
  22612. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22613. };
  22614. }
  22615. // Meshes
  22616. _this._pickedDownMesh = null;
  22617. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22618. _this._processPointerDown(pickResult, evt);
  22619. // Sprites
  22620. _this._pickedDownSprite = null;
  22621. if (_this.spriteManagers.length > 0) {
  22622. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22623. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22624. if (pickResult.pickedSprite.actionManager) {
  22625. _this._pickedDownSprite = pickResult.pickedSprite;
  22626. switch (evt.button) {
  22627. case 0:
  22628. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22629. break;
  22630. case 1:
  22631. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22632. break;
  22633. case 2:
  22634. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22635. break;
  22636. }
  22637. if (pickResult.pickedSprite.actionManager) {
  22638. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22639. }
  22640. }
  22641. }
  22642. }
  22643. };
  22644. this._onPointerUp = function (evt) {
  22645. if (_this._totalPointersPressed === 0) {
  22646. return; // So we need to test it the pointer down was pressed before.
  22647. }
  22648. _this._totalPointersPressed--;
  22649. _this._pickedUpMesh = null;
  22650. _this._meshPickProceed = false;
  22651. _this._updatePointerPosition(evt);
  22652. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22653. // PreObservable support
  22654. if (_this.onPrePointerObservable.hasObservers()) {
  22655. if (!clickInfo.ignore) {
  22656. if (!clickInfo.hasSwiped) {
  22657. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22658. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22659. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22660. _this.onPrePointerObservable.notifyObservers(pi, type);
  22661. if (pi.skipOnPointerObservable) {
  22662. return;
  22663. }
  22664. }
  22665. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22666. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22667. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22668. _this.onPrePointerObservable.notifyObservers(pi, type);
  22669. if (pi.skipOnPointerObservable) {
  22670. return;
  22671. }
  22672. }
  22673. }
  22674. }
  22675. else {
  22676. var type = BABYLON.PointerEventTypes.POINTERUP;
  22677. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22678. _this.onPrePointerObservable.notifyObservers(pi, type);
  22679. if (pi.skipOnPointerObservable) {
  22680. return;
  22681. }
  22682. }
  22683. }
  22684. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22685. return;
  22686. }
  22687. if (!_this.pointerUpPredicate) {
  22688. _this.pointerUpPredicate = function (mesh) {
  22689. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22690. };
  22691. }
  22692. // Meshes
  22693. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22694. _this._initActionManager(null, clickInfo);
  22695. }
  22696. if (!pickResult) {
  22697. pickResult = _this._currentPickResult;
  22698. }
  22699. _this._processPointerUp(pickResult, evt, clickInfo);
  22700. // Sprites
  22701. if (_this.spriteManagers.length > 0) {
  22702. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22703. if (spritePickResult) {
  22704. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22705. if (spritePickResult.pickedSprite.actionManager) {
  22706. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22707. if (spritePickResult.pickedSprite.actionManager) {
  22708. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22709. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22710. }
  22711. }
  22712. }
  22713. }
  22714. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22715. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22716. }
  22717. }
  22718. }
  22719. _this._previousPickResult = _this._currentPickResult;
  22720. });
  22721. };
  22722. this._onKeyDown = function (evt) {
  22723. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22724. if (_this.onPreKeyboardObservable.hasObservers()) {
  22725. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22726. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22727. if (pi.skipOnPointerObservable) {
  22728. return;
  22729. }
  22730. }
  22731. if (_this.onKeyboardObservable.hasObservers()) {
  22732. var pi = new BABYLON.KeyboardInfo(type, evt);
  22733. _this.onKeyboardObservable.notifyObservers(pi, type);
  22734. }
  22735. if (_this.actionManager) {
  22736. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22737. }
  22738. };
  22739. this._onKeyUp = function (evt) {
  22740. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22741. if (_this.onPreKeyboardObservable.hasObservers()) {
  22742. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22743. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22744. if (pi.skipOnPointerObservable) {
  22745. return;
  22746. }
  22747. }
  22748. if (_this.onKeyboardObservable.hasObservers()) {
  22749. var pi = new BABYLON.KeyboardInfo(type, evt);
  22750. _this.onKeyboardObservable.notifyObservers(pi, type);
  22751. }
  22752. if (_this.actionManager) {
  22753. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22754. }
  22755. };
  22756. var engine = this.getEngine();
  22757. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22758. if (!canvas) {
  22759. return;
  22760. }
  22761. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22762. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22763. });
  22764. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22765. if (!canvas) {
  22766. return;
  22767. }
  22768. canvas.removeEventListener("keydown", _this._onKeyDown);
  22769. canvas.removeEventListener("keyup", _this._onKeyUp);
  22770. });
  22771. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22772. var canvas = this._engine.getRenderingCanvas();
  22773. if (!canvas) {
  22774. return;
  22775. }
  22776. if (attachMove) {
  22777. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22778. // Wheel
  22779. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22780. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22781. }
  22782. if (attachDown) {
  22783. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22784. }
  22785. if (attachUp) {
  22786. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22787. }
  22788. canvas.tabIndex = 1;
  22789. };
  22790. Scene.prototype.detachControl = function () {
  22791. var engine = this.getEngine();
  22792. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22793. var canvas = engine.getRenderingCanvas();
  22794. if (!canvas) {
  22795. return;
  22796. }
  22797. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22798. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22799. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22800. if (this._onCanvasBlurObserver) {
  22801. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22802. }
  22803. if (this._onCanvasFocusObserver) {
  22804. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22805. }
  22806. // Wheel
  22807. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22808. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22809. // Keyboard
  22810. canvas.removeEventListener("keydown", this._onKeyDown);
  22811. canvas.removeEventListener("keyup", this._onKeyUp);
  22812. // Observables
  22813. this.onKeyboardObservable.clear();
  22814. this.onPreKeyboardObservable.clear();
  22815. this.onPointerObservable.clear();
  22816. this.onPrePointerObservable.clear();
  22817. };
  22818. /**
  22819. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22820. * Delay loaded resources are not taking in account
  22821. * @return true if all required resources are ready
  22822. */
  22823. Scene.prototype.isReady = function () {
  22824. if (this._isDisposed) {
  22825. return false;
  22826. }
  22827. if (this._pendingData.length > 0) {
  22828. return false;
  22829. }
  22830. var index;
  22831. var engine = this.getEngine();
  22832. // Geometries
  22833. for (index = 0; index < this._geometries.length; index++) {
  22834. var geometry = this._geometries[index];
  22835. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22836. return false;
  22837. }
  22838. }
  22839. // Meshes
  22840. for (index = 0; index < this.meshes.length; index++) {
  22841. var mesh = this.meshes[index];
  22842. if (!mesh.isEnabled()) {
  22843. continue;
  22844. }
  22845. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22846. continue;
  22847. }
  22848. if (!mesh.isReady(true)) {
  22849. return false;
  22850. }
  22851. // Effect layers
  22852. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22853. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22854. var layer = _a[_i];
  22855. if (!layer.hasMesh(mesh)) {
  22856. continue;
  22857. }
  22858. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22859. var subMesh = _c[_b];
  22860. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22861. return false;
  22862. }
  22863. }
  22864. }
  22865. }
  22866. return true;
  22867. };
  22868. Scene.prototype.resetCachedMaterial = function () {
  22869. this._cachedMaterial = null;
  22870. this._cachedEffect = null;
  22871. this._cachedVisibility = null;
  22872. };
  22873. Scene.prototype.registerBeforeRender = function (func) {
  22874. this.onBeforeRenderObservable.add(func);
  22875. };
  22876. Scene.prototype.unregisterBeforeRender = function (func) {
  22877. this.onBeforeRenderObservable.removeCallback(func);
  22878. };
  22879. Scene.prototype.registerAfterRender = function (func) {
  22880. this.onAfterRenderObservable.add(func);
  22881. };
  22882. Scene.prototype.unregisterAfterRender = function (func) {
  22883. this.onAfterRenderObservable.removeCallback(func);
  22884. };
  22885. Scene.prototype._executeOnceBeforeRender = function (func) {
  22886. var _this = this;
  22887. var execFunc = function () {
  22888. func();
  22889. setTimeout(function () {
  22890. _this.unregisterBeforeRender(execFunc);
  22891. });
  22892. };
  22893. this.registerBeforeRender(execFunc);
  22894. };
  22895. /**
  22896. * The provided function will run before render once and will be disposed afterwards.
  22897. * A timeout delay can be provided so that the function will be executed in N ms.
  22898. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22899. * @param func The function to be executed.
  22900. * @param timeout optional delay in ms
  22901. */
  22902. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22903. var _this = this;
  22904. if (timeout !== undefined) {
  22905. setTimeout(function () {
  22906. _this._executeOnceBeforeRender(func);
  22907. }, timeout);
  22908. }
  22909. else {
  22910. this._executeOnceBeforeRender(func);
  22911. }
  22912. };
  22913. Scene.prototype._addPendingData = function (data) {
  22914. this._pendingData.push(data);
  22915. };
  22916. Scene.prototype._removePendingData = function (data) {
  22917. var wasLoading = this.isLoading;
  22918. var index = this._pendingData.indexOf(data);
  22919. if (index !== -1) {
  22920. this._pendingData.splice(index, 1);
  22921. }
  22922. if (wasLoading && !this.isLoading) {
  22923. this.onDataLoadedObservable.notifyObservers(this);
  22924. }
  22925. };
  22926. Scene.prototype.getWaitingItemsCount = function () {
  22927. return this._pendingData.length;
  22928. };
  22929. Object.defineProperty(Scene.prototype, "isLoading", {
  22930. get: function () {
  22931. return this._pendingData.length > 0;
  22932. },
  22933. enumerable: true,
  22934. configurable: true
  22935. });
  22936. /**
  22937. * Registers a function to be executed when the scene is ready.
  22938. * @param {Function} func - the function to be executed.
  22939. */
  22940. Scene.prototype.executeWhenReady = function (func) {
  22941. var _this = this;
  22942. this.onReadyObservable.add(func);
  22943. if (this._executeWhenReadyTimeoutId !== -1) {
  22944. return;
  22945. }
  22946. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22947. _this._checkIsReady();
  22948. }, 150);
  22949. };
  22950. /**
  22951. * Returns a promise that resolves when the scene is ready.
  22952. * @returns A promise that resolves when the scene is ready.
  22953. */
  22954. Scene.prototype.whenReadyAsync = function () {
  22955. var _this = this;
  22956. return new Promise(function (resolve) {
  22957. _this.executeWhenReady(function () {
  22958. resolve();
  22959. });
  22960. });
  22961. };
  22962. Scene.prototype._checkIsReady = function () {
  22963. var _this = this;
  22964. if (this.isReady()) {
  22965. this.onReadyObservable.notifyObservers(this);
  22966. this.onReadyObservable.clear();
  22967. this._executeWhenReadyTimeoutId = -1;
  22968. return;
  22969. }
  22970. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22971. _this._checkIsReady();
  22972. }, 150);
  22973. };
  22974. // Animations
  22975. /**
  22976. * Will start the animation sequence of a given target
  22977. * @param target - the target
  22978. * @param {number} from - from which frame should animation start
  22979. * @param {number} to - till which frame should animation run.
  22980. * @param {boolean} [loop] - should the animation loop
  22981. * @param {number} [speedRatio] - the speed in which to run the animation
  22982. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22983. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22984. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22985. * See BABYLON.Animatable
  22986. */
  22987. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22988. if (speedRatio === void 0) { speedRatio = 1.0; }
  22989. if (from > to && speedRatio > 0) {
  22990. speedRatio *= -1;
  22991. }
  22992. this.stopAnimation(target);
  22993. if (!animatable) {
  22994. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22995. }
  22996. // Local animations
  22997. if (target.animations) {
  22998. animatable.appendAnimations(target, target.animations);
  22999. }
  23000. // Children animations
  23001. if (target.getAnimatables) {
  23002. var animatables = target.getAnimatables();
  23003. for (var index = 0; index < animatables.length; index++) {
  23004. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  23005. }
  23006. }
  23007. animatable.reset();
  23008. return animatable;
  23009. };
  23010. /**
  23011. * Begin a new animation on a given node
  23012. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23013. * @param {BABYLON.Animation[]} defines the list of animations to start
  23014. * @param {number} from defines the initial value
  23015. * @param {number} to defines the final value
  23016. * @param {boolean} loop defines if you want animation to loop (off by default)
  23017. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23018. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23019. * @returns the list of created animatables
  23020. */
  23021. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23022. if (speedRatio === undefined) {
  23023. speedRatio = 1.0;
  23024. }
  23025. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23026. return animatable;
  23027. };
  23028. /**
  23029. * Begin a new animation on a given node and its hierarchy
  23030. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23031. * @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.
  23032. * @param {BABYLON.Animation[]} defines the list of animations to start
  23033. * @param {number} from defines the initial value
  23034. * @param {number} to defines the final value
  23035. * @param {boolean} loop defines if you want animation to loop (off by default)
  23036. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23037. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23038. * @returns the list of animatables created for all nodes
  23039. */
  23040. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23041. var children = target.getDescendants(directDescendantsOnly);
  23042. var result = [];
  23043. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23044. var child = children_1[_i];
  23045. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23046. }
  23047. return result;
  23048. };
  23049. Scene.prototype.getAnimatableByTarget = function (target) {
  23050. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23051. if (this._activeAnimatables[index].target === target) {
  23052. return this._activeAnimatables[index];
  23053. }
  23054. }
  23055. return null;
  23056. };
  23057. Object.defineProperty(Scene.prototype, "animatables", {
  23058. get: function () {
  23059. return this._activeAnimatables;
  23060. },
  23061. enumerable: true,
  23062. configurable: true
  23063. });
  23064. /**
  23065. * Will stop the animation of the given target
  23066. * @param target - the target
  23067. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23068. * @see beginAnimation
  23069. */
  23070. Scene.prototype.stopAnimation = function (target, animationName) {
  23071. var animatable = this.getAnimatableByTarget(target);
  23072. if (animatable) {
  23073. animatable.stop(animationName);
  23074. }
  23075. };
  23076. /**
  23077. * Stops and removes all animations that have been applied to the scene
  23078. */
  23079. Scene.prototype.stopAllAnimations = function () {
  23080. if (this._activeAnimatables) {
  23081. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23082. this._activeAnimatables[i].stop();
  23083. }
  23084. this._activeAnimatables = [];
  23085. }
  23086. };
  23087. Scene.prototype._animate = function () {
  23088. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23089. return;
  23090. }
  23091. // Getting time
  23092. var now = BABYLON.Tools.Now;
  23093. if (!this._animationTimeLast) {
  23094. if (this._pendingData.length > 0) {
  23095. return;
  23096. }
  23097. this._animationTimeLast = now;
  23098. }
  23099. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23100. this._animationTime += deltaTime;
  23101. this._animationTimeLast = now;
  23102. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23103. this._activeAnimatables[index]._animate(this._animationTime);
  23104. }
  23105. };
  23106. // Matrix
  23107. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23108. this._useAlternateCameraConfiguration = active;
  23109. };
  23110. Scene.prototype.getViewMatrix = function () {
  23111. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23112. };
  23113. Scene.prototype.getProjectionMatrix = function () {
  23114. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23115. };
  23116. Scene.prototype.getTransformMatrix = function () {
  23117. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23118. };
  23119. Scene.prototype.setTransformMatrix = function (view, projection) {
  23120. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23121. return;
  23122. }
  23123. this._viewUpdateFlag = view.updateFlag;
  23124. this._projectionUpdateFlag = projection.updateFlag;
  23125. this._viewMatrix = view;
  23126. this._projectionMatrix = projection;
  23127. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23128. // Update frustum
  23129. if (!this._frustumPlanes) {
  23130. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23131. }
  23132. else {
  23133. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23134. }
  23135. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23136. var otherCamera = this.activeCamera._alternateCamera;
  23137. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23138. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23139. }
  23140. if (this._sceneUbo.useUbo) {
  23141. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23142. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23143. this._sceneUbo.update();
  23144. }
  23145. };
  23146. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23147. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23148. return;
  23149. }
  23150. this._alternateViewUpdateFlag = view.updateFlag;
  23151. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23152. this._alternateViewMatrix = view;
  23153. this._alternateProjectionMatrix = projection;
  23154. if (!this._alternateTransformMatrix) {
  23155. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23156. }
  23157. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23158. if (!this._alternateSceneUbo) {
  23159. this._createAlternateUbo();
  23160. }
  23161. if (this._alternateSceneUbo.useUbo) {
  23162. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23163. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23164. this._alternateSceneUbo.update();
  23165. }
  23166. };
  23167. Scene.prototype.getSceneUniformBuffer = function () {
  23168. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23169. };
  23170. // Methods
  23171. Scene.prototype.getUniqueId = function () {
  23172. var result = Scene._uniqueIdCounter;
  23173. Scene._uniqueIdCounter++;
  23174. return result;
  23175. };
  23176. Scene.prototype.addMesh = function (newMesh) {
  23177. this.meshes.push(newMesh);
  23178. //notify the collision coordinator
  23179. if (this.collisionCoordinator) {
  23180. this.collisionCoordinator.onMeshAdded(newMesh);
  23181. }
  23182. newMesh._resyncLightSources();
  23183. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23184. };
  23185. Scene.prototype.removeMesh = function (toRemove) {
  23186. var index = this.meshes.indexOf(toRemove);
  23187. if (index !== -1) {
  23188. // Remove from the scene if mesh found
  23189. this.meshes.splice(index, 1);
  23190. }
  23191. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23192. return index;
  23193. };
  23194. Scene.prototype.addTransformNode = function (newTransformNode) {
  23195. this.transformNodes.push(newTransformNode);
  23196. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23197. };
  23198. Scene.prototype.removeTransformNode = function (toRemove) {
  23199. var index = this.transformNodes.indexOf(toRemove);
  23200. if (index !== -1) {
  23201. // Remove from the scene if found
  23202. this.transformNodes.splice(index, 1);
  23203. }
  23204. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23205. return index;
  23206. };
  23207. Scene.prototype.removeSkeleton = function (toRemove) {
  23208. var index = this.skeletons.indexOf(toRemove);
  23209. if (index !== -1) {
  23210. // Remove from the scene if found
  23211. this.skeletons.splice(index, 1);
  23212. }
  23213. return index;
  23214. };
  23215. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23216. var index = this.morphTargetManagers.indexOf(toRemove);
  23217. if (index !== -1) {
  23218. // Remove from the scene if found
  23219. this.morphTargetManagers.splice(index, 1);
  23220. }
  23221. return index;
  23222. };
  23223. Scene.prototype.removeLight = function (toRemove) {
  23224. var index = this.lights.indexOf(toRemove);
  23225. if (index !== -1) {
  23226. // Remove from meshes
  23227. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23228. var mesh = _a[_i];
  23229. mesh._removeLightSource(toRemove);
  23230. }
  23231. // Remove from the scene if mesh found
  23232. this.lights.splice(index, 1);
  23233. this.sortLightsByPriority();
  23234. }
  23235. this.onLightRemovedObservable.notifyObservers(toRemove);
  23236. return index;
  23237. };
  23238. Scene.prototype.removeCamera = function (toRemove) {
  23239. var index = this.cameras.indexOf(toRemove);
  23240. if (index !== -1) {
  23241. // Remove from the scene if mesh found
  23242. this.cameras.splice(index, 1);
  23243. }
  23244. // Remove from activeCameras
  23245. var index2 = this.activeCameras.indexOf(toRemove);
  23246. if (index2 !== -1) {
  23247. // Remove from the scene if mesh found
  23248. this.activeCameras.splice(index2, 1);
  23249. }
  23250. // Reset the activeCamera
  23251. if (this.activeCamera === toRemove) {
  23252. if (this.cameras.length > 0) {
  23253. this.activeCamera = this.cameras[0];
  23254. }
  23255. else {
  23256. this.activeCamera = null;
  23257. }
  23258. }
  23259. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23260. return index;
  23261. };
  23262. Scene.prototype.removeParticleSystem = function (toRemove) {
  23263. var index = this.particleSystems.indexOf(toRemove);
  23264. if (index !== -1) {
  23265. this.particleSystems.splice(index, 1);
  23266. }
  23267. return index;
  23268. };
  23269. ;
  23270. Scene.prototype.removeAnimation = function (toRemove) {
  23271. var index = this.animations.indexOf(toRemove);
  23272. if (index !== -1) {
  23273. this.animations.splice(index, 1);
  23274. }
  23275. return index;
  23276. };
  23277. ;
  23278. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23279. var index = this.multiMaterials.indexOf(toRemove);
  23280. if (index !== -1) {
  23281. this.multiMaterials.splice(index, 1);
  23282. }
  23283. return index;
  23284. };
  23285. ;
  23286. Scene.prototype.removeMaterial = function (toRemove) {
  23287. var index = this.materials.indexOf(toRemove);
  23288. if (index !== -1) {
  23289. this.materials.splice(index, 1);
  23290. }
  23291. return index;
  23292. };
  23293. ;
  23294. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23295. var index = this.lensFlareSystems.indexOf(toRemove);
  23296. if (index !== -1) {
  23297. this.lensFlareSystems.splice(index, 1);
  23298. }
  23299. return index;
  23300. };
  23301. ;
  23302. Scene.prototype.removeActionManager = function (toRemove) {
  23303. var index = this._actionManagers.indexOf(toRemove);
  23304. if (index !== -1) {
  23305. this._actionManagers.splice(index, 1);
  23306. }
  23307. return index;
  23308. };
  23309. ;
  23310. Scene.prototype.addLight = function (newLight) {
  23311. this.lights.push(newLight);
  23312. this.sortLightsByPriority();
  23313. // Add light to all meshes (To support if the light is removed and then readded)
  23314. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23315. var mesh = _a[_i];
  23316. if (mesh._lightSources.indexOf(newLight) === -1) {
  23317. mesh._lightSources.push(newLight);
  23318. mesh._resyncLightSources();
  23319. }
  23320. }
  23321. this.onNewLightAddedObservable.notifyObservers(newLight);
  23322. };
  23323. Scene.prototype.sortLightsByPriority = function () {
  23324. if (this.requireLightSorting) {
  23325. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23326. }
  23327. };
  23328. Scene.prototype.addCamera = function (newCamera) {
  23329. this.cameras.push(newCamera);
  23330. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23331. };
  23332. Scene.prototype.addSkeleton = function (newSkeleton) {
  23333. this.skeletons.push(newSkeleton);
  23334. };
  23335. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23336. this.particleSystems.push(newParticleSystem);
  23337. };
  23338. Scene.prototype.addAnimation = function (newAnimation) {
  23339. this.animations.push(newAnimation);
  23340. };
  23341. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23342. this.multiMaterials.push(newMultiMaterial);
  23343. };
  23344. Scene.prototype.addMaterial = function (newMaterial) {
  23345. this.materials.push(newMaterial);
  23346. };
  23347. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23348. this.morphTargetManagers.push(newMorphTargetManager);
  23349. };
  23350. Scene.prototype.addGeometry = function (newGeometrie) {
  23351. this._geometries.push(newGeometrie);
  23352. };
  23353. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23354. this.lensFlareSystems.push(newLensFlareSystem);
  23355. };
  23356. Scene.prototype.addActionManager = function (newActionManager) {
  23357. this._actionManagers.push(newActionManager);
  23358. };
  23359. /**
  23360. * Switch active camera
  23361. * @param {Camera} newCamera - new active camera
  23362. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23363. */
  23364. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23365. if (attachControl === void 0) { attachControl = true; }
  23366. var canvas = this._engine.getRenderingCanvas();
  23367. if (!canvas) {
  23368. return;
  23369. }
  23370. if (this.activeCamera) {
  23371. this.activeCamera.detachControl(canvas);
  23372. }
  23373. this.activeCamera = newCamera;
  23374. if (attachControl) {
  23375. newCamera.attachControl(canvas);
  23376. }
  23377. };
  23378. /**
  23379. * sets the active camera of the scene using its ID
  23380. * @param {string} id - the camera's ID
  23381. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23382. * @see activeCamera
  23383. */
  23384. Scene.prototype.setActiveCameraByID = function (id) {
  23385. var camera = this.getCameraByID(id);
  23386. if (camera) {
  23387. this.activeCamera = camera;
  23388. return camera;
  23389. }
  23390. return null;
  23391. };
  23392. /**
  23393. * sets the active camera of the scene using its name
  23394. * @param {string} name - the camera's name
  23395. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23396. * @see activeCamera
  23397. */
  23398. Scene.prototype.setActiveCameraByName = function (name) {
  23399. var camera = this.getCameraByName(name);
  23400. if (camera) {
  23401. this.activeCamera = camera;
  23402. return camera;
  23403. }
  23404. return null;
  23405. };
  23406. /**
  23407. * get an animation group using its name
  23408. * @param {string} the material's name
  23409. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23410. */
  23411. Scene.prototype.getAnimationGroupByName = function (name) {
  23412. for (var index = 0; index < this.animationGroups.length; index++) {
  23413. if (this.animationGroups[index].name === name) {
  23414. return this.animationGroups[index];
  23415. }
  23416. }
  23417. return null;
  23418. };
  23419. /**
  23420. * get a material using its id
  23421. * @param {string} the material's ID
  23422. * @return {BABYLON.Material|null} the material or null if none found.
  23423. */
  23424. Scene.prototype.getMaterialByID = function (id) {
  23425. for (var index = 0; index < this.materials.length; index++) {
  23426. if (this.materials[index].id === id) {
  23427. return this.materials[index];
  23428. }
  23429. }
  23430. return null;
  23431. };
  23432. /**
  23433. * get a material using its name
  23434. * @param {string} the material's name
  23435. * @return {BABYLON.Material|null} the material or null if none found.
  23436. */
  23437. Scene.prototype.getMaterialByName = function (name) {
  23438. for (var index = 0; index < this.materials.length; index++) {
  23439. if (this.materials[index].name === name) {
  23440. return this.materials[index];
  23441. }
  23442. }
  23443. return null;
  23444. };
  23445. Scene.prototype.getLensFlareSystemByName = function (name) {
  23446. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23447. if (this.lensFlareSystems[index].name === name) {
  23448. return this.lensFlareSystems[index];
  23449. }
  23450. }
  23451. return null;
  23452. };
  23453. Scene.prototype.getLensFlareSystemByID = function (id) {
  23454. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23455. if (this.lensFlareSystems[index].id === id) {
  23456. return this.lensFlareSystems[index];
  23457. }
  23458. }
  23459. return null;
  23460. };
  23461. Scene.prototype.getCameraByID = function (id) {
  23462. for (var index = 0; index < this.cameras.length; index++) {
  23463. if (this.cameras[index].id === id) {
  23464. return this.cameras[index];
  23465. }
  23466. }
  23467. return null;
  23468. };
  23469. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23470. for (var index = 0; index < this.cameras.length; index++) {
  23471. if (this.cameras[index].uniqueId === uniqueId) {
  23472. return this.cameras[index];
  23473. }
  23474. }
  23475. return null;
  23476. };
  23477. /**
  23478. * get a camera using its name
  23479. * @param {string} the camera's name
  23480. * @return {BABYLON.Camera|null} the camera or null if none found.
  23481. */
  23482. Scene.prototype.getCameraByName = function (name) {
  23483. for (var index = 0; index < this.cameras.length; index++) {
  23484. if (this.cameras[index].name === name) {
  23485. return this.cameras[index];
  23486. }
  23487. }
  23488. return null;
  23489. };
  23490. /**
  23491. * get a bone using its id
  23492. * @param {string} the bone's id
  23493. * @return {BABYLON.Bone|null} the bone or null if not found
  23494. */
  23495. Scene.prototype.getBoneByID = function (id) {
  23496. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23497. var skeleton = this.skeletons[skeletonIndex];
  23498. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23499. if (skeleton.bones[boneIndex].id === id) {
  23500. return skeleton.bones[boneIndex];
  23501. }
  23502. }
  23503. }
  23504. return null;
  23505. };
  23506. /**
  23507. * get a bone using its id
  23508. * @param {string} the bone's name
  23509. * @return {BABYLON.Bone|null} the bone or null if not found
  23510. */
  23511. Scene.prototype.getBoneByName = function (name) {
  23512. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23513. var skeleton = this.skeletons[skeletonIndex];
  23514. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23515. if (skeleton.bones[boneIndex].name === name) {
  23516. return skeleton.bones[boneIndex];
  23517. }
  23518. }
  23519. }
  23520. return null;
  23521. };
  23522. /**
  23523. * get a light node using its name
  23524. * @param {string} the light's name
  23525. * @return {BABYLON.Light|null} the light or null if none found.
  23526. */
  23527. Scene.prototype.getLightByName = function (name) {
  23528. for (var index = 0; index < this.lights.length; index++) {
  23529. if (this.lights[index].name === name) {
  23530. return this.lights[index];
  23531. }
  23532. }
  23533. return null;
  23534. };
  23535. /**
  23536. * get a light node using its ID
  23537. * @param {string} the light's id
  23538. * @return {BABYLON.Light|null} the light or null if none found.
  23539. */
  23540. Scene.prototype.getLightByID = function (id) {
  23541. for (var index = 0; index < this.lights.length; index++) {
  23542. if (this.lights[index].id === id) {
  23543. return this.lights[index];
  23544. }
  23545. }
  23546. return null;
  23547. };
  23548. /**
  23549. * get a light node using its scene-generated unique ID
  23550. * @param {number} the light's unique id
  23551. * @return {BABYLON.Light|null} the light or null if none found.
  23552. */
  23553. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23554. for (var index = 0; index < this.lights.length; index++) {
  23555. if (this.lights[index].uniqueId === uniqueId) {
  23556. return this.lights[index];
  23557. }
  23558. }
  23559. return null;
  23560. };
  23561. /**
  23562. * get a particle system by id
  23563. * @param id {number} the particle system id
  23564. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23565. */
  23566. Scene.prototype.getParticleSystemByID = function (id) {
  23567. for (var index = 0; index < this.particleSystems.length; index++) {
  23568. if (this.particleSystems[index].id === id) {
  23569. return this.particleSystems[index];
  23570. }
  23571. }
  23572. return null;
  23573. };
  23574. /**
  23575. * get a geometry using its ID
  23576. * @param {string} the geometry's id
  23577. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23578. */
  23579. Scene.prototype.getGeometryByID = function (id) {
  23580. for (var index = 0; index < this._geometries.length; index++) {
  23581. if (this._geometries[index].id === id) {
  23582. return this._geometries[index];
  23583. }
  23584. }
  23585. return null;
  23586. };
  23587. /**
  23588. * add a new geometry to this scene.
  23589. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23590. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23591. * @return {boolean} was the geometry added or not
  23592. */
  23593. Scene.prototype.pushGeometry = function (geometry, force) {
  23594. if (!force && this.getGeometryByID(geometry.id)) {
  23595. return false;
  23596. }
  23597. this._geometries.push(geometry);
  23598. //notify the collision coordinator
  23599. if (this.collisionCoordinator) {
  23600. this.collisionCoordinator.onGeometryAdded(geometry);
  23601. }
  23602. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23603. return true;
  23604. };
  23605. /**
  23606. * Removes an existing geometry
  23607. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23608. * @return {boolean} was the geometry removed or not
  23609. */
  23610. Scene.prototype.removeGeometry = function (geometry) {
  23611. var index = this._geometries.indexOf(geometry);
  23612. if (index > -1) {
  23613. this._geometries.splice(index, 1);
  23614. //notify the collision coordinator
  23615. if (this.collisionCoordinator) {
  23616. this.collisionCoordinator.onGeometryDeleted(geometry);
  23617. }
  23618. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23619. return true;
  23620. }
  23621. return false;
  23622. };
  23623. Scene.prototype.getGeometries = function () {
  23624. return this._geometries;
  23625. };
  23626. /**
  23627. * Get the first added mesh found of a given ID
  23628. * @param {string} id - the id to search for
  23629. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23630. */
  23631. Scene.prototype.getMeshByID = function (id) {
  23632. for (var index = 0; index < this.meshes.length; index++) {
  23633. if (this.meshes[index].id === id) {
  23634. return this.meshes[index];
  23635. }
  23636. }
  23637. return null;
  23638. };
  23639. Scene.prototype.getMeshesByID = function (id) {
  23640. return this.meshes.filter(function (m) {
  23641. return m.id === id;
  23642. });
  23643. };
  23644. /**
  23645. * Get the first added transform node found of a given ID
  23646. * @param {string} id - the id to search for
  23647. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23648. */
  23649. Scene.prototype.getTransformNodeByID = function (id) {
  23650. for (var index = 0; index < this.transformNodes.length; index++) {
  23651. if (this.transformNodes[index].id === id) {
  23652. return this.transformNodes[index];
  23653. }
  23654. }
  23655. return null;
  23656. };
  23657. Scene.prototype.getTransformNodesByID = function (id) {
  23658. return this.transformNodes.filter(function (m) {
  23659. return m.id === id;
  23660. });
  23661. };
  23662. /**
  23663. * Get a mesh with its auto-generated unique id
  23664. * @param {number} uniqueId - the unique id to search for
  23665. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23666. */
  23667. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23668. for (var index = 0; index < this.meshes.length; index++) {
  23669. if (this.meshes[index].uniqueId === uniqueId) {
  23670. return this.meshes[index];
  23671. }
  23672. }
  23673. return null;
  23674. };
  23675. /**
  23676. * Get a the last added mesh found of a given ID
  23677. * @param {string} id - the id to search for
  23678. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23679. */
  23680. Scene.prototype.getLastMeshByID = function (id) {
  23681. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23682. if (this.meshes[index].id === id) {
  23683. return this.meshes[index];
  23684. }
  23685. }
  23686. return null;
  23687. };
  23688. /**
  23689. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23690. * @param {string} id - the id to search for
  23691. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23692. */
  23693. Scene.prototype.getLastEntryByID = function (id) {
  23694. var index;
  23695. for (index = this.meshes.length - 1; index >= 0; index--) {
  23696. if (this.meshes[index].id === id) {
  23697. return this.meshes[index];
  23698. }
  23699. }
  23700. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23701. if (this.transformNodes[index].id === id) {
  23702. return this.transformNodes[index];
  23703. }
  23704. }
  23705. for (index = this.cameras.length - 1; index >= 0; index--) {
  23706. if (this.cameras[index].id === id) {
  23707. return this.cameras[index];
  23708. }
  23709. }
  23710. for (index = this.lights.length - 1; index >= 0; index--) {
  23711. if (this.lights[index].id === id) {
  23712. return this.lights[index];
  23713. }
  23714. }
  23715. return null;
  23716. };
  23717. Scene.prototype.getNodeByID = function (id) {
  23718. var mesh = this.getMeshByID(id);
  23719. if (mesh) {
  23720. return mesh;
  23721. }
  23722. var light = this.getLightByID(id);
  23723. if (light) {
  23724. return light;
  23725. }
  23726. var camera = this.getCameraByID(id);
  23727. if (camera) {
  23728. return camera;
  23729. }
  23730. var bone = this.getBoneByID(id);
  23731. return bone;
  23732. };
  23733. Scene.prototype.getNodeByName = function (name) {
  23734. var mesh = this.getMeshByName(name);
  23735. if (mesh) {
  23736. return mesh;
  23737. }
  23738. var light = this.getLightByName(name);
  23739. if (light) {
  23740. return light;
  23741. }
  23742. var camera = this.getCameraByName(name);
  23743. if (camera) {
  23744. return camera;
  23745. }
  23746. var bone = this.getBoneByName(name);
  23747. return bone;
  23748. };
  23749. Scene.prototype.getMeshByName = function (name) {
  23750. for (var index = 0; index < this.meshes.length; index++) {
  23751. if (this.meshes[index].name === name) {
  23752. return this.meshes[index];
  23753. }
  23754. }
  23755. return null;
  23756. };
  23757. Scene.prototype.getTransformNodeByName = function (name) {
  23758. for (var index = 0; index < this.transformNodes.length; index++) {
  23759. if (this.transformNodes[index].name === name) {
  23760. return this.transformNodes[index];
  23761. }
  23762. }
  23763. return null;
  23764. };
  23765. Scene.prototype.getSoundByName = function (name) {
  23766. var index;
  23767. if (BABYLON.AudioEngine) {
  23768. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23769. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23770. return this.mainSoundTrack.soundCollection[index];
  23771. }
  23772. }
  23773. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23774. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23775. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23776. return this.soundTracks[sdIndex].soundCollection[index];
  23777. }
  23778. }
  23779. }
  23780. }
  23781. return null;
  23782. };
  23783. Scene.prototype.getLastSkeletonByID = function (id) {
  23784. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23785. if (this.skeletons[index].id === id) {
  23786. return this.skeletons[index];
  23787. }
  23788. }
  23789. return null;
  23790. };
  23791. Scene.prototype.getSkeletonById = function (id) {
  23792. for (var index = 0; index < this.skeletons.length; index++) {
  23793. if (this.skeletons[index].id === id) {
  23794. return this.skeletons[index];
  23795. }
  23796. }
  23797. return null;
  23798. };
  23799. Scene.prototype.getSkeletonByName = function (name) {
  23800. for (var index = 0; index < this.skeletons.length; index++) {
  23801. if (this.skeletons[index].name === name) {
  23802. return this.skeletons[index];
  23803. }
  23804. }
  23805. return null;
  23806. };
  23807. Scene.prototype.getMorphTargetManagerById = function (id) {
  23808. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23809. if (this.morphTargetManagers[index].uniqueId === id) {
  23810. return this.morphTargetManagers[index];
  23811. }
  23812. }
  23813. return null;
  23814. };
  23815. Scene.prototype.isActiveMesh = function (mesh) {
  23816. return (this._activeMeshes.indexOf(mesh) !== -1);
  23817. };
  23818. /**
  23819. * Return a the first highlight layer of the scene with a given name.
  23820. * @param name The name of the highlight layer to look for.
  23821. * @return The highlight layer if found otherwise null.
  23822. */
  23823. Scene.prototype.getHighlightLayerByName = function (name) {
  23824. for (var index = 0; index < this.effectLayers.length; index++) {
  23825. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23826. return this.effectLayers[index];
  23827. }
  23828. }
  23829. return null;
  23830. };
  23831. /**
  23832. * Return a the first highlight layer of the scene with a given name.
  23833. * @param name The name of the highlight layer to look for.
  23834. * @return The highlight layer if found otherwise null.
  23835. */
  23836. Scene.prototype.getGlowLayerByName = function (name) {
  23837. for (var index = 0; index < this.effectLayers.length; index++) {
  23838. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23839. return this.effectLayers[index];
  23840. }
  23841. }
  23842. return null;
  23843. };
  23844. Object.defineProperty(Scene.prototype, "uid", {
  23845. /**
  23846. * Return a unique id as a string which can serve as an identifier for the scene
  23847. */
  23848. get: function () {
  23849. if (!this._uid) {
  23850. this._uid = BABYLON.Tools.RandomId();
  23851. }
  23852. return this._uid;
  23853. },
  23854. enumerable: true,
  23855. configurable: true
  23856. });
  23857. /**
  23858. * Add an externaly attached data from its key.
  23859. * This method call will fail and return false, if such key already exists.
  23860. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23861. * @param key the unique key that identifies the data
  23862. * @param data the data object to associate to the key for this Engine instance
  23863. * @return true if no such key were already present and the data was added successfully, false otherwise
  23864. */
  23865. Scene.prototype.addExternalData = function (key, data) {
  23866. if (!this._externalData) {
  23867. this._externalData = new BABYLON.StringDictionary();
  23868. }
  23869. return this._externalData.add(key, data);
  23870. };
  23871. /**
  23872. * Get an externaly attached data from its key
  23873. * @param key the unique key that identifies the data
  23874. * @return the associated data, if present (can be null), or undefined if not present
  23875. */
  23876. Scene.prototype.getExternalData = function (key) {
  23877. if (!this._externalData) {
  23878. return null;
  23879. }
  23880. return this._externalData.get(key);
  23881. };
  23882. /**
  23883. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23884. * @param key the unique key that identifies the data
  23885. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23886. * @return the associated data, can be null if the factory returned null.
  23887. */
  23888. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23889. if (!this._externalData) {
  23890. this._externalData = new BABYLON.StringDictionary();
  23891. }
  23892. return this._externalData.getOrAddWithFactory(key, factory);
  23893. };
  23894. /**
  23895. * Remove an externaly attached data from the Engine instance
  23896. * @param key the unique key that identifies the data
  23897. * @return true if the data was successfully removed, false if it doesn't exist
  23898. */
  23899. Scene.prototype.removeExternalData = function (key) {
  23900. return this._externalData.remove(key);
  23901. };
  23902. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23903. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23904. if (mesh.showSubMeshesBoundingBox) {
  23905. var boundingInfo = subMesh.getBoundingInfo();
  23906. if (boundingInfo !== null && boundingInfo !== undefined) {
  23907. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23908. }
  23909. }
  23910. var material = subMesh.getMaterial();
  23911. if (material !== null && material !== undefined) {
  23912. // Render targets
  23913. if (material.getRenderTargetTextures !== undefined) {
  23914. if (this._processedMaterials.indexOf(material) === -1) {
  23915. this._processedMaterials.push(material);
  23916. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23917. }
  23918. }
  23919. // Dispatch
  23920. this._activeIndices.addCount(subMesh.indexCount, false);
  23921. this._renderingManager.dispatch(subMesh, mesh, material);
  23922. }
  23923. }
  23924. };
  23925. Scene.prototype._isInIntermediateRendering = function () {
  23926. return this._intermediateRendering;
  23927. };
  23928. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23929. this._activeMeshCandidateProvider = provider;
  23930. };
  23931. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23932. return this._activeMeshCandidateProvider;
  23933. };
  23934. /**
  23935. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23936. */
  23937. Scene.prototype.freezeActiveMeshes = function () {
  23938. this._evaluateActiveMeshes();
  23939. this._activeMeshesFrozen = true;
  23940. return this;
  23941. };
  23942. /**
  23943. * Use this function to restart evaluating active meshes on every frame
  23944. */
  23945. Scene.prototype.unfreezeActiveMeshes = function () {
  23946. this._activeMeshesFrozen = false;
  23947. return this;
  23948. };
  23949. Scene.prototype._evaluateActiveMeshes = function () {
  23950. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23951. return;
  23952. }
  23953. if (!this.activeCamera) {
  23954. return;
  23955. }
  23956. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23957. this.activeCamera._activeMeshes.reset();
  23958. this._activeMeshes.reset();
  23959. this._renderingManager.reset();
  23960. this._processedMaterials.reset();
  23961. this._activeParticleSystems.reset();
  23962. this._activeSkeletons.reset();
  23963. this._softwareSkinnedMeshes.reset();
  23964. if (this._boundingBoxRenderer) {
  23965. this._boundingBoxRenderer.reset();
  23966. }
  23967. // Meshes
  23968. var meshes;
  23969. var len;
  23970. var checkIsEnabled = true;
  23971. // Determine mesh candidates
  23972. if (this._activeMeshCandidateProvider !== undefined) {
  23973. // Use _activeMeshCandidateProvider
  23974. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23975. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23976. if (meshes !== undefined) {
  23977. len = meshes.length;
  23978. }
  23979. else {
  23980. len = 0;
  23981. }
  23982. }
  23983. else if (this._selectionOctree !== undefined) {
  23984. // Octree
  23985. var selection = this._selectionOctree.select(this._frustumPlanes);
  23986. meshes = selection.data;
  23987. len = selection.length;
  23988. }
  23989. else {
  23990. // Full scene traversal
  23991. len = this.meshes.length;
  23992. meshes = this.meshes;
  23993. }
  23994. // Check each mesh
  23995. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23996. mesh = meshes[meshIndex];
  23997. if (mesh.isBlocked) {
  23998. continue;
  23999. }
  24000. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24001. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24002. continue;
  24003. }
  24004. mesh.computeWorldMatrix();
  24005. // Intersections
  24006. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24007. this._meshesForIntersections.pushNoDuplicate(mesh);
  24008. }
  24009. // Switch to current LOD
  24010. meshLOD = mesh.getLOD(this.activeCamera);
  24011. if (meshLOD === undefined || meshLOD === null) {
  24012. continue;
  24013. }
  24014. mesh._preActivate();
  24015. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24016. this._activeMeshes.push(mesh);
  24017. this.activeCamera._activeMeshes.push(mesh);
  24018. mesh._activate(this._renderId);
  24019. if (meshLOD !== mesh) {
  24020. meshLOD._activate(this._renderId);
  24021. }
  24022. this._activeMesh(mesh, meshLOD);
  24023. }
  24024. }
  24025. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24026. // Particle systems
  24027. if (this.particlesEnabled) {
  24028. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24029. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24030. var particleSystem = this.particleSystems[particleIndex];
  24031. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24032. continue;
  24033. }
  24034. var emitter = particleSystem.emitter;
  24035. if (!emitter.position || emitter.isEnabled()) {
  24036. this._activeParticleSystems.push(particleSystem);
  24037. particleSystem.animate();
  24038. this._renderingManager.dispatchParticles(particleSystem);
  24039. }
  24040. }
  24041. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24042. }
  24043. };
  24044. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24045. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24046. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24047. mesh.skeleton.prepare();
  24048. }
  24049. if (!mesh.computeBonesUsingShaders) {
  24050. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24051. }
  24052. }
  24053. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24054. var boundingInfo = sourceMesh.getBoundingInfo();
  24055. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24056. }
  24057. if (mesh !== undefined && mesh !== null
  24058. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24059. // Submeshes Octrees
  24060. var len;
  24061. var subMeshes;
  24062. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24063. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24064. len = intersections.length;
  24065. subMeshes = intersections.data;
  24066. }
  24067. else {
  24068. subMeshes = mesh.subMeshes;
  24069. len = subMeshes.length;
  24070. }
  24071. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24072. subMesh = subMeshes[subIndex];
  24073. this._evaluateSubMesh(subMesh, mesh);
  24074. }
  24075. }
  24076. };
  24077. Scene.prototype.updateTransformMatrix = function (force) {
  24078. if (!this.activeCamera) {
  24079. return;
  24080. }
  24081. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24082. };
  24083. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24084. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24085. };
  24086. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24087. if (camera && camera._skipRendering) {
  24088. return;
  24089. }
  24090. var engine = this._engine;
  24091. this.activeCamera = camera;
  24092. if (!this.activeCamera)
  24093. throw new Error("Active camera not set");
  24094. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24095. // Viewport
  24096. engine.setViewport(this.activeCamera.viewport);
  24097. // Camera
  24098. this.resetCachedMaterial();
  24099. this._renderId++;
  24100. this.updateTransformMatrix();
  24101. if (camera._alternateCamera) {
  24102. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24103. this._alternateRendering = true;
  24104. }
  24105. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24106. // Meshes
  24107. this._evaluateActiveMeshes();
  24108. // Software skinning
  24109. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24110. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24111. mesh.applySkeleton(mesh.skeleton);
  24112. }
  24113. // Render targets
  24114. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24115. var needsRestoreFrameBuffer = false;
  24116. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24117. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24118. }
  24119. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24120. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24121. }
  24122. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24123. this._intermediateRendering = true;
  24124. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24125. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24126. var renderTarget = this._renderTargets.data[renderIndex];
  24127. if (renderTarget._shouldRender()) {
  24128. this._renderId++;
  24129. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24130. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24131. }
  24132. }
  24133. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24134. this._intermediateRendering = false;
  24135. this._renderId++;
  24136. needsRestoreFrameBuffer = true; // Restore back buffer
  24137. }
  24138. // Render EffecttLayer Texture
  24139. var stencilState = this._engine.getStencilBuffer();
  24140. var renderEffects = false;
  24141. var needStencil = false;
  24142. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24143. this._intermediateRendering = true;
  24144. for (var i = 0; i < this.effectLayers.length; i++) {
  24145. var effectLayer = this.effectLayers[i];
  24146. if (effectLayer.shouldRender() &&
  24147. (!effectLayer.camera ||
  24148. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24149. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24150. renderEffects = true;
  24151. needStencil = needStencil || effectLayer.needStencil();
  24152. var renderTarget = effectLayer._mainTexture;
  24153. if (renderTarget._shouldRender()) {
  24154. this._renderId++;
  24155. renderTarget.render(false, false);
  24156. needsRestoreFrameBuffer = true;
  24157. }
  24158. }
  24159. }
  24160. this._intermediateRendering = false;
  24161. this._renderId++;
  24162. }
  24163. if (needsRestoreFrameBuffer) {
  24164. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24165. }
  24166. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24167. // Prepare Frame
  24168. this.postProcessManager._prepareFrame();
  24169. // Backgrounds
  24170. var layerIndex;
  24171. var layer;
  24172. if (this.layers.length) {
  24173. engine.setDepthBuffer(false);
  24174. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24175. layer = this.layers[layerIndex];
  24176. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24177. layer.render();
  24178. }
  24179. }
  24180. engine.setDepthBuffer(true);
  24181. }
  24182. // Activate effect Layer stencil
  24183. if (needStencil) {
  24184. this._engine.setStencilBuffer(true);
  24185. }
  24186. // Render
  24187. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24188. this._renderingManager.render(null, null, true, true);
  24189. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24190. // Restore effect Layer stencil
  24191. if (needStencil) {
  24192. this._engine.setStencilBuffer(stencilState);
  24193. }
  24194. // Bounding boxes
  24195. if (this._boundingBoxRenderer) {
  24196. this._boundingBoxRenderer.render();
  24197. }
  24198. // Lens flares
  24199. if (this.lensFlaresEnabled) {
  24200. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24201. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24202. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24203. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24204. lensFlareSystem.render();
  24205. }
  24206. }
  24207. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24208. }
  24209. // Foregrounds
  24210. if (this.layers.length) {
  24211. engine.setDepthBuffer(false);
  24212. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24213. layer = this.layers[layerIndex];
  24214. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24215. layer.render();
  24216. }
  24217. }
  24218. engine.setDepthBuffer(true);
  24219. }
  24220. // Effect Layer
  24221. if (renderEffects) {
  24222. engine.setDepthBuffer(false);
  24223. for (var i = 0; i < this.effectLayers.length; i++) {
  24224. if (this.effectLayers[i].shouldRender()) {
  24225. this.effectLayers[i].render();
  24226. }
  24227. }
  24228. engine.setDepthBuffer(true);
  24229. }
  24230. // Finalize frame
  24231. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24232. // Reset some special arrays
  24233. this._renderTargets.reset();
  24234. this._alternateRendering = false;
  24235. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24236. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24237. };
  24238. Scene.prototype._processSubCameras = function (camera) {
  24239. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24240. this._renderForCamera(camera);
  24241. return;
  24242. }
  24243. // rig cameras
  24244. for (var index = 0; index < camera._rigCameras.length; index++) {
  24245. this._renderForCamera(camera._rigCameras[index], camera);
  24246. }
  24247. this.activeCamera = camera;
  24248. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24249. };
  24250. Scene.prototype._checkIntersections = function () {
  24251. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24252. var sourceMesh = this._meshesForIntersections.data[index];
  24253. if (!sourceMesh.actionManager) {
  24254. continue;
  24255. }
  24256. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24257. var action = sourceMesh.actionManager.actions[actionIndex];
  24258. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24259. var parameters = action.getTriggerParameter();
  24260. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24261. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24262. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24263. if (areIntersecting && currentIntersectionInProgress === -1) {
  24264. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24265. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24266. sourceMesh._intersectionsInProgress.push(otherMesh);
  24267. }
  24268. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24269. sourceMesh._intersectionsInProgress.push(otherMesh);
  24270. }
  24271. }
  24272. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24273. //They intersected, and now they don't.
  24274. //is this trigger an exit trigger? execute an event.
  24275. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24276. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24277. }
  24278. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24279. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24280. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24281. }
  24282. }
  24283. }
  24284. }
  24285. }
  24286. };
  24287. Scene.prototype.render = function () {
  24288. if (this.isDisposed) {
  24289. return;
  24290. }
  24291. this._activeParticles.fetchNewFrame();
  24292. this._totalVertices.fetchNewFrame();
  24293. this._activeIndices.fetchNewFrame();
  24294. this._activeBones.fetchNewFrame();
  24295. this._meshesForIntersections.reset();
  24296. this.resetCachedMaterial();
  24297. this.onBeforeAnimationsObservable.notifyObservers(this);
  24298. // Actions
  24299. if (this.actionManager) {
  24300. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24301. }
  24302. //Simplification Queue
  24303. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24304. this.simplificationQueue.executeNext();
  24305. }
  24306. if (this._engine.isDeterministicLockStep()) {
  24307. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24308. var defaultFPS = (60.0 / 1000.0);
  24309. var defaultFrameTime = 1000 / 60; // frame time in MS
  24310. if (this._physicsEngine) {
  24311. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24312. }
  24313. var stepsTaken = 0;
  24314. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24315. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24316. internalSteps = Math.min(internalSteps, maxSubSteps);
  24317. do {
  24318. this.onBeforeStepObservable.notifyObservers(this);
  24319. // Animations
  24320. this._animationRatio = defaultFrameTime * defaultFPS;
  24321. this._animate();
  24322. this.onAfterAnimationsObservable.notifyObservers(this);
  24323. // Physics
  24324. if (this._physicsEngine) {
  24325. this.onBeforePhysicsObservable.notifyObservers(this);
  24326. this._physicsEngine._step(defaultFrameTime / 1000);
  24327. this.onAfterPhysicsObservable.notifyObservers(this);
  24328. }
  24329. this.onAfterStepObservable.notifyObservers(this);
  24330. this._currentStepId++;
  24331. stepsTaken++;
  24332. deltaTime -= defaultFrameTime;
  24333. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24334. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24335. }
  24336. else {
  24337. // Animations
  24338. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24339. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24340. this._animate();
  24341. this.onAfterAnimationsObservable.notifyObservers(this);
  24342. // Physics
  24343. if (this._physicsEngine) {
  24344. this.onBeforePhysicsObservable.notifyObservers(this);
  24345. this._physicsEngine._step(deltaTime / 1000.0);
  24346. this.onAfterPhysicsObservable.notifyObservers(this);
  24347. }
  24348. }
  24349. // update gamepad manager
  24350. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24351. this._gamepadManager._checkGamepadsStatus();
  24352. }
  24353. // Before render
  24354. this.onBeforeRenderObservable.notifyObservers(this);
  24355. // Update Cameras
  24356. if (this.activeCameras.length > 0) {
  24357. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24358. var camera = this.activeCameras[cameraIndex];
  24359. camera.update();
  24360. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24361. // rig cameras
  24362. for (var index = 0; index < camera._rigCameras.length; index++) {
  24363. camera._rigCameras[index].update();
  24364. }
  24365. }
  24366. }
  24367. }
  24368. else if (this.activeCamera) {
  24369. this.activeCamera.update();
  24370. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24371. // rig cameras
  24372. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24373. this.activeCamera._rigCameras[index].update();
  24374. }
  24375. }
  24376. }
  24377. // Customs render targets
  24378. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24379. var engine = this.getEngine();
  24380. var currentActiveCamera = this.activeCamera;
  24381. if (this.renderTargetsEnabled) {
  24382. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24383. this._intermediateRendering = true;
  24384. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24385. var renderTarget = this.customRenderTargets[customIndex];
  24386. if (renderTarget._shouldRender()) {
  24387. this._renderId++;
  24388. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24389. if (!this.activeCamera)
  24390. throw new Error("Active camera not set");
  24391. // Viewport
  24392. engine.setViewport(this.activeCamera.viewport);
  24393. // Camera
  24394. this.updateTransformMatrix();
  24395. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24396. }
  24397. }
  24398. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24399. this._intermediateRendering = false;
  24400. this._renderId++;
  24401. }
  24402. // Restore back buffer
  24403. if (this.customRenderTargets.length > 0) {
  24404. engine.restoreDefaultFramebuffer();
  24405. }
  24406. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24407. this.activeCamera = currentActiveCamera;
  24408. // Procedural textures
  24409. if (this.proceduralTexturesEnabled) {
  24410. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24411. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24412. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24413. if (proceduralTexture._shouldRender()) {
  24414. proceduralTexture.render();
  24415. }
  24416. }
  24417. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24418. }
  24419. // Clear
  24420. if (this.autoClearDepthAndStencil || this.autoClear) {
  24421. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24422. }
  24423. // Shadows
  24424. if (this.shadowsEnabled) {
  24425. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24426. var light = this.lights[lightIndex];
  24427. var shadowGenerator = light.getShadowGenerator();
  24428. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24429. var shadowMap = (shadowGenerator.getShadowMap());
  24430. if (this.textures.indexOf(shadowMap) !== -1) {
  24431. this._renderTargets.push(shadowMap);
  24432. }
  24433. }
  24434. }
  24435. }
  24436. // Depth renderer
  24437. for (var key in this._depthRenderer) {
  24438. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24439. }
  24440. // Geometry renderer
  24441. if (this._geometryBufferRenderer) {
  24442. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24443. }
  24444. // RenderPipeline
  24445. if (this._postProcessRenderPipelineManager) {
  24446. this._postProcessRenderPipelineManager.update();
  24447. }
  24448. // Multi-cameras?
  24449. if (this.activeCameras.length > 0) {
  24450. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24451. if (cameraIndex > 0) {
  24452. this._engine.clear(null, false, true, true);
  24453. }
  24454. this._processSubCameras(this.activeCameras[cameraIndex]);
  24455. }
  24456. }
  24457. else {
  24458. if (!this.activeCamera) {
  24459. throw new Error("No camera defined");
  24460. }
  24461. this._processSubCameras(this.activeCamera);
  24462. }
  24463. // Intersection checks
  24464. this._checkIntersections();
  24465. // Update the audio listener attached to the camera
  24466. if (BABYLON.AudioEngine) {
  24467. this._updateAudioParameters();
  24468. }
  24469. // After render
  24470. if (this.afterRender) {
  24471. this.afterRender();
  24472. }
  24473. this.onAfterRenderObservable.notifyObservers(this);
  24474. // Cleaning
  24475. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24476. var data = this._toBeDisposed.data[index];
  24477. if (data) {
  24478. data.dispose();
  24479. }
  24480. this._toBeDisposed[index] = null;
  24481. }
  24482. this._toBeDisposed.reset();
  24483. if (this.dumpNextRenderTargets) {
  24484. this.dumpNextRenderTargets = false;
  24485. }
  24486. this._activeBones.addCount(0, true);
  24487. this._activeIndices.addCount(0, true);
  24488. this._activeParticles.addCount(0, true);
  24489. };
  24490. Scene.prototype._updateAudioParameters = function () {
  24491. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24492. return;
  24493. }
  24494. var listeningCamera;
  24495. var audioEngine = BABYLON.Engine.audioEngine;
  24496. if (this.activeCameras.length > 0) {
  24497. listeningCamera = this.activeCameras[0];
  24498. }
  24499. else {
  24500. listeningCamera = this.activeCamera;
  24501. }
  24502. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24503. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24504. // for VR cameras
  24505. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24506. listeningCamera = listeningCamera.rigCameras[0];
  24507. }
  24508. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24509. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24510. cameraDirection.normalize();
  24511. // To avoid some errors on GearVR
  24512. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24513. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24514. }
  24515. var i;
  24516. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24517. var sound = this.mainSoundTrack.soundCollection[i];
  24518. if (sound.useCustomAttenuation) {
  24519. sound.updateDistanceFromListener();
  24520. }
  24521. }
  24522. for (i = 0; i < this.soundTracks.length; i++) {
  24523. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24524. sound = this.soundTracks[i].soundCollection[j];
  24525. if (sound.useCustomAttenuation) {
  24526. sound.updateDistanceFromListener();
  24527. }
  24528. }
  24529. }
  24530. }
  24531. };
  24532. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24533. // Audio
  24534. get: function () {
  24535. return this._audioEnabled;
  24536. },
  24537. set: function (value) {
  24538. this._audioEnabled = value;
  24539. if (BABYLON.AudioEngine) {
  24540. if (this._audioEnabled) {
  24541. this._enableAudio();
  24542. }
  24543. else {
  24544. this._disableAudio();
  24545. }
  24546. }
  24547. },
  24548. enumerable: true,
  24549. configurable: true
  24550. });
  24551. Scene.prototype._disableAudio = function () {
  24552. var i;
  24553. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24554. this.mainSoundTrack.soundCollection[i].pause();
  24555. }
  24556. for (i = 0; i < this.soundTracks.length; i++) {
  24557. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24558. this.soundTracks[i].soundCollection[j].pause();
  24559. }
  24560. }
  24561. };
  24562. Scene.prototype._enableAudio = function () {
  24563. var i;
  24564. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24565. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24566. this.mainSoundTrack.soundCollection[i].play();
  24567. }
  24568. }
  24569. for (i = 0; i < this.soundTracks.length; i++) {
  24570. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24571. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24572. this.soundTracks[i].soundCollection[j].play();
  24573. }
  24574. }
  24575. }
  24576. };
  24577. Object.defineProperty(Scene.prototype, "headphone", {
  24578. get: function () {
  24579. return this._headphone;
  24580. },
  24581. set: function (value) {
  24582. this._headphone = value;
  24583. if (BABYLON.AudioEngine) {
  24584. if (this._headphone) {
  24585. this._switchAudioModeForHeadphones();
  24586. }
  24587. else {
  24588. this._switchAudioModeForNormalSpeakers();
  24589. }
  24590. }
  24591. },
  24592. enumerable: true,
  24593. configurable: true
  24594. });
  24595. Scene.prototype._switchAudioModeForHeadphones = function () {
  24596. this.mainSoundTrack.switchPanningModelToHRTF();
  24597. for (var i = 0; i < this.soundTracks.length; i++) {
  24598. this.soundTracks[i].switchPanningModelToHRTF();
  24599. }
  24600. };
  24601. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24602. this.mainSoundTrack.switchPanningModelToEqualPower();
  24603. for (var i = 0; i < this.soundTracks.length; i++) {
  24604. this.soundTracks[i].switchPanningModelToEqualPower();
  24605. }
  24606. };
  24607. /**
  24608. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24609. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24610. * @returns the created depth renderer
  24611. */
  24612. Scene.prototype.enableDepthRenderer = function (camera) {
  24613. camera = camera || this.activeCamera;
  24614. if (!camera) {
  24615. throw "No camera available to enable depth renderer";
  24616. }
  24617. if (!this._depthRenderer[camera.id]) {
  24618. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24619. }
  24620. return this._depthRenderer[camera.id];
  24621. };
  24622. /**
  24623. * Disables a depth renderer for a given camera
  24624. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24625. */
  24626. Scene.prototype.disableDepthRenderer = function (camera) {
  24627. camera = camera || this.activeCamera;
  24628. if (!camera || !this._depthRenderer[camera.id]) {
  24629. return;
  24630. }
  24631. this._depthRenderer[camera.id].dispose();
  24632. delete this._depthRenderer[camera.id];
  24633. };
  24634. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24635. if (ratio === void 0) { ratio = 1; }
  24636. if (this._geometryBufferRenderer) {
  24637. return this._geometryBufferRenderer;
  24638. }
  24639. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24640. if (!this._geometryBufferRenderer.isSupported) {
  24641. this._geometryBufferRenderer = null;
  24642. }
  24643. return this._geometryBufferRenderer;
  24644. };
  24645. Scene.prototype.disableGeometryBufferRenderer = function () {
  24646. if (!this._geometryBufferRenderer) {
  24647. return;
  24648. }
  24649. this._geometryBufferRenderer.dispose();
  24650. this._geometryBufferRenderer = null;
  24651. };
  24652. Scene.prototype.freezeMaterials = function () {
  24653. for (var i = 0; i < this.materials.length; i++) {
  24654. this.materials[i].freeze();
  24655. }
  24656. };
  24657. Scene.prototype.unfreezeMaterials = function () {
  24658. for (var i = 0; i < this.materials.length; i++) {
  24659. this.materials[i].unfreeze();
  24660. }
  24661. };
  24662. Scene.prototype.dispose = function () {
  24663. this.beforeRender = null;
  24664. this.afterRender = null;
  24665. this.skeletons = [];
  24666. this.morphTargetManagers = [];
  24667. this.importedMeshesFiles = new Array();
  24668. this.stopAllAnimations();
  24669. this.resetCachedMaterial();
  24670. for (var key in this._depthRenderer) {
  24671. this._depthRenderer[key].dispose();
  24672. }
  24673. if (this._gamepadManager) {
  24674. this._gamepadManager.dispose();
  24675. this._gamepadManager = null;
  24676. }
  24677. // Smart arrays
  24678. if (this.activeCamera) {
  24679. this.activeCamera._activeMeshes.dispose();
  24680. this.activeCamera = null;
  24681. }
  24682. this._activeMeshes.dispose();
  24683. this._renderingManager.dispose();
  24684. this._processedMaterials.dispose();
  24685. this._activeParticleSystems.dispose();
  24686. this._activeSkeletons.dispose();
  24687. this._softwareSkinnedMeshes.dispose();
  24688. this._renderTargets.dispose();
  24689. if (this._boundingBoxRenderer) {
  24690. this._boundingBoxRenderer.dispose();
  24691. }
  24692. this._meshesForIntersections.dispose();
  24693. this._toBeDisposed.dispose();
  24694. // Abort active requests
  24695. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24696. var request = _a[_i];
  24697. request.abort();
  24698. }
  24699. // Debug layer
  24700. if (this._debugLayer) {
  24701. this._debugLayer.hide();
  24702. }
  24703. // Events
  24704. this.onDisposeObservable.notifyObservers(this);
  24705. this.onDisposeObservable.clear();
  24706. this.onBeforeRenderObservable.clear();
  24707. this.onAfterRenderObservable.clear();
  24708. this.OnBeforeRenderTargetsRenderObservable.clear();
  24709. this.OnAfterRenderTargetsRenderObservable.clear();
  24710. this.onAfterStepObservable.clear();
  24711. this.onBeforeStepObservable.clear();
  24712. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24713. this.onAfterActiveMeshesEvaluationObservable.clear();
  24714. this.onBeforeParticlesRenderingObservable.clear();
  24715. this.onAfterParticlesRenderingObservable.clear();
  24716. this.onBeforeSpritesRenderingObservable.clear();
  24717. this.onAfterSpritesRenderingObservable.clear();
  24718. this.onBeforeDrawPhaseObservable.clear();
  24719. this.onAfterDrawPhaseObservable.clear();
  24720. this.onBeforePhysicsObservable.clear();
  24721. this.onAfterPhysicsObservable.clear();
  24722. this.onBeforeAnimationsObservable.clear();
  24723. this.onAfterAnimationsObservable.clear();
  24724. this.onDataLoadedObservable.clear();
  24725. this.detachControl();
  24726. // Release sounds & sounds tracks
  24727. if (BABYLON.AudioEngine) {
  24728. this.disposeSounds();
  24729. }
  24730. // VR Helper
  24731. if (this.VRHelper) {
  24732. this.VRHelper.dispose();
  24733. }
  24734. // Detach cameras
  24735. var canvas = this._engine.getRenderingCanvas();
  24736. if (canvas) {
  24737. var index;
  24738. for (index = 0; index < this.cameras.length; index++) {
  24739. this.cameras[index].detachControl(canvas);
  24740. }
  24741. }
  24742. // Release animation groups
  24743. while (this.animationGroups.length) {
  24744. this.animationGroups[0].dispose();
  24745. }
  24746. // Release lights
  24747. while (this.lights.length) {
  24748. this.lights[0].dispose();
  24749. }
  24750. // Release meshes
  24751. while (this.meshes.length) {
  24752. this.meshes[0].dispose(true);
  24753. }
  24754. while (this.transformNodes.length) {
  24755. this.removeTransformNode(this.transformNodes[0]);
  24756. }
  24757. // Release cameras
  24758. while (this.cameras.length) {
  24759. this.cameras[0].dispose();
  24760. }
  24761. // Release materials
  24762. if (this.defaultMaterial) {
  24763. this.defaultMaterial.dispose();
  24764. }
  24765. while (this.multiMaterials.length) {
  24766. this.multiMaterials[0].dispose();
  24767. }
  24768. while (this.materials.length) {
  24769. this.materials[0].dispose();
  24770. }
  24771. // Release particles
  24772. while (this.particleSystems.length) {
  24773. this.particleSystems[0].dispose();
  24774. }
  24775. // Release sprites
  24776. while (this.spriteManagers.length) {
  24777. this.spriteManagers[0].dispose();
  24778. }
  24779. // Release postProcesses
  24780. while (this.postProcesses.length) {
  24781. this.postProcesses[0].dispose();
  24782. }
  24783. // Release layers
  24784. while (this.layers.length) {
  24785. this.layers[0].dispose();
  24786. }
  24787. while (this.effectLayers.length) {
  24788. this.effectLayers[0].dispose();
  24789. }
  24790. // Release textures
  24791. while (this.textures.length) {
  24792. this.textures[0].dispose();
  24793. }
  24794. // Release UBO
  24795. this._sceneUbo.dispose();
  24796. if (this._alternateSceneUbo) {
  24797. this._alternateSceneUbo.dispose();
  24798. }
  24799. // Post-processes
  24800. this.postProcessManager.dispose();
  24801. if (this._postProcessRenderPipelineManager) {
  24802. this._postProcessRenderPipelineManager.dispose();
  24803. }
  24804. // Physics
  24805. if (this._physicsEngine) {
  24806. this.disablePhysicsEngine();
  24807. }
  24808. // Remove from engine
  24809. index = this._engine.scenes.indexOf(this);
  24810. if (index > -1) {
  24811. this._engine.scenes.splice(index, 1);
  24812. }
  24813. this._engine.wipeCaches(true);
  24814. this._isDisposed = true;
  24815. };
  24816. Object.defineProperty(Scene.prototype, "isDisposed", {
  24817. get: function () {
  24818. return this._isDisposed;
  24819. },
  24820. enumerable: true,
  24821. configurable: true
  24822. });
  24823. // Release sounds & sounds tracks
  24824. Scene.prototype.disposeSounds = function () {
  24825. if (!this._mainSoundTrack) {
  24826. return;
  24827. }
  24828. this.mainSoundTrack.dispose();
  24829. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24830. this.soundTracks[scIndex].dispose();
  24831. }
  24832. };
  24833. // Octrees
  24834. /**
  24835. * Get the world extend vectors with an optional filter
  24836. *
  24837. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24838. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24839. */
  24840. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24841. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24842. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24843. filterPredicate = filterPredicate || (function () { return true; });
  24844. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24845. mesh.computeWorldMatrix(true);
  24846. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24847. return;
  24848. }
  24849. var boundingInfo = mesh.getBoundingInfo();
  24850. var minBox = boundingInfo.boundingBox.minimumWorld;
  24851. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24852. BABYLON.Tools.CheckExtends(minBox, min, max);
  24853. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24854. });
  24855. return {
  24856. min: min,
  24857. max: max
  24858. };
  24859. };
  24860. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24861. if (maxCapacity === void 0) { maxCapacity = 64; }
  24862. if (maxDepth === void 0) { maxDepth = 2; }
  24863. if (!this._selectionOctree) {
  24864. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24865. }
  24866. var worldExtends = this.getWorldExtends();
  24867. // Update octree
  24868. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24869. return this._selectionOctree;
  24870. };
  24871. // Picking
  24872. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24873. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24874. var result = BABYLON.Ray.Zero();
  24875. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24876. return result;
  24877. };
  24878. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24879. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24880. var engine = this._engine;
  24881. if (!camera) {
  24882. if (!this.activeCamera)
  24883. throw new Error("Active camera not set");
  24884. camera = this.activeCamera;
  24885. }
  24886. var cameraViewport = camera.viewport;
  24887. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24888. // Moving coordinates to local viewport world
  24889. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24890. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24891. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24892. return this;
  24893. };
  24894. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24895. var result = BABYLON.Ray.Zero();
  24896. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24897. return result;
  24898. };
  24899. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24900. if (!BABYLON.PickingInfo) {
  24901. return this;
  24902. }
  24903. var engine = this._engine;
  24904. if (!camera) {
  24905. if (!this.activeCamera)
  24906. throw new Error("Active camera not set");
  24907. camera = this.activeCamera;
  24908. }
  24909. var cameraViewport = camera.viewport;
  24910. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24911. var identity = BABYLON.Matrix.Identity();
  24912. // Moving coordinates to local viewport world
  24913. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24914. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24915. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24916. return this;
  24917. };
  24918. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24919. if (!BABYLON.PickingInfo) {
  24920. return null;
  24921. }
  24922. var pickingInfo = null;
  24923. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24924. var mesh = this.meshes[meshIndex];
  24925. if (predicate) {
  24926. if (!predicate(mesh)) {
  24927. continue;
  24928. }
  24929. }
  24930. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24931. continue;
  24932. }
  24933. var world = mesh.getWorldMatrix();
  24934. var ray = rayFunction(world);
  24935. var result = mesh.intersects(ray, fastCheck);
  24936. if (!result || !result.hit)
  24937. continue;
  24938. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24939. continue;
  24940. pickingInfo = result;
  24941. if (fastCheck) {
  24942. break;
  24943. }
  24944. }
  24945. return pickingInfo || new BABYLON.PickingInfo();
  24946. };
  24947. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24948. if (!BABYLON.PickingInfo) {
  24949. return null;
  24950. }
  24951. var pickingInfos = new Array();
  24952. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24953. var mesh = this.meshes[meshIndex];
  24954. if (predicate) {
  24955. if (!predicate(mesh)) {
  24956. continue;
  24957. }
  24958. }
  24959. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24960. continue;
  24961. }
  24962. var world = mesh.getWorldMatrix();
  24963. var ray = rayFunction(world);
  24964. var result = mesh.intersects(ray, false);
  24965. if (!result || !result.hit)
  24966. continue;
  24967. pickingInfos.push(result);
  24968. }
  24969. return pickingInfos;
  24970. };
  24971. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24972. if (!BABYLON.PickingInfo) {
  24973. return null;
  24974. }
  24975. var pickingInfo = null;
  24976. if (!camera) {
  24977. if (!this.activeCamera) {
  24978. return null;
  24979. }
  24980. camera = this.activeCamera;
  24981. }
  24982. if (this.spriteManagers.length > 0) {
  24983. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24984. var spriteManager = this.spriteManagers[spriteIndex];
  24985. if (!spriteManager.isPickable) {
  24986. continue;
  24987. }
  24988. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24989. if (!result || !result.hit)
  24990. continue;
  24991. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24992. continue;
  24993. pickingInfo = result;
  24994. if (fastCheck) {
  24995. break;
  24996. }
  24997. }
  24998. }
  24999. return pickingInfo || new BABYLON.PickingInfo();
  25000. };
  25001. /** Launch a ray to try to pick a mesh in the scene
  25002. * @param x position on screen
  25003. * @param y position on screen
  25004. * @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
  25005. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25006. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25007. */
  25008. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25009. var _this = this;
  25010. if (!BABYLON.PickingInfo) {
  25011. return null;
  25012. }
  25013. return this._internalPick(function (world) {
  25014. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25015. return _this._tempPickingRay;
  25016. }, predicate, fastCheck);
  25017. };
  25018. /** Launch a ray to try to pick a sprite in the scene
  25019. * @param x position on screen
  25020. * @param y position on screen
  25021. * @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
  25022. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25023. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25024. */
  25025. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25026. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25027. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25028. };
  25029. /** Use the given ray to pick a mesh in the scene
  25030. * @param ray The ray to use to pick meshes
  25031. * @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
  25032. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25033. */
  25034. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25035. var _this = this;
  25036. return this._internalPick(function (world) {
  25037. if (!_this._pickWithRayInverseMatrix) {
  25038. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25039. }
  25040. world.invertToRef(_this._pickWithRayInverseMatrix);
  25041. if (!_this._cachedRayForTransform) {
  25042. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25043. }
  25044. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25045. return _this._cachedRayForTransform;
  25046. }, predicate, fastCheck);
  25047. };
  25048. /**
  25049. * Launch a ray to try to pick a mesh in the scene
  25050. * @param x X position on screen
  25051. * @param y Y position on screen
  25052. * @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
  25053. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25054. */
  25055. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25056. var _this = this;
  25057. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25058. };
  25059. /**
  25060. * Launch a ray to try to pick a mesh in the scene
  25061. * @param ray Ray to use
  25062. * @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
  25063. */
  25064. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25065. var _this = this;
  25066. return this._internalMultiPick(function (world) {
  25067. if (!_this._pickWithRayInverseMatrix) {
  25068. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25069. }
  25070. world.invertToRef(_this._pickWithRayInverseMatrix);
  25071. if (!_this._cachedRayForTransform) {
  25072. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25073. }
  25074. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25075. return _this._cachedRayForTransform;
  25076. }, predicate);
  25077. };
  25078. Scene.prototype.setPointerOverMesh = function (mesh) {
  25079. if (this._pointerOverMesh === mesh) {
  25080. return;
  25081. }
  25082. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25083. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25084. }
  25085. this._pointerOverMesh = mesh;
  25086. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25087. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25088. }
  25089. };
  25090. Scene.prototype.getPointerOverMesh = function () {
  25091. return this._pointerOverMesh;
  25092. };
  25093. Scene.prototype.setPointerOverSprite = function (sprite) {
  25094. if (this._pointerOverSprite === sprite) {
  25095. return;
  25096. }
  25097. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25098. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25099. }
  25100. this._pointerOverSprite = sprite;
  25101. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25102. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25103. }
  25104. };
  25105. Scene.prototype.getPointerOverSprite = function () {
  25106. return this._pointerOverSprite;
  25107. };
  25108. // Physics
  25109. Scene.prototype.getPhysicsEngine = function () {
  25110. return this._physicsEngine;
  25111. };
  25112. /**
  25113. * Enables physics to the current scene
  25114. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25115. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25116. * @return {boolean} was the physics engine initialized
  25117. */
  25118. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25119. if (gravity === void 0) { gravity = null; }
  25120. if (this._physicsEngine) {
  25121. return true;
  25122. }
  25123. try {
  25124. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25125. return true;
  25126. }
  25127. catch (e) {
  25128. BABYLON.Tools.Error(e.message);
  25129. return false;
  25130. }
  25131. };
  25132. Scene.prototype.disablePhysicsEngine = function () {
  25133. if (!this._physicsEngine) {
  25134. return;
  25135. }
  25136. this._physicsEngine.dispose();
  25137. this._physicsEngine = null;
  25138. };
  25139. Scene.prototype.isPhysicsEnabled = function () {
  25140. return this._physicsEngine !== undefined;
  25141. };
  25142. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25143. var mesh = compound.parts[0].mesh;
  25144. if (mesh.physicsImpostor) {
  25145. mesh.physicsImpostor.dispose();
  25146. mesh.physicsImpostor = null;
  25147. }
  25148. };
  25149. // Misc.
  25150. Scene.prototype._rebuildGeometries = function () {
  25151. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25152. var geometry = _a[_i];
  25153. geometry._rebuild();
  25154. }
  25155. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25156. var mesh = _c[_b];
  25157. mesh._rebuild();
  25158. }
  25159. if (this.postProcessManager) {
  25160. this.postProcessManager._rebuild();
  25161. }
  25162. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25163. var layer = _e[_d];
  25164. layer._rebuild();
  25165. }
  25166. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25167. var effectLayer = _g[_f];
  25168. effectLayer._rebuild();
  25169. }
  25170. if (this._boundingBoxRenderer) {
  25171. this._boundingBoxRenderer._rebuild();
  25172. }
  25173. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25174. var system = _j[_h];
  25175. system.rebuild();
  25176. }
  25177. if (this._postProcessRenderPipelineManager) {
  25178. this._postProcessRenderPipelineManager._rebuild();
  25179. }
  25180. };
  25181. Scene.prototype._rebuildTextures = function () {
  25182. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25183. var texture = _a[_i];
  25184. texture._rebuild();
  25185. }
  25186. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25187. };
  25188. /**
  25189. * Creates a default light for the scene.
  25190. * @param replace Whether to replace the existing lights in the scene.
  25191. */
  25192. Scene.prototype.createDefaultLight = function (replace) {
  25193. if (replace === void 0) { replace = false; }
  25194. // Dispose existing light in replace mode.
  25195. if (replace) {
  25196. if (this.lights) {
  25197. for (var i = 0; i < this.lights.length; i++) {
  25198. this.lights[i].dispose();
  25199. }
  25200. }
  25201. }
  25202. // Light
  25203. if (this.lights.length === 0) {
  25204. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25205. }
  25206. };
  25207. /**
  25208. * Creates a default camera for the scene.
  25209. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25210. * @param replace Whether to replace the existing active camera in the scene.
  25211. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25212. */
  25213. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25214. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25215. if (replace === void 0) { replace = false; }
  25216. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25217. // Dispose existing camera in replace mode.
  25218. if (replace) {
  25219. if (this.activeCamera) {
  25220. this.activeCamera.dispose();
  25221. this.activeCamera = null;
  25222. }
  25223. }
  25224. // Camera
  25225. if (!this.activeCamera) {
  25226. var worldExtends = this.getWorldExtends();
  25227. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25228. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25229. var camera;
  25230. var radius = worldSize.length() * 1.5;
  25231. // empty scene scenario!
  25232. if (!isFinite(radius)) {
  25233. radius = 1;
  25234. worldCenter.copyFromFloats(0, 0, 0);
  25235. }
  25236. if (createArcRotateCamera) {
  25237. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25238. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25239. arcRotateCamera.wheelPrecision = 100 / radius;
  25240. camera = arcRotateCamera;
  25241. }
  25242. else {
  25243. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25244. freeCamera.setTarget(worldCenter);
  25245. camera = freeCamera;
  25246. }
  25247. camera.minZ = radius * 0.01;
  25248. camera.maxZ = radius * 1000;
  25249. camera.speed = radius * 0.2;
  25250. this.activeCamera = camera;
  25251. var canvas = this.getEngine().getRenderingCanvas();
  25252. if (attachCameraControls && canvas) {
  25253. camera.attachControl(canvas);
  25254. }
  25255. }
  25256. };
  25257. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25258. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25259. if (replace === void 0) { replace = false; }
  25260. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25261. this.createDefaultLight(replace);
  25262. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25263. };
  25264. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25265. if (pbr === void 0) { pbr = false; }
  25266. if (scale === void 0) { scale = 1000; }
  25267. if (blur === void 0) { blur = 0; }
  25268. if (environmentTexture) {
  25269. this.environmentTexture = environmentTexture;
  25270. }
  25271. if (!this.environmentTexture) {
  25272. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25273. return null;
  25274. }
  25275. // Skybox
  25276. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25277. if (pbr) {
  25278. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25279. hdrSkyboxMaterial.backFaceCulling = false;
  25280. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25281. if (hdrSkyboxMaterial.reflectionTexture) {
  25282. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25283. }
  25284. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25285. hdrSkyboxMaterial.disableLighting = true;
  25286. hdrSkyboxMaterial.twoSidedLighting = true;
  25287. hdrSkybox.infiniteDistance = true;
  25288. hdrSkybox.material = hdrSkyboxMaterial;
  25289. }
  25290. else {
  25291. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25292. skyboxMaterial.backFaceCulling = false;
  25293. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25294. if (skyboxMaterial.reflectionTexture) {
  25295. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25296. }
  25297. skyboxMaterial.disableLighting = true;
  25298. hdrSkybox.infiniteDistance = true;
  25299. hdrSkybox.material = skyboxMaterial;
  25300. }
  25301. return hdrSkybox;
  25302. };
  25303. Scene.prototype.createDefaultEnvironment = function (options) {
  25304. if (BABYLON.EnvironmentHelper) {
  25305. return new BABYLON.EnvironmentHelper(options, this);
  25306. }
  25307. return null;
  25308. };
  25309. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25310. if (webVROptions === void 0) { webVROptions = {}; }
  25311. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25312. };
  25313. // Tags
  25314. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25315. if (tagsQuery === undefined) {
  25316. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25317. return list;
  25318. }
  25319. var listByTags = [];
  25320. forEach = forEach || (function (item) { return; });
  25321. for (var i in list) {
  25322. var item = list[i];
  25323. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25324. listByTags.push(item);
  25325. forEach(item);
  25326. }
  25327. }
  25328. return listByTags;
  25329. };
  25330. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25331. return this._getByTags(this.meshes, tagsQuery, forEach);
  25332. };
  25333. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25334. return this._getByTags(this.cameras, tagsQuery, forEach);
  25335. };
  25336. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25337. return this._getByTags(this.lights, tagsQuery, forEach);
  25338. };
  25339. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25340. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25341. };
  25342. /**
  25343. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25344. * This allowed control for front to back rendering or reversly depending of the special needs.
  25345. *
  25346. * @param renderingGroupId The rendering group id corresponding to its index
  25347. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25348. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25349. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25350. */
  25351. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25352. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25353. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25354. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25355. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25356. };
  25357. /**
  25358. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25359. *
  25360. * @param renderingGroupId The rendering group id corresponding to its index
  25361. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25362. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25363. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25364. */
  25365. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25366. if (depth === void 0) { depth = true; }
  25367. if (stencil === void 0) { stencil = true; }
  25368. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25369. };
  25370. /**
  25371. * Will flag all materials as dirty to trigger new shader compilation
  25372. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25373. */
  25374. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25375. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25376. var material = _a[_i];
  25377. if (predicate && !predicate(material)) {
  25378. continue;
  25379. }
  25380. material.markAsDirty(flag);
  25381. }
  25382. };
  25383. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25384. var _this = this;
  25385. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25386. this._activeRequests.push(request);
  25387. request.onCompleteObservable.add(function (request) {
  25388. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25389. });
  25390. return request;
  25391. };
  25392. /** @ignore */
  25393. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25394. var _this = this;
  25395. return new Promise(function (resolve, reject) {
  25396. _this._loadFile(url, function (data) {
  25397. resolve(data);
  25398. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25399. reject(exception);
  25400. });
  25401. });
  25402. };
  25403. // Statics
  25404. Scene._FOGMODE_NONE = 0;
  25405. Scene._FOGMODE_EXP = 1;
  25406. Scene._FOGMODE_EXP2 = 2;
  25407. Scene._FOGMODE_LINEAR = 3;
  25408. Scene._uniqueIdCounter = 0;
  25409. Scene.MinDeltaTime = 1.0;
  25410. Scene.MaxDeltaTime = 1000.0;
  25411. /** The distance in pixel that you have to move to prevent some events */
  25412. Scene.DragMovementThreshold = 10; // in pixels
  25413. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25414. Scene.LongPressDelay = 500; // in milliseconds
  25415. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25416. Scene.DoubleClickDelay = 300; // in milliseconds
  25417. /** If you need to check double click without raising a single click at first click, enable this flag */
  25418. Scene.ExclusiveDoubleClickMode = false;
  25419. return Scene;
  25420. }());
  25421. BABYLON.Scene = Scene;
  25422. })(BABYLON || (BABYLON = {}));
  25423. //# sourceMappingURL=babylon.scene.js.map
  25424. var BABYLON;
  25425. (function (BABYLON) {
  25426. /**
  25427. * Set of assets to keep when moving a scene into an asset container.
  25428. */
  25429. var KeepAssets = /** @class */ (function () {
  25430. function KeepAssets() {
  25431. /**
  25432. * Cameras to keep.
  25433. */
  25434. this.cameras = new Array();
  25435. /**
  25436. * Lights to keep.
  25437. */
  25438. this.lights = new Array();
  25439. /**
  25440. * Meshes to keep.
  25441. */
  25442. this.meshes = new Array();
  25443. /**
  25444. * Skeletons to keep.
  25445. */
  25446. this.skeletons = new Array();
  25447. /**
  25448. * ParticleSystems to keep.
  25449. */
  25450. this.particleSystems = new Array();
  25451. /**
  25452. * Animations to keep.
  25453. */
  25454. this.animations = new Array();
  25455. /**
  25456. * MultiMaterials to keep.
  25457. */
  25458. this.multiMaterials = new Array();
  25459. /**
  25460. * Materials to keep.
  25461. */
  25462. this.materials = new Array();
  25463. /**
  25464. * MorphTargetManagers to keep.
  25465. */
  25466. this.morphTargetManagers = new Array();
  25467. /**
  25468. * Geometries to keep.
  25469. */
  25470. this.geometries = new Array();
  25471. /**
  25472. * TransformNodes to keep.
  25473. */
  25474. this.transformNodes = new Array();
  25475. /**
  25476. * LensFlareSystems to keep.
  25477. */
  25478. this.lensFlareSystems = new Array();
  25479. /**
  25480. * ShadowGenerators to keep.
  25481. */
  25482. this.shadowGenerators = new Array();
  25483. /**
  25484. * ActionManagers to keep.
  25485. */
  25486. this.actionManagers = new Array();
  25487. /**
  25488. * Sounds to keep.
  25489. */
  25490. this.sounds = new Array();
  25491. }
  25492. return KeepAssets;
  25493. }());
  25494. BABYLON.KeepAssets = KeepAssets;
  25495. /**
  25496. * Container with a set of assets that can be added or removed from a scene.
  25497. */
  25498. var AssetContainer = /** @class */ (function () {
  25499. /**
  25500. * Instantiates an AssetContainer.
  25501. * @param scene The scene the AssetContainer belongs to.
  25502. */
  25503. function AssetContainer(scene) {
  25504. // Objects
  25505. /**
  25506. * Cameras populated in the container.
  25507. */
  25508. this.cameras = new Array();
  25509. /**
  25510. * Lights populated in the container.
  25511. */
  25512. this.lights = new Array();
  25513. /**
  25514. * Meshes populated in the container.
  25515. */
  25516. this.meshes = new Array();
  25517. /**
  25518. * Skeletons populated in the container.
  25519. */
  25520. this.skeletons = new Array();
  25521. /**
  25522. * ParticleSystems populated in the container.
  25523. */
  25524. this.particleSystems = new Array();
  25525. /**
  25526. * Animations populated in the container.
  25527. */
  25528. this.animations = new Array();
  25529. /**
  25530. * MultiMaterials populated in the container.
  25531. */
  25532. this.multiMaterials = new Array();
  25533. /**
  25534. * Materials populated in the container.
  25535. */
  25536. this.materials = new Array();
  25537. /**
  25538. * MorphTargetManagers populated in the container.
  25539. */
  25540. this.morphTargetManagers = new Array();
  25541. /**
  25542. * Geometries populated in the container.
  25543. */
  25544. this.geometries = new Array();
  25545. /**
  25546. * TransformNodes populated in the container.
  25547. */
  25548. this.transformNodes = new Array();
  25549. /**
  25550. * LensFlareSystems populated in the container.
  25551. */
  25552. this.lensFlareSystems = new Array();
  25553. /**
  25554. * ShadowGenerators populated in the container.
  25555. */
  25556. this.shadowGenerators = new Array();
  25557. /**
  25558. * ActionManagers populated in the container.
  25559. */
  25560. this.actionManagers = new Array();
  25561. /**
  25562. * Sounds populated in the container.
  25563. */
  25564. this.sounds = new Array();
  25565. this.scene = scene;
  25566. }
  25567. /**
  25568. * Adds all the assets from the container to the scene.
  25569. */
  25570. AssetContainer.prototype.addAllToScene = function () {
  25571. var _this = this;
  25572. this.cameras.forEach(function (o) {
  25573. _this.scene.addCamera(o);
  25574. });
  25575. this.lights.forEach(function (o) {
  25576. _this.scene.addLight(o);
  25577. });
  25578. this.meshes.forEach(function (o) {
  25579. _this.scene.addMesh(o);
  25580. });
  25581. this.skeletons.forEach(function (o) {
  25582. _this.scene.addSkeleton(o);
  25583. });
  25584. this.particleSystems.forEach(function (o) {
  25585. _this.scene.addParticleSystem(o);
  25586. });
  25587. this.animations.forEach(function (o) {
  25588. _this.scene.addAnimation(o);
  25589. });
  25590. this.multiMaterials.forEach(function (o) {
  25591. _this.scene.addMultiMaterial(o);
  25592. });
  25593. this.materials.forEach(function (o) {
  25594. _this.scene.addMaterial(o);
  25595. });
  25596. this.morphTargetManagers.forEach(function (o) {
  25597. _this.scene.addMorphTargetManager(o);
  25598. });
  25599. this.geometries.forEach(function (o) {
  25600. _this.scene.addGeometry(o);
  25601. });
  25602. this.transformNodes.forEach(function (o) {
  25603. _this.scene.addTransformNode(o);
  25604. });
  25605. this.lensFlareSystems.forEach(function (o) {
  25606. _this.scene.addLensFlareSystem(o);
  25607. });
  25608. this.actionManagers.forEach(function (o) {
  25609. _this.scene.addActionManager(o);
  25610. });
  25611. this.sounds.forEach(function (o) {
  25612. o.play();
  25613. o.autoplay = true;
  25614. _this.scene.mainSoundTrack.AddSound(o);
  25615. });
  25616. };
  25617. /**
  25618. * Removes all the assets in the container from the scene
  25619. */
  25620. AssetContainer.prototype.removeAllFromScene = function () {
  25621. var _this = this;
  25622. this.cameras.forEach(function (o) {
  25623. _this.scene.removeCamera(o);
  25624. });
  25625. this.lights.forEach(function (o) {
  25626. _this.scene.removeLight(o);
  25627. });
  25628. this.meshes.forEach(function (o) {
  25629. _this.scene.removeMesh(o);
  25630. });
  25631. this.skeletons.forEach(function (o) {
  25632. _this.scene.removeSkeleton(o);
  25633. });
  25634. this.particleSystems.forEach(function (o) {
  25635. _this.scene.removeParticleSystem(o);
  25636. });
  25637. this.animations.forEach(function (o) {
  25638. _this.scene.removeAnimation(o);
  25639. });
  25640. this.multiMaterials.forEach(function (o) {
  25641. _this.scene.removeMultiMaterial(o);
  25642. });
  25643. this.materials.forEach(function (o) {
  25644. _this.scene.removeMaterial(o);
  25645. });
  25646. this.morphTargetManagers.forEach(function (o) {
  25647. _this.scene.removeMorphTargetManager(o);
  25648. });
  25649. this.geometries.forEach(function (o) {
  25650. _this.scene.removeGeometry(o);
  25651. });
  25652. this.transformNodes.forEach(function (o) {
  25653. _this.scene.removeTransformNode(o);
  25654. });
  25655. this.lensFlareSystems.forEach(function (o) {
  25656. _this.scene.removeLensFlareSystem(o);
  25657. });
  25658. this.actionManagers.forEach(function (o) {
  25659. _this.scene.removeActionManager(o);
  25660. });
  25661. this.sounds.forEach(function (o) {
  25662. o.stop();
  25663. o.autoplay = false;
  25664. _this.scene.mainSoundTrack.RemoveSound(o);
  25665. });
  25666. };
  25667. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25668. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25669. var asset = sourceAssets_1[_i];
  25670. var move = true;
  25671. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25672. var keepAsset = keepAssets_1[_a];
  25673. if (asset === keepAsset) {
  25674. move = false;
  25675. break;
  25676. }
  25677. }
  25678. if (move) {
  25679. targetAssets.push(asset);
  25680. }
  25681. }
  25682. };
  25683. /**
  25684. * Removes all the assets contained in the scene and adds them to the container.
  25685. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25686. */
  25687. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25688. if (keepAssets === undefined) {
  25689. keepAssets = new KeepAssets();
  25690. }
  25691. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25692. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25693. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25694. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25695. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25696. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25697. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25698. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25699. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25700. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25701. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25702. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25703. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25704. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25705. this.removeAllFromScene();
  25706. };
  25707. return AssetContainer;
  25708. }());
  25709. BABYLON.AssetContainer = AssetContainer;
  25710. })(BABYLON || (BABYLON = {}));
  25711. //# sourceMappingURL=babylon.assetContainer.js.map
  25712. var BABYLON;
  25713. (function (BABYLON) {
  25714. var Buffer = /** @class */ (function () {
  25715. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25716. if (instanced === void 0) { instanced = false; }
  25717. if (engine instanceof BABYLON.Mesh) {
  25718. this._engine = engine.getScene().getEngine();
  25719. }
  25720. else {
  25721. this._engine = engine;
  25722. }
  25723. this._updatable = updatable;
  25724. this._instanced = instanced;
  25725. this._data = data;
  25726. this._strideSize = stride;
  25727. if (!postponeInternalCreation) {
  25728. this.create();
  25729. }
  25730. }
  25731. /**
  25732. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25733. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25734. * @param offset defines offset in the buffer (0 by default)
  25735. * @param size defines the size in floats of attributes (position is 3 for instance)
  25736. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25737. * @param instanced defines if the vertex buffer contains indexed data
  25738. * @returns the new vertex buffer
  25739. */
  25740. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25741. // a lot of these parameters are ignored as they are overriden by the buffer
  25742. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25743. };
  25744. // Properties
  25745. Buffer.prototype.isUpdatable = function () {
  25746. return this._updatable;
  25747. };
  25748. Buffer.prototype.getData = function () {
  25749. return this._data;
  25750. };
  25751. Buffer.prototype.getBuffer = function () {
  25752. return this._buffer;
  25753. };
  25754. Buffer.prototype.getStrideSize = function () {
  25755. return this._strideSize;
  25756. };
  25757. // public getIsInstanced(): boolean {
  25758. // return this._instanced;
  25759. // }
  25760. // public get instanceDivisor(): number {
  25761. // return this._instanceDivisor;
  25762. // }
  25763. // public set instanceDivisor(value: number) {
  25764. // this._instanceDivisor = value;
  25765. // if (value == 0) {
  25766. // this._instanced = false;
  25767. // } else {
  25768. // this._instanced = true;
  25769. // }
  25770. // }
  25771. // Methods
  25772. Buffer.prototype.create = function (data) {
  25773. if (data === void 0) { data = null; }
  25774. if (!data && this._buffer) {
  25775. return; // nothing to do
  25776. }
  25777. data = data || this._data;
  25778. if (!data) {
  25779. return;
  25780. }
  25781. if (!this._buffer) {
  25782. if (this._updatable) {
  25783. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25784. this._data = data;
  25785. }
  25786. else {
  25787. this._buffer = this._engine.createVertexBuffer(data);
  25788. }
  25789. }
  25790. else if (this._updatable) {
  25791. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25792. this._data = data;
  25793. }
  25794. };
  25795. Buffer.prototype._rebuild = function () {
  25796. this._buffer = null;
  25797. this.create(this._data);
  25798. };
  25799. Buffer.prototype.update = function (data) {
  25800. this.create(data);
  25801. };
  25802. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25803. if (!this._buffer) {
  25804. return;
  25805. }
  25806. if (this._updatable) {
  25807. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25808. this._data = null;
  25809. }
  25810. };
  25811. Buffer.prototype.dispose = function () {
  25812. if (!this._buffer) {
  25813. return;
  25814. }
  25815. if (this._engine._releaseBuffer(this._buffer)) {
  25816. this._buffer = null;
  25817. }
  25818. };
  25819. return Buffer;
  25820. }());
  25821. BABYLON.Buffer = Buffer;
  25822. })(BABYLON || (BABYLON = {}));
  25823. //# sourceMappingURL=babylon.buffer.js.map
  25824. var BABYLON;
  25825. (function (BABYLON) {
  25826. var VertexBuffer = /** @class */ (function () {
  25827. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25828. if (data instanceof BABYLON.Buffer) {
  25829. if (!stride) {
  25830. stride = data.getStrideSize();
  25831. }
  25832. this._buffer = data;
  25833. this._ownsBuffer = false;
  25834. }
  25835. else {
  25836. if (!stride) {
  25837. stride = VertexBuffer.DeduceStride(kind);
  25838. }
  25839. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25840. this._ownsBuffer = true;
  25841. }
  25842. this._stride = stride;
  25843. this._instanced = instanced !== undefined ? instanced : false;
  25844. this._instanceDivisor = instanced ? 1 : 0;
  25845. this._offset = offset ? offset : 0;
  25846. this._size = size ? size : stride;
  25847. this._kind = kind;
  25848. }
  25849. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25850. /**
  25851. * Gets or sets the instance divisor when in instanced mode
  25852. */
  25853. get: function () {
  25854. return this._instanceDivisor;
  25855. },
  25856. set: function (value) {
  25857. this._instanceDivisor = value;
  25858. if (value == 0) {
  25859. this._instanced = false;
  25860. }
  25861. else {
  25862. this._instanced = true;
  25863. }
  25864. },
  25865. enumerable: true,
  25866. configurable: true
  25867. });
  25868. VertexBuffer.prototype._rebuild = function () {
  25869. if (!this._buffer) {
  25870. return;
  25871. }
  25872. this._buffer._rebuild();
  25873. };
  25874. /**
  25875. * Returns the kind of the VertexBuffer (string).
  25876. */
  25877. VertexBuffer.prototype.getKind = function () {
  25878. return this._kind;
  25879. };
  25880. // Properties
  25881. /**
  25882. * Boolean : is the VertexBuffer updatable ?
  25883. */
  25884. VertexBuffer.prototype.isUpdatable = function () {
  25885. return this._buffer.isUpdatable();
  25886. };
  25887. /**
  25888. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25889. */
  25890. VertexBuffer.prototype.getData = function () {
  25891. return this._buffer.getData();
  25892. };
  25893. /**
  25894. * Returns the WebGLBuffer associated to the VertexBuffer.
  25895. */
  25896. VertexBuffer.prototype.getBuffer = function () {
  25897. return this._buffer.getBuffer();
  25898. };
  25899. /**
  25900. * Returns the stride of the VertexBuffer (integer).
  25901. */
  25902. VertexBuffer.prototype.getStrideSize = function () {
  25903. return this._stride;
  25904. };
  25905. /**
  25906. * Returns the offset (integer).
  25907. */
  25908. VertexBuffer.prototype.getOffset = function () {
  25909. return this._offset;
  25910. };
  25911. /**
  25912. * Returns the VertexBuffer total size (integer).
  25913. */
  25914. VertexBuffer.prototype.getSize = function () {
  25915. return this._size;
  25916. };
  25917. /**
  25918. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25919. */
  25920. VertexBuffer.prototype.getIsInstanced = function () {
  25921. return this._instanced;
  25922. };
  25923. /**
  25924. * Returns the instancing divisor, zero for non-instanced (integer).
  25925. */
  25926. VertexBuffer.prototype.getInstanceDivisor = function () {
  25927. return this._instanceDivisor;
  25928. };
  25929. // Methods
  25930. /**
  25931. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25932. * Returns the created WebGLBuffer.
  25933. */
  25934. VertexBuffer.prototype.create = function (data) {
  25935. return this._buffer.create(data);
  25936. };
  25937. /**
  25938. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25939. * This function will create a new buffer if the current one is not updatable
  25940. * Returns the updated WebGLBuffer.
  25941. */
  25942. VertexBuffer.prototype.update = function (data) {
  25943. return this._buffer.update(data);
  25944. };
  25945. /**
  25946. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25947. * Returns the directly updated WebGLBuffer.
  25948. */
  25949. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25950. return this._buffer.updateDirectly(data, offset);
  25951. };
  25952. /**
  25953. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25954. */
  25955. VertexBuffer.prototype.dispose = function () {
  25956. if (this._ownsBuffer) {
  25957. this._buffer.dispose();
  25958. }
  25959. };
  25960. Object.defineProperty(VertexBuffer, "PositionKind", {
  25961. get: function () {
  25962. return VertexBuffer._PositionKind;
  25963. },
  25964. enumerable: true,
  25965. configurable: true
  25966. });
  25967. Object.defineProperty(VertexBuffer, "NormalKind", {
  25968. get: function () {
  25969. return VertexBuffer._NormalKind;
  25970. },
  25971. enumerable: true,
  25972. configurable: true
  25973. });
  25974. Object.defineProperty(VertexBuffer, "TangentKind", {
  25975. get: function () {
  25976. return VertexBuffer._TangentKind;
  25977. },
  25978. enumerable: true,
  25979. configurable: true
  25980. });
  25981. Object.defineProperty(VertexBuffer, "UVKind", {
  25982. get: function () {
  25983. return VertexBuffer._UVKind;
  25984. },
  25985. enumerable: true,
  25986. configurable: true
  25987. });
  25988. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25989. get: function () {
  25990. return VertexBuffer._UV2Kind;
  25991. },
  25992. enumerable: true,
  25993. configurable: true
  25994. });
  25995. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25996. get: function () {
  25997. return VertexBuffer._UV3Kind;
  25998. },
  25999. enumerable: true,
  26000. configurable: true
  26001. });
  26002. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26003. get: function () {
  26004. return VertexBuffer._UV4Kind;
  26005. },
  26006. enumerable: true,
  26007. configurable: true
  26008. });
  26009. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26010. get: function () {
  26011. return VertexBuffer._UV5Kind;
  26012. },
  26013. enumerable: true,
  26014. configurable: true
  26015. });
  26016. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26017. get: function () {
  26018. return VertexBuffer._UV6Kind;
  26019. },
  26020. enumerable: true,
  26021. configurable: true
  26022. });
  26023. Object.defineProperty(VertexBuffer, "ColorKind", {
  26024. get: function () {
  26025. return VertexBuffer._ColorKind;
  26026. },
  26027. enumerable: true,
  26028. configurable: true
  26029. });
  26030. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26031. get: function () {
  26032. return VertexBuffer._MatricesIndicesKind;
  26033. },
  26034. enumerable: true,
  26035. configurable: true
  26036. });
  26037. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26038. get: function () {
  26039. return VertexBuffer._MatricesWeightsKind;
  26040. },
  26041. enumerable: true,
  26042. configurable: true
  26043. });
  26044. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26045. get: function () {
  26046. return VertexBuffer._MatricesIndicesExtraKind;
  26047. },
  26048. enumerable: true,
  26049. configurable: true
  26050. });
  26051. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26052. get: function () {
  26053. return VertexBuffer._MatricesWeightsExtraKind;
  26054. },
  26055. enumerable: true,
  26056. configurable: true
  26057. });
  26058. /**
  26059. * Deduces the stride given a kind.
  26060. * @param kind The kind string to deduce
  26061. * @returns The deduced stride
  26062. */
  26063. VertexBuffer.DeduceStride = function (kind) {
  26064. switch (kind) {
  26065. case VertexBuffer.UVKind:
  26066. case VertexBuffer.UV2Kind:
  26067. case VertexBuffer.UV3Kind:
  26068. case VertexBuffer.UV4Kind:
  26069. case VertexBuffer.UV5Kind:
  26070. case VertexBuffer.UV6Kind:
  26071. return 2;
  26072. case VertexBuffer.NormalKind:
  26073. case VertexBuffer.PositionKind:
  26074. return 3;
  26075. case VertexBuffer.ColorKind:
  26076. case VertexBuffer.MatricesIndicesKind:
  26077. case VertexBuffer.MatricesIndicesExtraKind:
  26078. case VertexBuffer.MatricesWeightsKind:
  26079. case VertexBuffer.MatricesWeightsExtraKind:
  26080. case VertexBuffer.TangentKind:
  26081. return 4;
  26082. default:
  26083. throw new Error("Invalid kind '" + kind + "'");
  26084. }
  26085. };
  26086. // Enums
  26087. VertexBuffer._PositionKind = "position";
  26088. VertexBuffer._NormalKind = "normal";
  26089. VertexBuffer._TangentKind = "tangent";
  26090. VertexBuffer._UVKind = "uv";
  26091. VertexBuffer._UV2Kind = "uv2";
  26092. VertexBuffer._UV3Kind = "uv3";
  26093. VertexBuffer._UV4Kind = "uv4";
  26094. VertexBuffer._UV5Kind = "uv5";
  26095. VertexBuffer._UV6Kind = "uv6";
  26096. VertexBuffer._ColorKind = "color";
  26097. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26098. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26099. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26100. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26101. return VertexBuffer;
  26102. }());
  26103. BABYLON.VertexBuffer = VertexBuffer;
  26104. })(BABYLON || (BABYLON = {}));
  26105. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26106. var BABYLON;
  26107. (function (BABYLON) {
  26108. /**
  26109. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26110. */
  26111. var DummyInternalTextureTracker = /** @class */ (function () {
  26112. function DummyInternalTextureTracker() {
  26113. /**
  26114. * Gets or set the previous tracker in the list
  26115. */
  26116. this.previous = null;
  26117. /**
  26118. * Gets or set the next tracker in the list
  26119. */
  26120. this.next = null;
  26121. }
  26122. return DummyInternalTextureTracker;
  26123. }());
  26124. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26125. })(BABYLON || (BABYLON = {}));
  26126. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26127. var BABYLON;
  26128. (function (BABYLON) {
  26129. /**
  26130. * Class used to store data associated with WebGL texture data for the engine
  26131. * This class should not be used directly
  26132. */
  26133. var InternalTexture = /** @class */ (function () {
  26134. /**
  26135. * Creates a new InternalTexture
  26136. * @param engine defines the engine to use
  26137. * @param dataSource defines the type of data that will be used
  26138. */
  26139. function InternalTexture(engine, dataSource) {
  26140. /**
  26141. * Observable called when the texture is loaded
  26142. */
  26143. this.onLoadedObservable = new BABYLON.Observable();
  26144. /**
  26145. * Gets or set the previous tracker in the list
  26146. */
  26147. this.previous = null;
  26148. /**
  26149. * Gets or set the next tracker in the list
  26150. */
  26151. this.next = null;
  26152. // Private
  26153. /** @ignore */
  26154. this._initialSlot = -1;
  26155. /** @ignore */
  26156. this._designatedSlot = -1;
  26157. /** @ignore */
  26158. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26159. /** @ignore */
  26160. this._comparisonFunction = 0;
  26161. /** @ignore */
  26162. this._references = 1;
  26163. this._engine = engine;
  26164. this._dataSource = dataSource;
  26165. this._webGLTexture = engine._createTexture();
  26166. }
  26167. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26168. /**
  26169. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26170. */
  26171. get: function () {
  26172. return this._dataSource;
  26173. },
  26174. enumerable: true,
  26175. configurable: true
  26176. });
  26177. /**
  26178. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26179. */
  26180. InternalTexture.prototype.incrementReferences = function () {
  26181. this._references++;
  26182. };
  26183. /**
  26184. * Change the size of the texture (not the size of the content)
  26185. * @param width defines the new width
  26186. * @param height defines the new height
  26187. * @param depth defines the new depth (1 by default)
  26188. */
  26189. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26190. if (depth === void 0) { depth = 1; }
  26191. this.width = width;
  26192. this.height = height;
  26193. this.depth = depth;
  26194. this.baseWidth = width;
  26195. this.baseHeight = height;
  26196. this.baseDepth = depth;
  26197. this._size = width * height * depth;
  26198. };
  26199. /** @ignore */
  26200. InternalTexture.prototype._rebuild = function () {
  26201. var _this = this;
  26202. var proxy;
  26203. this.isReady = false;
  26204. this._cachedCoordinatesMode = null;
  26205. this._cachedWrapU = null;
  26206. this._cachedWrapV = null;
  26207. this._cachedAnisotropicFilteringLevel = null;
  26208. switch (this._dataSource) {
  26209. case InternalTexture.DATASOURCE_TEMP:
  26210. return;
  26211. case InternalTexture.DATASOURCE_URL:
  26212. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26213. _this.isReady = true;
  26214. }, null, this._buffer, undefined, this.format);
  26215. proxy._swapAndDie(this);
  26216. return;
  26217. case InternalTexture.DATASOURCE_RAW:
  26218. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26219. proxy._swapAndDie(this);
  26220. this.isReady = true;
  26221. return;
  26222. case InternalTexture.DATASOURCE_RAW3D:
  26223. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26224. proxy._swapAndDie(this);
  26225. this.isReady = true;
  26226. return;
  26227. case InternalTexture.DATASOURCE_DYNAMIC:
  26228. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26229. proxy._swapAndDie(this);
  26230. // The engine will make sure to update content so no need to flag it as isReady = true
  26231. return;
  26232. case InternalTexture.DATASOURCE_RENDERTARGET:
  26233. var options = new BABYLON.RenderTargetCreationOptions();
  26234. options.generateDepthBuffer = this._generateDepthBuffer;
  26235. options.generateMipMaps = this.generateMipMaps;
  26236. options.generateStencilBuffer = this._generateStencilBuffer;
  26237. options.samplingMode = this.samplingMode;
  26238. options.type = this.type;
  26239. if (this.isCube) {
  26240. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26241. }
  26242. else {
  26243. var size = {
  26244. width: this.width,
  26245. height: this.height
  26246. };
  26247. proxy = this._engine.createRenderTargetTexture(size, options);
  26248. }
  26249. proxy._swapAndDie(this);
  26250. this.isReady = true;
  26251. return;
  26252. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26253. var depthTextureOptions = {
  26254. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26255. comparisonFunction: this._comparisonFunction,
  26256. generateStencil: this._generateStencilBuffer,
  26257. };
  26258. if (this.isCube) {
  26259. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26260. }
  26261. else {
  26262. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26263. }
  26264. proxy._swapAndDie(this);
  26265. this.isReady = true;
  26266. return;
  26267. case InternalTexture.DATASOURCE_CUBE:
  26268. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26269. _this.isReady = true;
  26270. }, null, this.format, this._extension);
  26271. proxy._swapAndDie(this);
  26272. return;
  26273. case InternalTexture.DATASOURCE_CUBERAW:
  26274. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26275. proxy._swapAndDie(this);
  26276. this.isReady = true;
  26277. return;
  26278. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26279. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26280. if (proxy) {
  26281. proxy._swapAndDie(_this);
  26282. }
  26283. _this.isReady = true;
  26284. }, null, this.format, this._extension);
  26285. return;
  26286. }
  26287. };
  26288. InternalTexture.prototype._swapAndDie = function (target) {
  26289. target._webGLTexture = this._webGLTexture;
  26290. if (this._framebuffer) {
  26291. target._framebuffer = this._framebuffer;
  26292. }
  26293. if (this._depthStencilBuffer) {
  26294. target._depthStencilBuffer = this._depthStencilBuffer;
  26295. }
  26296. if (this._lodTextureHigh) {
  26297. if (target._lodTextureHigh) {
  26298. target._lodTextureHigh.dispose();
  26299. }
  26300. target._lodTextureHigh = this._lodTextureHigh;
  26301. }
  26302. if (this._lodTextureMid) {
  26303. if (target._lodTextureMid) {
  26304. target._lodTextureMid.dispose();
  26305. }
  26306. target._lodTextureMid = this._lodTextureMid;
  26307. }
  26308. if (this._lodTextureLow) {
  26309. if (target._lodTextureLow) {
  26310. target._lodTextureLow.dispose();
  26311. }
  26312. target._lodTextureLow = this._lodTextureLow;
  26313. }
  26314. var cache = this._engine.getLoadedTexturesCache();
  26315. var index = cache.indexOf(this);
  26316. if (index !== -1) {
  26317. cache.splice(index, 1);
  26318. }
  26319. };
  26320. /**
  26321. * Dispose the current allocated resources
  26322. */
  26323. InternalTexture.prototype.dispose = function () {
  26324. if (!this._webGLTexture) {
  26325. return;
  26326. }
  26327. this._references--;
  26328. if (this._references === 0) {
  26329. this._engine._releaseTexture(this);
  26330. this._webGLTexture = null;
  26331. this.previous = null;
  26332. this.next = null;
  26333. }
  26334. };
  26335. /**
  26336. * The source of the texture data is unknown
  26337. */
  26338. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26339. /**
  26340. * Texture data comes from an URL
  26341. */
  26342. InternalTexture.DATASOURCE_URL = 1;
  26343. /**
  26344. * Texture data is only used for temporary storage
  26345. */
  26346. InternalTexture.DATASOURCE_TEMP = 2;
  26347. /**
  26348. * Texture data comes from raw data (ArrayBuffer)
  26349. */
  26350. InternalTexture.DATASOURCE_RAW = 3;
  26351. /**
  26352. * Texture content is dynamic (video or dynamic texture)
  26353. */
  26354. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26355. /**
  26356. * Texture content is generated by rendering to it
  26357. */
  26358. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26359. /**
  26360. * Texture content is part of a multi render target process
  26361. */
  26362. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26363. /**
  26364. * Texture data comes from a cube data file
  26365. */
  26366. InternalTexture.DATASOURCE_CUBE = 7;
  26367. /**
  26368. * Texture data comes from a raw cube data
  26369. */
  26370. InternalTexture.DATASOURCE_CUBERAW = 8;
  26371. /**
  26372. * Texture data come from a prefiltered cube data file
  26373. */
  26374. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26375. /**
  26376. * Texture content is raw 3D data
  26377. */
  26378. InternalTexture.DATASOURCE_RAW3D = 10;
  26379. /**
  26380. * Texture content is a depth texture
  26381. */
  26382. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26383. return InternalTexture;
  26384. }());
  26385. BABYLON.InternalTexture = InternalTexture;
  26386. })(BABYLON || (BABYLON = {}));
  26387. //# sourceMappingURL=babylon.internalTexture.js.map
  26388. var BABYLON;
  26389. (function (BABYLON) {
  26390. var BaseTexture = /** @class */ (function () {
  26391. function BaseTexture(scene) {
  26392. this._hasAlpha = false;
  26393. this.getAlphaFromRGB = false;
  26394. this.level = 1;
  26395. this.coordinatesIndex = 0;
  26396. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26397. /**
  26398. * | Value | Type | Description |
  26399. * | ----- | ------------------ | ----------- |
  26400. * | 0 | CLAMP_ADDRESSMODE | |
  26401. * | 1 | WRAP_ADDRESSMODE | |
  26402. * | 2 | MIRROR_ADDRESSMODE | |
  26403. */
  26404. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26405. /**
  26406. * | Value | Type | Description |
  26407. * | ----- | ------------------ | ----------- |
  26408. * | 0 | CLAMP_ADDRESSMODE | |
  26409. * | 1 | WRAP_ADDRESSMODE | |
  26410. * | 2 | MIRROR_ADDRESSMODE | |
  26411. */
  26412. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26413. /**
  26414. * | Value | Type | Description |
  26415. * | ----- | ------------------ | ----------- |
  26416. * | 0 | CLAMP_ADDRESSMODE | |
  26417. * | 1 | WRAP_ADDRESSMODE | |
  26418. * | 2 | MIRROR_ADDRESSMODE | |
  26419. */
  26420. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26421. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26422. this.isCube = false;
  26423. this.is3D = false;
  26424. this.gammaSpace = true;
  26425. this.invertZ = false;
  26426. this.lodLevelInAlpha = false;
  26427. this.lodGenerationOffset = 0.0;
  26428. this.lodGenerationScale = 0.8;
  26429. this.isRenderTarget = false;
  26430. this.animations = new Array();
  26431. /**
  26432. * An event triggered when the texture is disposed.
  26433. * @type {BABYLON.Observable}
  26434. */
  26435. this.onDisposeObservable = new BABYLON.Observable();
  26436. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26437. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26438. if (this._scene) {
  26439. this._scene.textures.push(this);
  26440. }
  26441. this._uid = null;
  26442. }
  26443. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26444. get: function () {
  26445. return this._hasAlpha;
  26446. },
  26447. set: function (value) {
  26448. if (this._hasAlpha === value) {
  26449. return;
  26450. }
  26451. this._hasAlpha = value;
  26452. if (this._scene) {
  26453. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26454. }
  26455. },
  26456. enumerable: true,
  26457. configurable: true
  26458. });
  26459. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26460. get: function () {
  26461. return this._coordinatesMode;
  26462. },
  26463. /**
  26464. * How a texture is mapped.
  26465. *
  26466. * | Value | Type | Description |
  26467. * | ----- | ----------------------------------- | ----------- |
  26468. * | 0 | EXPLICIT_MODE | |
  26469. * | 1 | SPHERICAL_MODE | |
  26470. * | 2 | PLANAR_MODE | |
  26471. * | 3 | CUBIC_MODE | |
  26472. * | 4 | PROJECTION_MODE | |
  26473. * | 5 | SKYBOX_MODE | |
  26474. * | 6 | INVCUBIC_MODE | |
  26475. * | 7 | EQUIRECTANGULAR_MODE | |
  26476. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26477. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26478. */
  26479. set: function (value) {
  26480. if (this._coordinatesMode === value) {
  26481. return;
  26482. }
  26483. this._coordinatesMode = value;
  26484. if (this._scene) {
  26485. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26486. }
  26487. },
  26488. enumerable: true,
  26489. configurable: true
  26490. });
  26491. Object.defineProperty(BaseTexture.prototype, "uid", {
  26492. get: function () {
  26493. if (!this._uid) {
  26494. this._uid = BABYLON.Tools.RandomId();
  26495. }
  26496. return this._uid;
  26497. },
  26498. enumerable: true,
  26499. configurable: true
  26500. });
  26501. BaseTexture.prototype.toString = function () {
  26502. return this.name;
  26503. };
  26504. BaseTexture.prototype.getClassName = function () {
  26505. return "BaseTexture";
  26506. };
  26507. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26508. set: function (callback) {
  26509. if (this._onDisposeObserver) {
  26510. this.onDisposeObservable.remove(this._onDisposeObserver);
  26511. }
  26512. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26513. },
  26514. enumerable: true,
  26515. configurable: true
  26516. });
  26517. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26518. get: function () {
  26519. return true;
  26520. },
  26521. enumerable: true,
  26522. configurable: true
  26523. });
  26524. BaseTexture.prototype.getScene = function () {
  26525. return this._scene;
  26526. };
  26527. BaseTexture.prototype.getTextureMatrix = function () {
  26528. return BABYLON.Matrix.IdentityReadOnly;
  26529. };
  26530. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26531. return BABYLON.Matrix.IdentityReadOnly;
  26532. };
  26533. BaseTexture.prototype.getInternalTexture = function () {
  26534. return this._texture;
  26535. };
  26536. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26537. return !this.isBlocking || this.isReady();
  26538. };
  26539. BaseTexture.prototype.isReady = function () {
  26540. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26541. this.delayLoad();
  26542. return false;
  26543. }
  26544. if (this._texture) {
  26545. return this._texture.isReady;
  26546. }
  26547. return false;
  26548. };
  26549. BaseTexture.prototype.getSize = function () {
  26550. if (this._texture && this._texture.width) {
  26551. return new BABYLON.Size(this._texture.width, this._texture.height);
  26552. }
  26553. if (this._texture && this._texture._size) {
  26554. return new BABYLON.Size(this._texture._size, this._texture._size);
  26555. }
  26556. return BABYLON.Size.Zero();
  26557. };
  26558. BaseTexture.prototype.getBaseSize = function () {
  26559. if (!this.isReady() || !this._texture)
  26560. return BABYLON.Size.Zero();
  26561. if (this._texture._size) {
  26562. return new BABYLON.Size(this._texture._size, this._texture._size);
  26563. }
  26564. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26565. };
  26566. BaseTexture.prototype.scale = function (ratio) {
  26567. };
  26568. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26569. get: function () {
  26570. return false;
  26571. },
  26572. enumerable: true,
  26573. configurable: true
  26574. });
  26575. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26576. if (!this._scene) {
  26577. return null;
  26578. }
  26579. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26580. for (var index = 0; index < texturesCache.length; index++) {
  26581. var texturesCacheEntry = texturesCache[index];
  26582. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26583. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26584. texturesCacheEntry.incrementReferences();
  26585. return texturesCacheEntry;
  26586. }
  26587. }
  26588. }
  26589. return null;
  26590. };
  26591. BaseTexture.prototype._rebuild = function () {
  26592. };
  26593. BaseTexture.prototype.delayLoad = function () {
  26594. };
  26595. BaseTexture.prototype.clone = function () {
  26596. return null;
  26597. };
  26598. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26599. get: function () {
  26600. if (!this._texture) {
  26601. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26602. }
  26603. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26604. },
  26605. enumerable: true,
  26606. configurable: true
  26607. });
  26608. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26609. get: function () {
  26610. if (!this._texture) {
  26611. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26612. }
  26613. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26614. },
  26615. enumerable: true,
  26616. configurable: true
  26617. });
  26618. BaseTexture.prototype.readPixels = function (faceIndex) {
  26619. if (faceIndex === void 0) { faceIndex = 0; }
  26620. if (!this._texture) {
  26621. return null;
  26622. }
  26623. var size = this.getSize();
  26624. var scene = this.getScene();
  26625. if (!scene) {
  26626. return null;
  26627. }
  26628. var engine = scene.getEngine();
  26629. if (this._texture.isCube) {
  26630. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26631. }
  26632. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26633. };
  26634. BaseTexture.prototype.releaseInternalTexture = function () {
  26635. if (this._texture) {
  26636. this._texture.dispose();
  26637. this._texture = null;
  26638. }
  26639. };
  26640. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26641. get: function () {
  26642. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26643. return null;
  26644. }
  26645. if (!this._texture._sphericalPolynomial) {
  26646. this._texture._sphericalPolynomial =
  26647. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26648. }
  26649. return this._texture._sphericalPolynomial;
  26650. },
  26651. set: function (value) {
  26652. if (this._texture) {
  26653. this._texture._sphericalPolynomial = value;
  26654. }
  26655. },
  26656. enumerable: true,
  26657. configurable: true
  26658. });
  26659. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26660. get: function () {
  26661. if (this._texture) {
  26662. return this._texture._lodTextureHigh;
  26663. }
  26664. return null;
  26665. },
  26666. enumerable: true,
  26667. configurable: true
  26668. });
  26669. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26670. get: function () {
  26671. if (this._texture) {
  26672. return this._texture._lodTextureMid;
  26673. }
  26674. return null;
  26675. },
  26676. enumerable: true,
  26677. configurable: true
  26678. });
  26679. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26680. get: function () {
  26681. if (this._texture) {
  26682. return this._texture._lodTextureLow;
  26683. }
  26684. return null;
  26685. },
  26686. enumerable: true,
  26687. configurable: true
  26688. });
  26689. BaseTexture.prototype.dispose = function () {
  26690. if (!this._scene) {
  26691. return;
  26692. }
  26693. // Animations
  26694. this._scene.stopAnimation(this);
  26695. // Remove from scene
  26696. this._scene._removePendingData(this);
  26697. var index = this._scene.textures.indexOf(this);
  26698. if (index >= 0) {
  26699. this._scene.textures.splice(index, 1);
  26700. }
  26701. if (this._texture === undefined) {
  26702. return;
  26703. }
  26704. // Release
  26705. this.releaseInternalTexture();
  26706. // Callback
  26707. this.onDisposeObservable.notifyObservers(this);
  26708. this.onDisposeObservable.clear();
  26709. };
  26710. BaseTexture.prototype.serialize = function () {
  26711. if (!this.name) {
  26712. return null;
  26713. }
  26714. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26715. // Animations
  26716. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26717. return serializationObject;
  26718. };
  26719. BaseTexture.WhenAllReady = function (textures, callback) {
  26720. var numRemaining = textures.length;
  26721. if (numRemaining === 0) {
  26722. callback();
  26723. return;
  26724. }
  26725. var _loop_1 = function () {
  26726. texture = textures[i];
  26727. if (texture.isReady()) {
  26728. if (--numRemaining === 0) {
  26729. callback();
  26730. }
  26731. }
  26732. else {
  26733. onLoadObservable = texture.onLoadObservable;
  26734. var onLoadCallback_1 = function () {
  26735. onLoadObservable.removeCallback(onLoadCallback_1);
  26736. if (--numRemaining === 0) {
  26737. callback();
  26738. }
  26739. };
  26740. onLoadObservable.add(onLoadCallback_1);
  26741. }
  26742. };
  26743. var texture, onLoadObservable;
  26744. for (var i = 0; i < textures.length; i++) {
  26745. _loop_1();
  26746. }
  26747. };
  26748. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26749. __decorate([
  26750. BABYLON.serialize()
  26751. ], BaseTexture.prototype, "name", void 0);
  26752. __decorate([
  26753. BABYLON.serialize("hasAlpha")
  26754. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26755. __decorate([
  26756. BABYLON.serialize()
  26757. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26758. __decorate([
  26759. BABYLON.serialize()
  26760. ], BaseTexture.prototype, "level", void 0);
  26761. __decorate([
  26762. BABYLON.serialize()
  26763. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26764. __decorate([
  26765. BABYLON.serialize("coordinatesMode")
  26766. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26767. __decorate([
  26768. BABYLON.serialize()
  26769. ], BaseTexture.prototype, "wrapU", void 0);
  26770. __decorate([
  26771. BABYLON.serialize()
  26772. ], BaseTexture.prototype, "wrapV", void 0);
  26773. __decorate([
  26774. BABYLON.serialize()
  26775. ], BaseTexture.prototype, "wrapR", void 0);
  26776. __decorate([
  26777. BABYLON.serialize()
  26778. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26779. __decorate([
  26780. BABYLON.serialize()
  26781. ], BaseTexture.prototype, "isCube", void 0);
  26782. __decorate([
  26783. BABYLON.serialize()
  26784. ], BaseTexture.prototype, "is3D", void 0);
  26785. __decorate([
  26786. BABYLON.serialize()
  26787. ], BaseTexture.prototype, "gammaSpace", void 0);
  26788. __decorate([
  26789. BABYLON.serialize()
  26790. ], BaseTexture.prototype, "invertZ", void 0);
  26791. __decorate([
  26792. BABYLON.serialize()
  26793. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26794. __decorate([
  26795. BABYLON.serialize()
  26796. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26797. __decorate([
  26798. BABYLON.serialize()
  26799. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26800. __decorate([
  26801. BABYLON.serialize()
  26802. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26803. return BaseTexture;
  26804. }());
  26805. BABYLON.BaseTexture = BaseTexture;
  26806. })(BABYLON || (BABYLON = {}));
  26807. //# sourceMappingURL=babylon.baseTexture.js.map
  26808. var BABYLON;
  26809. (function (BABYLON) {
  26810. var Texture = /** @class */ (function (_super) {
  26811. __extends(Texture, _super);
  26812. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26813. if (noMipmap === void 0) { noMipmap = false; }
  26814. if (invertY === void 0) { invertY = true; }
  26815. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26816. if (onLoad === void 0) { onLoad = null; }
  26817. if (onError === void 0) { onError = null; }
  26818. if (buffer === void 0) { buffer = null; }
  26819. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26820. var _this = _super.call(this, scene) || this;
  26821. _this.uOffset = 0;
  26822. _this.vOffset = 0;
  26823. _this.uScale = 1.0;
  26824. _this.vScale = 1.0;
  26825. _this.uAng = 0;
  26826. _this.vAng = 0;
  26827. _this.wAng = 0;
  26828. _this._isBlocking = true;
  26829. _this.name = url || "";
  26830. _this.url = url;
  26831. _this._noMipmap = noMipmap;
  26832. _this._invertY = invertY;
  26833. _this._samplingMode = samplingMode;
  26834. _this._buffer = buffer;
  26835. _this._deleteBuffer = deleteBuffer;
  26836. if (format) {
  26837. _this._format = format;
  26838. }
  26839. scene = _this.getScene();
  26840. if (!scene) {
  26841. return _this;
  26842. }
  26843. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26844. var load = function () {
  26845. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26846. _this.onLoadObservable.notifyObservers(_this);
  26847. }
  26848. if (onLoad) {
  26849. onLoad();
  26850. }
  26851. if (!_this.isBlocking && scene) {
  26852. scene.resetCachedMaterial();
  26853. }
  26854. };
  26855. if (!_this.url) {
  26856. _this._delayedOnLoad = load;
  26857. _this._delayedOnError = onError;
  26858. return _this;
  26859. }
  26860. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26861. if (!_this._texture) {
  26862. if (!scene.useDelayedTextureLoading) {
  26863. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26864. if (deleteBuffer) {
  26865. delete _this._buffer;
  26866. }
  26867. }
  26868. else {
  26869. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26870. _this._delayedOnLoad = load;
  26871. _this._delayedOnError = onError;
  26872. }
  26873. }
  26874. else {
  26875. if (_this._texture.isReady) {
  26876. BABYLON.Tools.SetImmediate(function () { return load(); });
  26877. }
  26878. else {
  26879. _this._texture.onLoadedObservable.add(load);
  26880. }
  26881. }
  26882. return _this;
  26883. }
  26884. Object.defineProperty(Texture.prototype, "noMipmap", {
  26885. get: function () {
  26886. return this._noMipmap;
  26887. },
  26888. enumerable: true,
  26889. configurable: true
  26890. });
  26891. Object.defineProperty(Texture.prototype, "isBlocking", {
  26892. get: function () {
  26893. return this._isBlocking;
  26894. },
  26895. set: function (value) {
  26896. this._isBlocking = value;
  26897. },
  26898. enumerable: true,
  26899. configurable: true
  26900. });
  26901. Object.defineProperty(Texture.prototype, "samplingMode", {
  26902. get: function () {
  26903. return this._samplingMode;
  26904. },
  26905. enumerable: true,
  26906. configurable: true
  26907. });
  26908. Texture.prototype.updateURL = function (url) {
  26909. this.url = url;
  26910. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26911. this.delayLoad();
  26912. };
  26913. Texture.prototype.delayLoad = function () {
  26914. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26915. return;
  26916. }
  26917. var scene = this.getScene();
  26918. if (!scene) {
  26919. return;
  26920. }
  26921. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26922. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26923. if (!this._texture) {
  26924. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26925. if (this._deleteBuffer) {
  26926. delete this._buffer;
  26927. }
  26928. }
  26929. else {
  26930. if (this._delayedOnLoad) {
  26931. if (this._texture.isReady) {
  26932. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26933. }
  26934. else {
  26935. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26936. }
  26937. }
  26938. }
  26939. this._delayedOnLoad = null;
  26940. this._delayedOnError = null;
  26941. };
  26942. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26943. if (!this._texture) {
  26944. return;
  26945. }
  26946. var scene = this.getScene();
  26947. if (!scene) {
  26948. return;
  26949. }
  26950. this._samplingMode = samplingMode;
  26951. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26952. };
  26953. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26954. x *= this.uScale;
  26955. y *= this.vScale;
  26956. x -= 0.5 * this.uScale;
  26957. y -= 0.5 * this.vScale;
  26958. z -= 0.5;
  26959. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26960. t.x += 0.5 * this.uScale + this.uOffset;
  26961. t.y += 0.5 * this.vScale + this.vOffset;
  26962. t.z += 0.5;
  26963. };
  26964. Texture.prototype.getTextureMatrix = function () {
  26965. var _this = this;
  26966. if (this.uOffset === this._cachedUOffset &&
  26967. this.vOffset === this._cachedVOffset &&
  26968. this.uScale === this._cachedUScale &&
  26969. this.vScale === this._cachedVScale &&
  26970. this.uAng === this._cachedUAng &&
  26971. this.vAng === this._cachedVAng &&
  26972. this.wAng === this._cachedWAng) {
  26973. return this._cachedTextureMatrix;
  26974. }
  26975. this._cachedUOffset = this.uOffset;
  26976. this._cachedVOffset = this.vOffset;
  26977. this._cachedUScale = this.uScale;
  26978. this._cachedVScale = this.vScale;
  26979. this._cachedUAng = this.uAng;
  26980. this._cachedVAng = this.vAng;
  26981. this._cachedWAng = this.wAng;
  26982. if (!this._cachedTextureMatrix) {
  26983. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26984. this._rowGenerationMatrix = new BABYLON.Matrix();
  26985. this._t0 = BABYLON.Vector3.Zero();
  26986. this._t1 = BABYLON.Vector3.Zero();
  26987. this._t2 = BABYLON.Vector3.Zero();
  26988. }
  26989. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26990. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26991. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26992. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26993. this._t1.subtractInPlace(this._t0);
  26994. this._t2.subtractInPlace(this._t0);
  26995. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26996. this._cachedTextureMatrix.m[0] = this._t1.x;
  26997. this._cachedTextureMatrix.m[1] = this._t1.y;
  26998. this._cachedTextureMatrix.m[2] = this._t1.z;
  26999. this._cachedTextureMatrix.m[4] = this._t2.x;
  27000. this._cachedTextureMatrix.m[5] = this._t2.y;
  27001. this._cachedTextureMatrix.m[6] = this._t2.z;
  27002. this._cachedTextureMatrix.m[8] = this._t0.x;
  27003. this._cachedTextureMatrix.m[9] = this._t0.y;
  27004. this._cachedTextureMatrix.m[10] = this._t0.z;
  27005. var scene = this.getScene();
  27006. if (!scene) {
  27007. return this._cachedTextureMatrix;
  27008. }
  27009. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27010. return mat.hasTexture(_this);
  27011. });
  27012. return this._cachedTextureMatrix;
  27013. };
  27014. Texture.prototype.getReflectionTextureMatrix = function () {
  27015. var _this = this;
  27016. var scene = this.getScene();
  27017. if (!scene) {
  27018. return this._cachedTextureMatrix;
  27019. }
  27020. if (this.uOffset === this._cachedUOffset &&
  27021. this.vOffset === this._cachedVOffset &&
  27022. this.uScale === this._cachedUScale &&
  27023. this.vScale === this._cachedVScale &&
  27024. this.coordinatesMode === this._cachedCoordinatesMode) {
  27025. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27026. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27027. return this._cachedTextureMatrix;
  27028. }
  27029. }
  27030. else {
  27031. return this._cachedTextureMatrix;
  27032. }
  27033. }
  27034. if (!this._cachedTextureMatrix) {
  27035. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27036. }
  27037. if (!this._projectionModeMatrix) {
  27038. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27039. }
  27040. this._cachedUOffset = this.uOffset;
  27041. this._cachedVOffset = this.vOffset;
  27042. this._cachedUScale = this.uScale;
  27043. this._cachedVScale = this.vScale;
  27044. this._cachedCoordinatesMode = this.coordinatesMode;
  27045. switch (this.coordinatesMode) {
  27046. case Texture.PLANAR_MODE:
  27047. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27048. this._cachedTextureMatrix[0] = this.uScale;
  27049. this._cachedTextureMatrix[5] = this.vScale;
  27050. this._cachedTextureMatrix[12] = this.uOffset;
  27051. this._cachedTextureMatrix[13] = this.vOffset;
  27052. break;
  27053. case Texture.PROJECTION_MODE:
  27054. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27055. this._projectionModeMatrix.m[0] = 0.5;
  27056. this._projectionModeMatrix.m[5] = -0.5;
  27057. this._projectionModeMatrix.m[10] = 0.0;
  27058. this._projectionModeMatrix.m[12] = 0.5;
  27059. this._projectionModeMatrix.m[13] = 0.5;
  27060. this._projectionModeMatrix.m[14] = 1.0;
  27061. this._projectionModeMatrix.m[15] = 1.0;
  27062. var projectionMatrix = scene.getProjectionMatrix();
  27063. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27064. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27065. break;
  27066. default:
  27067. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27068. break;
  27069. }
  27070. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27071. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27072. });
  27073. return this._cachedTextureMatrix;
  27074. };
  27075. Texture.prototype.clone = function () {
  27076. var _this = this;
  27077. return BABYLON.SerializationHelper.Clone(function () {
  27078. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27079. }, this);
  27080. };
  27081. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27082. get: function () {
  27083. if (!this._onLoadObservable) {
  27084. this._onLoadObservable = new BABYLON.Observable();
  27085. }
  27086. return this._onLoadObservable;
  27087. },
  27088. enumerable: true,
  27089. configurable: true
  27090. });
  27091. Texture.prototype.serialize = function () {
  27092. var serializationObject = _super.prototype.serialize.call(this);
  27093. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27094. serializationObject.base64String = this._buffer;
  27095. serializationObject.name = serializationObject.name.replace("data:", "");
  27096. }
  27097. return serializationObject;
  27098. };
  27099. Texture.prototype.getClassName = function () {
  27100. return "Texture";
  27101. };
  27102. Texture.prototype.dispose = function () {
  27103. _super.prototype.dispose.call(this);
  27104. if (this.onLoadObservable) {
  27105. this.onLoadObservable.clear();
  27106. this._onLoadObservable = null;
  27107. }
  27108. this._delayedOnLoad = null;
  27109. this._delayedOnError = null;
  27110. };
  27111. // Statics
  27112. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27113. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27114. if (onLoad === void 0) { onLoad = null; }
  27115. if (onError === void 0) { onError = null; }
  27116. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27117. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27118. };
  27119. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27120. if (parsedTexture.customType) {
  27121. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27122. // Update Sampling Mode
  27123. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27124. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27125. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27126. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27127. }
  27128. }
  27129. return parsedCustomTexture;
  27130. }
  27131. if (parsedTexture.isCube) {
  27132. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27133. }
  27134. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27135. return null;
  27136. }
  27137. var texture = BABYLON.SerializationHelper.Parse(function () {
  27138. var generateMipMaps = true;
  27139. if (parsedTexture.noMipmap) {
  27140. generateMipMaps = false;
  27141. }
  27142. if (parsedTexture.mirrorPlane) {
  27143. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27144. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27145. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27146. return mirrorTexture;
  27147. }
  27148. else if (parsedTexture.isRenderTarget) {
  27149. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27150. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27151. return renderTargetTexture;
  27152. }
  27153. else {
  27154. var texture;
  27155. if (parsedTexture.base64String) {
  27156. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27157. }
  27158. else {
  27159. var url = rootUrl + parsedTexture.name;
  27160. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27161. url = parsedTexture.url;
  27162. }
  27163. texture = new Texture(url, scene, !generateMipMaps);
  27164. }
  27165. return texture;
  27166. }
  27167. }, parsedTexture, scene);
  27168. // Update Sampling Mode
  27169. if (parsedTexture.samplingMode) {
  27170. var sampling = parsedTexture.samplingMode;
  27171. if (texture._samplingMode !== sampling) {
  27172. texture.updateSamplingMode(sampling);
  27173. }
  27174. }
  27175. // Animations
  27176. if (parsedTexture.animations) {
  27177. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27178. var parsedAnimation = parsedTexture.animations[animationIndex];
  27179. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27180. }
  27181. }
  27182. return texture;
  27183. };
  27184. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27185. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27186. if (noMipmap === void 0) { noMipmap = false; }
  27187. if (invertY === void 0) { invertY = true; }
  27188. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27189. if (onLoad === void 0) { onLoad = null; }
  27190. if (onError === void 0) { onError = null; }
  27191. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27192. if (name.substr(0, 5) !== "data:") {
  27193. name = "data:" + name;
  27194. }
  27195. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27196. };
  27197. // Constants
  27198. Texture.NEAREST_SAMPLINGMODE = 1;
  27199. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27200. Texture.BILINEAR_SAMPLINGMODE = 2;
  27201. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27202. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27203. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27204. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27205. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27206. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27207. Texture.NEAREST_LINEAR = 7;
  27208. Texture.NEAREST_NEAREST = 8;
  27209. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27210. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27211. Texture.LINEAR_LINEAR = 11;
  27212. Texture.LINEAR_NEAREST = 12;
  27213. Texture.EXPLICIT_MODE = 0;
  27214. Texture.SPHERICAL_MODE = 1;
  27215. Texture.PLANAR_MODE = 2;
  27216. Texture.CUBIC_MODE = 3;
  27217. Texture.PROJECTION_MODE = 4;
  27218. Texture.SKYBOX_MODE = 5;
  27219. Texture.INVCUBIC_MODE = 6;
  27220. Texture.EQUIRECTANGULAR_MODE = 7;
  27221. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27222. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27223. Texture.CLAMP_ADDRESSMODE = 0;
  27224. Texture.WRAP_ADDRESSMODE = 1;
  27225. Texture.MIRROR_ADDRESSMODE = 2;
  27226. /**
  27227. * 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
  27228. */
  27229. Texture.UseSerializedUrlIfAny = false;
  27230. __decorate([
  27231. BABYLON.serialize()
  27232. ], Texture.prototype, "url", void 0);
  27233. __decorate([
  27234. BABYLON.serialize()
  27235. ], Texture.prototype, "uOffset", void 0);
  27236. __decorate([
  27237. BABYLON.serialize()
  27238. ], Texture.prototype, "vOffset", void 0);
  27239. __decorate([
  27240. BABYLON.serialize()
  27241. ], Texture.prototype, "uScale", void 0);
  27242. __decorate([
  27243. BABYLON.serialize()
  27244. ], Texture.prototype, "vScale", void 0);
  27245. __decorate([
  27246. BABYLON.serialize()
  27247. ], Texture.prototype, "uAng", void 0);
  27248. __decorate([
  27249. BABYLON.serialize()
  27250. ], Texture.prototype, "vAng", void 0);
  27251. __decorate([
  27252. BABYLON.serialize()
  27253. ], Texture.prototype, "wAng", void 0);
  27254. __decorate([
  27255. BABYLON.serialize()
  27256. ], Texture.prototype, "isBlocking", null);
  27257. return Texture;
  27258. }(BABYLON.BaseTexture));
  27259. BABYLON.Texture = Texture;
  27260. })(BABYLON || (BABYLON = {}));
  27261. //# sourceMappingURL=babylon.texture.js.map
  27262. var BABYLON;
  27263. (function (BABYLON) {
  27264. var _InstancesBatch = /** @class */ (function () {
  27265. function _InstancesBatch() {
  27266. this.mustReturn = false;
  27267. this.visibleInstances = new Array();
  27268. this.renderSelf = new Array();
  27269. }
  27270. return _InstancesBatch;
  27271. }());
  27272. BABYLON._InstancesBatch = _InstancesBatch;
  27273. var Mesh = /** @class */ (function (_super) {
  27274. __extends(Mesh, _super);
  27275. /**
  27276. * @constructor
  27277. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27278. * @param {Scene} scene The scene to add this mesh to.
  27279. * @param {Node} parent The parent of this mesh, if it has one
  27280. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27281. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27282. * When false, achieved by calling a clone(), also passing False.
  27283. * This will make creation of children, recursive.
  27284. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27285. */
  27286. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27287. if (scene === void 0) { scene = null; }
  27288. if (parent === void 0) { parent = null; }
  27289. if (source === void 0) { source = null; }
  27290. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27291. var _this = _super.call(this, name, scene) || this;
  27292. // Events
  27293. /**
  27294. * An event triggered before rendering the mesh
  27295. * @type {BABYLON.Observable}
  27296. */
  27297. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27298. /**
  27299. * An event triggered after rendering the mesh
  27300. * @type {BABYLON.Observable}
  27301. */
  27302. _this.onAfterRenderObservable = new BABYLON.Observable();
  27303. /**
  27304. * An event triggered before drawing the mesh
  27305. * @type {BABYLON.Observable}
  27306. */
  27307. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27308. // Members
  27309. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27310. _this.instances = new Array();
  27311. _this._LODLevels = new Array();
  27312. _this._visibleInstances = {};
  27313. _this._renderIdForInstances = new Array();
  27314. _this._batchCache = new _InstancesBatch();
  27315. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27316. // Use by builder only to know what orientation were the mesh build in.
  27317. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27318. _this.overrideMaterialSideOrientation = null;
  27319. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27320. // Will be used to save a source mesh reference, If any
  27321. _this._source = null;
  27322. scene = _this.getScene();
  27323. if (source) {
  27324. // Source mesh
  27325. _this._source = source;
  27326. // Geometry
  27327. if (source._geometry) {
  27328. source._geometry.applyToMesh(_this);
  27329. }
  27330. // Deep copy
  27331. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27332. // Metadata
  27333. if (source.metadata && source.metadata.clone) {
  27334. _this.metadata = source.metadata.clone();
  27335. }
  27336. else {
  27337. _this.metadata = source.metadata;
  27338. }
  27339. // Tags
  27340. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27341. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27342. }
  27343. // Parent
  27344. _this.parent = source.parent;
  27345. // Pivot
  27346. _this.setPivotMatrix(source.getPivotMatrix());
  27347. _this.id = name + "." + source.id;
  27348. // Material
  27349. _this.material = source.material;
  27350. var index;
  27351. if (!doNotCloneChildren) {
  27352. // Children
  27353. var directDescendants = source.getDescendants(true);
  27354. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27355. var child = directDescendants[index_1];
  27356. if (child.clone) {
  27357. child.clone(name + "." + child.name, _this);
  27358. }
  27359. }
  27360. }
  27361. // Physics clone
  27362. var physicsEngine = _this.getScene().getPhysicsEngine();
  27363. if (clonePhysicsImpostor && physicsEngine) {
  27364. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27365. if (impostor) {
  27366. _this.physicsImpostor = impostor.clone(_this);
  27367. }
  27368. }
  27369. // Particles
  27370. for (index = 0; index < scene.particleSystems.length; index++) {
  27371. var system = scene.particleSystems[index];
  27372. if (system.emitter === source) {
  27373. system.clone(system.name, _this);
  27374. }
  27375. }
  27376. _this.computeWorldMatrix(true);
  27377. }
  27378. // Parent
  27379. if (parent !== null) {
  27380. _this.parent = parent;
  27381. }
  27382. return _this;
  27383. }
  27384. Object.defineProperty(Mesh, "FRONTSIDE", {
  27385. /**
  27386. * Mesh side orientation : usually the external or front surface
  27387. */
  27388. get: function () {
  27389. return Mesh._FRONTSIDE;
  27390. },
  27391. enumerable: true,
  27392. configurable: true
  27393. });
  27394. Object.defineProperty(Mesh, "BACKSIDE", {
  27395. /**
  27396. * Mesh side orientation : usually the internal or back surface
  27397. */
  27398. get: function () {
  27399. return Mesh._BACKSIDE;
  27400. },
  27401. enumerable: true,
  27402. configurable: true
  27403. });
  27404. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27405. /**
  27406. * Mesh side orientation : both internal and external or front and back surfaces
  27407. */
  27408. get: function () {
  27409. return Mesh._DOUBLESIDE;
  27410. },
  27411. enumerable: true,
  27412. configurable: true
  27413. });
  27414. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27415. /**
  27416. * Mesh side orientation : by default, `FRONTSIDE`
  27417. */
  27418. get: function () {
  27419. return Mesh._DEFAULTSIDE;
  27420. },
  27421. enumerable: true,
  27422. configurable: true
  27423. });
  27424. Object.defineProperty(Mesh, "NO_CAP", {
  27425. /**
  27426. * Mesh cap setting : no cap
  27427. */
  27428. get: function () {
  27429. return Mesh._NO_CAP;
  27430. },
  27431. enumerable: true,
  27432. configurable: true
  27433. });
  27434. Object.defineProperty(Mesh, "CAP_START", {
  27435. /**
  27436. * Mesh cap setting : one cap at the beginning of the mesh
  27437. */
  27438. get: function () {
  27439. return Mesh._CAP_START;
  27440. },
  27441. enumerable: true,
  27442. configurable: true
  27443. });
  27444. Object.defineProperty(Mesh, "CAP_END", {
  27445. /**
  27446. * Mesh cap setting : one cap at the end of the mesh
  27447. */
  27448. get: function () {
  27449. return Mesh._CAP_END;
  27450. },
  27451. enumerable: true,
  27452. configurable: true
  27453. });
  27454. Object.defineProperty(Mesh, "CAP_ALL", {
  27455. /**
  27456. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27457. */
  27458. get: function () {
  27459. return Mesh._CAP_ALL;
  27460. },
  27461. enumerable: true,
  27462. configurable: true
  27463. });
  27464. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27465. set: function (callback) {
  27466. if (this._onBeforeDrawObserver) {
  27467. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27468. }
  27469. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27470. },
  27471. enumerable: true,
  27472. configurable: true
  27473. });
  27474. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27475. get: function () {
  27476. return this._morphTargetManager;
  27477. },
  27478. set: function (value) {
  27479. if (this._morphTargetManager === value) {
  27480. return;
  27481. }
  27482. this._morphTargetManager = value;
  27483. this._syncGeometryWithMorphTargetManager();
  27484. },
  27485. enumerable: true,
  27486. configurable: true
  27487. });
  27488. Object.defineProperty(Mesh.prototype, "source", {
  27489. get: function () {
  27490. return this._source;
  27491. },
  27492. enumerable: true,
  27493. configurable: true
  27494. });
  27495. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27496. get: function () {
  27497. return this._unIndexed;
  27498. },
  27499. set: function (value) {
  27500. if (this._unIndexed !== value) {
  27501. this._unIndexed = value;
  27502. this._markSubMeshesAsAttributesDirty();
  27503. }
  27504. },
  27505. enumerable: true,
  27506. configurable: true
  27507. });
  27508. // Methods
  27509. /**
  27510. * Returns the string "Mesh".
  27511. */
  27512. Mesh.prototype.getClassName = function () {
  27513. return "Mesh";
  27514. };
  27515. /**
  27516. * Returns a string.
  27517. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27518. */
  27519. Mesh.prototype.toString = function (fullDetails) {
  27520. var ret = _super.prototype.toString.call(this, fullDetails);
  27521. ret += ", n vertices: " + this.getTotalVertices();
  27522. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27523. if (this.animations) {
  27524. for (var i = 0; i < this.animations.length; i++) {
  27525. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27526. }
  27527. }
  27528. if (fullDetails) {
  27529. if (this._geometry) {
  27530. var ib = this.getIndices();
  27531. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27532. if (vb && ib) {
  27533. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27534. }
  27535. }
  27536. else {
  27537. ret += ", flat shading: UNKNOWN";
  27538. }
  27539. }
  27540. return ret;
  27541. };
  27542. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27543. /**
  27544. * True if the mesh has some Levels Of Details (LOD).
  27545. * Returns a boolean.
  27546. */
  27547. get: function () {
  27548. return this._LODLevels.length > 0;
  27549. },
  27550. enumerable: true,
  27551. configurable: true
  27552. });
  27553. /**
  27554. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27555. * @returns an array of {BABYLON.MeshLODLevel}
  27556. */
  27557. Mesh.prototype.getLODLevels = function () {
  27558. return this._LODLevels;
  27559. };
  27560. Mesh.prototype._sortLODLevels = function () {
  27561. this._LODLevels.sort(function (a, b) {
  27562. if (a.distance < b.distance) {
  27563. return 1;
  27564. }
  27565. if (a.distance > b.distance) {
  27566. return -1;
  27567. }
  27568. return 0;
  27569. });
  27570. };
  27571. /**
  27572. * Add a mesh as LOD level triggered at the given distance.
  27573. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27574. * @param {number} distance The distance from the center of the object to show this level
  27575. * @param {Mesh} mesh The mesh to be added as LOD level
  27576. * @return {Mesh} This mesh (for chaining)
  27577. */
  27578. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27579. if (mesh && mesh._masterMesh) {
  27580. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27581. return this;
  27582. }
  27583. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27584. this._LODLevels.push(level);
  27585. if (mesh) {
  27586. mesh._masterMesh = this;
  27587. }
  27588. this._sortLODLevels();
  27589. return this;
  27590. };
  27591. /**
  27592. * Returns the LOD level mesh at the passed distance or null if not found.
  27593. * It is related to the method `addLODLevel(distance, mesh)`.
  27594. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27595. * Returns an object Mesh or `null`.
  27596. */
  27597. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27598. for (var index = 0; index < this._LODLevels.length; index++) {
  27599. var level = this._LODLevels[index];
  27600. if (level.distance === distance) {
  27601. return level.mesh;
  27602. }
  27603. }
  27604. return null;
  27605. };
  27606. /**
  27607. * Remove a mesh from the LOD array
  27608. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27609. * @param {Mesh} mesh The mesh to be removed.
  27610. * @return {Mesh} This mesh (for chaining)
  27611. */
  27612. Mesh.prototype.removeLODLevel = function (mesh) {
  27613. for (var index = 0; index < this._LODLevels.length; index++) {
  27614. if (this._LODLevels[index].mesh === mesh) {
  27615. this._LODLevels.splice(index, 1);
  27616. if (mesh) {
  27617. mesh._masterMesh = null;
  27618. }
  27619. }
  27620. }
  27621. this._sortLODLevels();
  27622. return this;
  27623. };
  27624. /**
  27625. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27626. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27627. */
  27628. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27629. if (!this._LODLevels || this._LODLevels.length === 0) {
  27630. return this;
  27631. }
  27632. var bSphere;
  27633. if (boundingSphere) {
  27634. bSphere = boundingSphere;
  27635. }
  27636. else {
  27637. var boundingInfo = this.getBoundingInfo();
  27638. bSphere = boundingInfo.boundingSphere;
  27639. }
  27640. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27641. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27642. if (this.onLODLevelSelection) {
  27643. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27644. }
  27645. return this;
  27646. }
  27647. for (var index = 0; index < this._LODLevels.length; index++) {
  27648. var level = this._LODLevels[index];
  27649. if (level.distance < distanceToCamera) {
  27650. if (level.mesh) {
  27651. level.mesh._preActivate();
  27652. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27653. }
  27654. if (this.onLODLevelSelection) {
  27655. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27656. }
  27657. return level.mesh;
  27658. }
  27659. }
  27660. if (this.onLODLevelSelection) {
  27661. this.onLODLevelSelection(distanceToCamera, this, this);
  27662. }
  27663. return this;
  27664. };
  27665. Object.defineProperty(Mesh.prototype, "geometry", {
  27666. /**
  27667. * Returns the mesh internal Geometry object.
  27668. */
  27669. get: function () {
  27670. return this._geometry;
  27671. },
  27672. enumerable: true,
  27673. configurable: true
  27674. });
  27675. /**
  27676. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27677. */
  27678. Mesh.prototype.getTotalVertices = function () {
  27679. if (this._geometry === null || this._geometry === undefined) {
  27680. return 0;
  27681. }
  27682. return this._geometry.getTotalVertices();
  27683. };
  27684. /**
  27685. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27686. * 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.
  27687. * You can force the copy with forceCopy === true
  27688. * Returns null if the mesh has no geometry or no vertex buffer.
  27689. * Possible `kind` values :
  27690. * - BABYLON.VertexBuffer.PositionKind
  27691. * - BABYLON.VertexBuffer.UVKind
  27692. * - BABYLON.VertexBuffer.UV2Kind
  27693. * - BABYLON.VertexBuffer.UV3Kind
  27694. * - BABYLON.VertexBuffer.UV4Kind
  27695. * - BABYLON.VertexBuffer.UV5Kind
  27696. * - BABYLON.VertexBuffer.UV6Kind
  27697. * - BABYLON.VertexBuffer.ColorKind
  27698. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27699. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27700. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27701. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27702. */
  27703. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27704. if (!this._geometry) {
  27705. return null;
  27706. }
  27707. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27708. };
  27709. /**
  27710. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27711. * Returns `null` if the mesh has no geometry.
  27712. * Possible `kind` values :
  27713. * - BABYLON.VertexBuffer.PositionKind
  27714. * - BABYLON.VertexBuffer.UVKind
  27715. * - BABYLON.VertexBuffer.UV2Kind
  27716. * - BABYLON.VertexBuffer.UV3Kind
  27717. * - BABYLON.VertexBuffer.UV4Kind
  27718. * - BABYLON.VertexBuffer.UV5Kind
  27719. * - BABYLON.VertexBuffer.UV6Kind
  27720. * - BABYLON.VertexBuffer.ColorKind
  27721. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27722. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27723. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27724. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27725. */
  27726. Mesh.prototype.getVertexBuffer = function (kind) {
  27727. if (!this._geometry) {
  27728. return null;
  27729. }
  27730. return this._geometry.getVertexBuffer(kind);
  27731. };
  27732. /**
  27733. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27734. * Possible `kind` values :
  27735. * - BABYLON.VertexBuffer.PositionKind
  27736. * - BABYLON.VertexBuffer.UVKind
  27737. * - BABYLON.VertexBuffer.UV2Kind
  27738. * - BABYLON.VertexBuffer.UV3Kind
  27739. * - BABYLON.VertexBuffer.UV4Kind
  27740. * - BABYLON.VertexBuffer.UV5Kind
  27741. * - BABYLON.VertexBuffer.UV6Kind
  27742. * - BABYLON.VertexBuffer.ColorKind
  27743. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27744. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27745. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27746. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27747. */
  27748. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27749. if (!this._geometry) {
  27750. if (this._delayInfo) {
  27751. return this._delayInfo.indexOf(kind) !== -1;
  27752. }
  27753. return false;
  27754. }
  27755. return this._geometry.isVerticesDataPresent(kind);
  27756. };
  27757. /**
  27758. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27759. * Possible `kind` values :
  27760. * - BABYLON.VertexBuffer.PositionKind
  27761. * - BABYLON.VertexBuffer.UVKind
  27762. * - BABYLON.VertexBuffer.UV2Kind
  27763. * - BABYLON.VertexBuffer.UV3Kind
  27764. * - BABYLON.VertexBuffer.UV4Kind
  27765. * - BABYLON.VertexBuffer.UV5Kind
  27766. * - BABYLON.VertexBuffer.UV6Kind
  27767. * - BABYLON.VertexBuffer.ColorKind
  27768. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27769. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27770. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27771. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27772. */
  27773. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27774. if (!this._geometry) {
  27775. if (this._delayInfo) {
  27776. return this._delayInfo.indexOf(kind) !== -1;
  27777. }
  27778. return false;
  27779. }
  27780. return this._geometry.isVertexBufferUpdatable(kind);
  27781. };
  27782. /**
  27783. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27784. * Possible `kind` values :
  27785. * - BABYLON.VertexBuffer.PositionKind
  27786. * - BABYLON.VertexBuffer.UVKind
  27787. * - BABYLON.VertexBuffer.UV2Kind
  27788. * - BABYLON.VertexBuffer.UV3Kind
  27789. * - BABYLON.VertexBuffer.UV4Kind
  27790. * - BABYLON.VertexBuffer.UV5Kind
  27791. * - BABYLON.VertexBuffer.UV6Kind
  27792. * - BABYLON.VertexBuffer.ColorKind
  27793. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27794. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27795. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27796. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27797. */
  27798. Mesh.prototype.getVerticesDataKinds = function () {
  27799. if (!this._geometry) {
  27800. var result = new Array();
  27801. if (this._delayInfo) {
  27802. this._delayInfo.forEach(function (kind, index, array) {
  27803. result.push(kind);
  27804. });
  27805. }
  27806. return result;
  27807. }
  27808. return this._geometry.getVerticesDataKinds();
  27809. };
  27810. /**
  27811. * Returns a positive integer : the total number of indices in this mesh geometry.
  27812. * Returns zero if the mesh has no geometry.
  27813. */
  27814. Mesh.prototype.getTotalIndices = function () {
  27815. if (!this._geometry) {
  27816. return 0;
  27817. }
  27818. return this._geometry.getTotalIndices();
  27819. };
  27820. /**
  27821. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27822. * 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.
  27823. * Returns an empty array if the mesh has no geometry.
  27824. */
  27825. Mesh.prototype.getIndices = function (copyWhenShared) {
  27826. if (!this._geometry) {
  27827. return [];
  27828. }
  27829. return this._geometry.getIndices(copyWhenShared);
  27830. };
  27831. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27832. get: function () {
  27833. return this._masterMesh !== null && this._masterMesh !== undefined;
  27834. },
  27835. enumerable: true,
  27836. configurable: true
  27837. });
  27838. /**
  27839. * Determine if the current mesh is ready to be rendered
  27840. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27841. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27842. * @returns true if all associated assets are ready (material, textures, shaders)
  27843. */
  27844. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27845. if (completeCheck === void 0) { completeCheck = false; }
  27846. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27847. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27848. return false;
  27849. }
  27850. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27851. return false;
  27852. }
  27853. if (!this.subMeshes || this.subMeshes.length === 0) {
  27854. return true;
  27855. }
  27856. if (!completeCheck) {
  27857. return true;
  27858. }
  27859. var engine = this.getEngine();
  27860. var scene = this.getScene();
  27861. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27862. this.computeWorldMatrix();
  27863. var mat = this.material || scene.defaultMaterial;
  27864. if (mat) {
  27865. if (mat.storeEffectOnSubMeshes) {
  27866. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27867. var subMesh = _a[_i];
  27868. var effectiveMaterial = subMesh.getMaterial();
  27869. if (effectiveMaterial) {
  27870. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27871. return false;
  27872. }
  27873. }
  27874. }
  27875. }
  27876. else {
  27877. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27878. return false;
  27879. }
  27880. }
  27881. }
  27882. // Shadows
  27883. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27884. var light = _c[_b];
  27885. var generator = light.getShadowGenerator();
  27886. if (generator) {
  27887. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27888. var subMesh = _e[_d];
  27889. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27890. return false;
  27891. }
  27892. }
  27893. }
  27894. }
  27895. // LOD
  27896. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27897. var lod = _g[_f];
  27898. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27899. return false;
  27900. }
  27901. }
  27902. return true;
  27903. };
  27904. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27905. /**
  27906. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27907. * This property is pertinent only for updatable parametric shapes.
  27908. */
  27909. get: function () {
  27910. return this._areNormalsFrozen;
  27911. },
  27912. enumerable: true,
  27913. configurable: true
  27914. });
  27915. /**
  27916. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27917. * It has no effect at all on other shapes.
  27918. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27919. * Returns the Mesh.
  27920. */
  27921. Mesh.prototype.freezeNormals = function () {
  27922. this._areNormalsFrozen = true;
  27923. return this;
  27924. };
  27925. /**
  27926. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27927. * It has no effect at all on other shapes.
  27928. * It reactivates the mesh normals computation if it was previously frozen.
  27929. * Returns the Mesh.
  27930. */
  27931. Mesh.prototype.unfreezeNormals = function () {
  27932. this._areNormalsFrozen = false;
  27933. return this;
  27934. };
  27935. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27936. /**
  27937. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27938. */
  27939. set: function (count) {
  27940. this._overridenInstanceCount = count;
  27941. },
  27942. enumerable: true,
  27943. configurable: true
  27944. });
  27945. // Methods
  27946. Mesh.prototype._preActivate = function () {
  27947. var sceneRenderId = this.getScene().getRenderId();
  27948. if (this._preActivateId === sceneRenderId) {
  27949. return this;
  27950. }
  27951. this._preActivateId = sceneRenderId;
  27952. this._visibleInstances = null;
  27953. return this;
  27954. };
  27955. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27956. if (this._visibleInstances) {
  27957. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27958. }
  27959. return this;
  27960. };
  27961. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27962. if (!this._visibleInstances) {
  27963. this._visibleInstances = {};
  27964. this._visibleInstances.defaultRenderId = renderId;
  27965. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27966. }
  27967. if (!this._visibleInstances[renderId]) {
  27968. this._visibleInstances[renderId] = new Array();
  27969. }
  27970. this._visibleInstances[renderId].push(instance);
  27971. return this;
  27972. };
  27973. /**
  27974. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27975. * This means the mesh underlying bounding box and sphere are recomputed.
  27976. * Returns the Mesh.
  27977. */
  27978. Mesh.prototype.refreshBoundingInfo = function () {
  27979. return this._refreshBoundingInfo(false);
  27980. };
  27981. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27982. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27983. return this;
  27984. }
  27985. var data = this._getPositionData(applySkeleton);
  27986. if (data) {
  27987. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27988. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27989. }
  27990. if (this.subMeshes) {
  27991. for (var index = 0; index < this.subMeshes.length; index++) {
  27992. this.subMeshes[index].refreshBoundingInfo();
  27993. }
  27994. }
  27995. this._updateBoundingInfo();
  27996. return this;
  27997. };
  27998. Mesh.prototype._getPositionData = function (applySkeleton) {
  27999. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28000. if (data && applySkeleton && this.skeleton) {
  28001. data = BABYLON.Tools.Slice(data);
  28002. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28003. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28004. if (matricesWeightsData && matricesIndicesData) {
  28005. var needExtras = this.numBoneInfluencers > 4;
  28006. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28007. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28008. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28009. var tempVector = BABYLON.Tmp.Vector3[0];
  28010. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28011. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28012. var matWeightIdx = 0;
  28013. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28014. finalMatrix.reset();
  28015. var inf;
  28016. var weight;
  28017. for (inf = 0; inf < 4; inf++) {
  28018. weight = matricesWeightsData[matWeightIdx + inf];
  28019. if (weight <= 0)
  28020. break;
  28021. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28022. finalMatrix.addToSelf(tempMatrix);
  28023. }
  28024. if (needExtras) {
  28025. for (inf = 0; inf < 4; inf++) {
  28026. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28027. if (weight <= 0)
  28028. break;
  28029. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28030. finalMatrix.addToSelf(tempMatrix);
  28031. }
  28032. }
  28033. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28034. tempVector.toArray(data, index);
  28035. }
  28036. }
  28037. }
  28038. return data;
  28039. };
  28040. Mesh.prototype._createGlobalSubMesh = function (force) {
  28041. var totalVertices = this.getTotalVertices();
  28042. if (!totalVertices || !this.getIndices()) {
  28043. return null;
  28044. }
  28045. // Check if we need to recreate the submeshes
  28046. if (this.subMeshes && this.subMeshes.length > 0) {
  28047. var ib = this.getIndices();
  28048. if (!ib) {
  28049. return null;
  28050. }
  28051. var totalIndices = ib.length;
  28052. var needToRecreate = false;
  28053. if (force) {
  28054. needToRecreate = true;
  28055. }
  28056. else {
  28057. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28058. var submesh = _a[_i];
  28059. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28060. needToRecreate = true;
  28061. break;
  28062. }
  28063. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28064. needToRecreate = true;
  28065. break;
  28066. }
  28067. }
  28068. }
  28069. if (!needToRecreate) {
  28070. return this.subMeshes[0];
  28071. }
  28072. }
  28073. this.releaseSubMeshes();
  28074. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28075. };
  28076. Mesh.prototype.subdivide = function (count) {
  28077. if (count < 1) {
  28078. return;
  28079. }
  28080. var totalIndices = this.getTotalIndices();
  28081. var subdivisionSize = (totalIndices / count) | 0;
  28082. var offset = 0;
  28083. // Ensure that subdivisionSize is a multiple of 3
  28084. while (subdivisionSize % 3 !== 0) {
  28085. subdivisionSize++;
  28086. }
  28087. this.releaseSubMeshes();
  28088. for (var index = 0; index < count; index++) {
  28089. if (offset >= totalIndices) {
  28090. break;
  28091. }
  28092. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28093. offset += subdivisionSize;
  28094. }
  28095. this.synchronizeInstances();
  28096. };
  28097. /**
  28098. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28099. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28100. * The `data` are either a numeric array either a Float32Array.
  28101. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28102. * 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).
  28103. * Note that a new underlying VertexBuffer object is created each call.
  28104. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28105. *
  28106. * Possible `kind` values :
  28107. * - BABYLON.VertexBuffer.PositionKind
  28108. * - BABYLON.VertexBuffer.UVKind
  28109. * - BABYLON.VertexBuffer.UV2Kind
  28110. * - BABYLON.VertexBuffer.UV3Kind
  28111. * - BABYLON.VertexBuffer.UV4Kind
  28112. * - BABYLON.VertexBuffer.UV5Kind
  28113. * - BABYLON.VertexBuffer.UV6Kind
  28114. * - BABYLON.VertexBuffer.ColorKind
  28115. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28116. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28117. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28118. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28119. *
  28120. * Returns the Mesh.
  28121. */
  28122. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28123. if (updatable === void 0) { updatable = false; }
  28124. if (!this._geometry) {
  28125. var vertexData = new BABYLON.VertexData();
  28126. vertexData.set(data, kind);
  28127. var scene = this.getScene();
  28128. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28129. }
  28130. else {
  28131. this._geometry.setVerticesData(kind, data, updatable, stride);
  28132. }
  28133. return this;
  28134. };
  28135. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28136. if (updatable === void 0) { updatable = true; }
  28137. var vb = this.getVertexBuffer(kind);
  28138. if (!vb || vb.isUpdatable() === updatable) {
  28139. return;
  28140. }
  28141. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28142. };
  28143. /**
  28144. * Sets the mesh VertexBuffer.
  28145. * Returns the Mesh.
  28146. */
  28147. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28148. if (!this._geometry) {
  28149. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28150. }
  28151. this._geometry.setVerticesBuffer(buffer);
  28152. return this;
  28153. };
  28154. /**
  28155. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28156. * If the mesh has no geometry, it is simply returned as it is.
  28157. * The `data` are either a numeric array either a Float32Array.
  28158. * No new underlying VertexBuffer object is created.
  28159. * 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.
  28160. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28161. *
  28162. * Possible `kind` values :
  28163. * - BABYLON.VertexBuffer.PositionKind
  28164. * - BABYLON.VertexBuffer.UVKind
  28165. * - BABYLON.VertexBuffer.UV2Kind
  28166. * - BABYLON.VertexBuffer.UV3Kind
  28167. * - BABYLON.VertexBuffer.UV4Kind
  28168. * - BABYLON.VertexBuffer.UV5Kind
  28169. * - BABYLON.VertexBuffer.UV6Kind
  28170. * - BABYLON.VertexBuffer.ColorKind
  28171. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28172. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28173. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28174. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28175. *
  28176. * Returns the Mesh.
  28177. */
  28178. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28179. if (!this._geometry) {
  28180. return this;
  28181. }
  28182. if (!makeItUnique) {
  28183. this._geometry.updateVerticesData(kind, data, updateExtends);
  28184. }
  28185. else {
  28186. this.makeGeometryUnique();
  28187. this.updateVerticesData(kind, data, updateExtends, false);
  28188. }
  28189. return this;
  28190. };
  28191. /**
  28192. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28193. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28194. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28195. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28196. * Returns the Mesh.
  28197. */
  28198. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28199. if (computeNormals === void 0) { computeNormals = true; }
  28200. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28201. if (!positions) {
  28202. return this;
  28203. }
  28204. positionFunction(positions);
  28205. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28206. if (computeNormals) {
  28207. var indices = this.getIndices();
  28208. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28209. if (!normals) {
  28210. return this;
  28211. }
  28212. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28213. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28214. }
  28215. return this;
  28216. };
  28217. /**
  28218. * Creates a un-shared specific occurence of the geometry for the mesh.
  28219. * Returns the Mesh.
  28220. */
  28221. Mesh.prototype.makeGeometryUnique = function () {
  28222. if (!this._geometry) {
  28223. return this;
  28224. }
  28225. var oldGeometry = this._geometry;
  28226. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28227. oldGeometry.releaseForMesh(this, true);
  28228. geometry.applyToMesh(this);
  28229. return this;
  28230. };
  28231. /**
  28232. * Sets the mesh indices.
  28233. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28234. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28235. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28236. * This method creates a new index buffer each call.
  28237. * Returns the Mesh.
  28238. */
  28239. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28240. if (totalVertices === void 0) { totalVertices = null; }
  28241. if (updatable === void 0) { updatable = false; }
  28242. if (!this._geometry) {
  28243. var vertexData = new BABYLON.VertexData();
  28244. vertexData.indices = indices;
  28245. var scene = this.getScene();
  28246. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28247. }
  28248. else {
  28249. this._geometry.setIndices(indices, totalVertices, updatable);
  28250. }
  28251. return this;
  28252. };
  28253. /**
  28254. * Update the current index buffer
  28255. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28256. * Returns the Mesh.
  28257. */
  28258. Mesh.prototype.updateIndices = function (indices, offset) {
  28259. if (!this._geometry) {
  28260. return this;
  28261. }
  28262. this._geometry.updateIndices(indices, offset);
  28263. return this;
  28264. };
  28265. /**
  28266. * Invert the geometry to move from a right handed system to a left handed one.
  28267. * Returns the Mesh.
  28268. */
  28269. Mesh.prototype.toLeftHanded = function () {
  28270. if (!this._geometry) {
  28271. return this;
  28272. }
  28273. this._geometry.toLeftHanded();
  28274. return this;
  28275. };
  28276. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28277. if (!this._geometry) {
  28278. return this;
  28279. }
  28280. var engine = this.getScene().getEngine();
  28281. // Wireframe
  28282. var indexToBind;
  28283. if (this._unIndexed) {
  28284. indexToBind = null;
  28285. }
  28286. else {
  28287. switch (fillMode) {
  28288. case BABYLON.Material.PointFillMode:
  28289. indexToBind = null;
  28290. break;
  28291. case BABYLON.Material.WireFrameFillMode:
  28292. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28293. break;
  28294. default:
  28295. case BABYLON.Material.TriangleFillMode:
  28296. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28297. break;
  28298. }
  28299. }
  28300. // VBOs
  28301. this._geometry._bind(effect, indexToBind);
  28302. return this;
  28303. };
  28304. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28305. if (alternate === void 0) { alternate = false; }
  28306. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28307. return this;
  28308. }
  28309. this.onBeforeDrawObservable.notifyObservers(this);
  28310. var scene = this.getScene();
  28311. var engine = scene.getEngine();
  28312. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28313. // or triangles as points
  28314. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28315. }
  28316. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28317. // Triangles as wireframe
  28318. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28319. }
  28320. else {
  28321. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28322. }
  28323. if (scene._isAlternateRenderingEnabled && !alternate) {
  28324. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28325. if (!effect || !scene.activeCamera) {
  28326. return this;
  28327. }
  28328. scene._switchToAlternateCameraConfiguration(true);
  28329. this._effectiveMaterial.bindView(effect);
  28330. this._effectiveMaterial.bindViewProjection(effect);
  28331. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28332. this._draw(subMesh, fillMode, instancesCount, true);
  28333. engine.setViewport(scene.activeCamera.viewport);
  28334. scene._switchToAlternateCameraConfiguration(false);
  28335. this._effectiveMaterial.bindView(effect);
  28336. this._effectiveMaterial.bindViewProjection(effect);
  28337. }
  28338. return this;
  28339. };
  28340. /**
  28341. * Registers for this mesh a javascript function called just before the rendering process.
  28342. * This function is passed the current mesh.
  28343. * Return the Mesh.
  28344. */
  28345. Mesh.prototype.registerBeforeRender = function (func) {
  28346. this.onBeforeRenderObservable.add(func);
  28347. return this;
  28348. };
  28349. /**
  28350. * Disposes a previously registered javascript function called before the rendering.
  28351. * This function is passed the current mesh.
  28352. * Returns the Mesh.
  28353. */
  28354. Mesh.prototype.unregisterBeforeRender = function (func) {
  28355. this.onBeforeRenderObservable.removeCallback(func);
  28356. return this;
  28357. };
  28358. /**
  28359. * Registers for this mesh a javascript function called just after the rendering is complete.
  28360. * This function is passed the current mesh.
  28361. * Returns the Mesh.
  28362. */
  28363. Mesh.prototype.registerAfterRender = function (func) {
  28364. this.onAfterRenderObservable.add(func);
  28365. return this;
  28366. };
  28367. /**
  28368. * Disposes a previously registered javascript function called after the rendering.
  28369. * This function is passed the current mesh.
  28370. * Return the Mesh.
  28371. */
  28372. Mesh.prototype.unregisterAfterRender = function (func) {
  28373. this.onAfterRenderObservable.removeCallback(func);
  28374. return this;
  28375. };
  28376. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28377. var scene = this.getScene();
  28378. this._batchCache.mustReturn = false;
  28379. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28380. this._batchCache.visibleInstances[subMeshId] = null;
  28381. if (this._visibleInstances) {
  28382. var currentRenderId = scene.getRenderId();
  28383. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28384. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28385. var selfRenderId = this._renderId;
  28386. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28387. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28388. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28389. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28390. }
  28391. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28392. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28393. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28394. this._batchCache.mustReturn = true;
  28395. return this._batchCache;
  28396. }
  28397. if (currentRenderId !== selfRenderId) {
  28398. this._batchCache.renderSelf[subMeshId] = false;
  28399. }
  28400. }
  28401. this._renderIdForInstances[subMeshId] = currentRenderId;
  28402. }
  28403. return this._batchCache;
  28404. };
  28405. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28406. var visibleInstances = batch.visibleInstances[subMesh._id];
  28407. if (!visibleInstances) {
  28408. return this;
  28409. }
  28410. var matricesCount = visibleInstances.length + 1;
  28411. var bufferSize = matricesCount * 16 * 4;
  28412. var currentInstancesBufferSize = this._instancesBufferSize;
  28413. var instancesBuffer = this._instancesBuffer;
  28414. while (this._instancesBufferSize < bufferSize) {
  28415. this._instancesBufferSize *= 2;
  28416. }
  28417. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28418. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28419. }
  28420. var offset = 0;
  28421. var instancesCount = 0;
  28422. var world = this.getWorldMatrix();
  28423. if (batch.renderSelf[subMesh._id]) {
  28424. world.copyToArray(this._instancesData, offset);
  28425. offset += 16;
  28426. instancesCount++;
  28427. }
  28428. if (visibleInstances) {
  28429. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28430. var instance = visibleInstances[instanceIndex];
  28431. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28432. offset += 16;
  28433. instancesCount++;
  28434. }
  28435. }
  28436. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28437. if (instancesBuffer) {
  28438. instancesBuffer.dispose();
  28439. }
  28440. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28441. this._instancesBuffer = instancesBuffer;
  28442. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28443. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28444. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28445. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28446. }
  28447. else {
  28448. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28449. }
  28450. this._bind(subMesh, effect, fillMode);
  28451. this._draw(subMesh, fillMode, instancesCount);
  28452. engine.unbindInstanceAttributes();
  28453. return this;
  28454. };
  28455. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28456. var scene = this.getScene();
  28457. var engine = scene.getEngine();
  28458. if (hardwareInstancedRendering) {
  28459. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28460. }
  28461. else {
  28462. if (batch.renderSelf[subMesh._id]) {
  28463. // Draw
  28464. if (onBeforeDraw) {
  28465. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28466. }
  28467. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28468. }
  28469. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28470. if (visibleInstancesForSubMesh) {
  28471. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28472. var instance = visibleInstancesForSubMesh[instanceIndex];
  28473. // World
  28474. var world = instance.getWorldMatrix();
  28475. if (onBeforeDraw) {
  28476. onBeforeDraw(true, world, effectiveMaterial);
  28477. }
  28478. // Draw
  28479. this._draw(subMesh, fillMode);
  28480. }
  28481. }
  28482. }
  28483. return this;
  28484. };
  28485. /**
  28486. * Triggers the draw call for the mesh.
  28487. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28488. * Returns the Mesh.
  28489. */
  28490. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28491. this.checkOcclusionQuery();
  28492. if (this._isOccluded) {
  28493. return this;
  28494. }
  28495. var scene = this.getScene();
  28496. // Managing instances
  28497. var batch = this._getInstancesRenderList(subMesh._id);
  28498. if (batch.mustReturn) {
  28499. return this;
  28500. }
  28501. // Checking geometry state
  28502. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28503. return this;
  28504. }
  28505. this.onBeforeRenderObservable.notifyObservers(this);
  28506. var engine = scene.getEngine();
  28507. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28508. // Material
  28509. var material = subMesh.getMaterial();
  28510. if (!material) {
  28511. return this;
  28512. }
  28513. this._effectiveMaterial = material;
  28514. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28515. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28516. return this;
  28517. }
  28518. }
  28519. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28520. return this;
  28521. }
  28522. // Alpha mode
  28523. if (enableAlphaMode) {
  28524. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28525. }
  28526. // Outline - step 1
  28527. var savedDepthWrite = engine.getDepthWrite();
  28528. if (this.renderOutline) {
  28529. engine.setDepthWrite(false);
  28530. scene.getOutlineRenderer().render(subMesh, batch);
  28531. engine.setDepthWrite(savedDepthWrite);
  28532. }
  28533. var effect;
  28534. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28535. effect = subMesh.effect;
  28536. }
  28537. else {
  28538. effect = this._effectiveMaterial.getEffect();
  28539. }
  28540. if (!effect) {
  28541. return this;
  28542. }
  28543. var sideOrientation = this.overrideMaterialSideOrientation;
  28544. if (sideOrientation == null) {
  28545. sideOrientation = this._effectiveMaterial.sideOrientation;
  28546. if (this._getWorldMatrixDeterminant() < 0) {
  28547. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28548. }
  28549. }
  28550. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28551. if (this._effectiveMaterial.forceDepthWrite) {
  28552. engine.setDepthWrite(true);
  28553. }
  28554. // Bind
  28555. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28556. if (!hardwareInstancedRendering) {
  28557. this._bind(subMesh, effect, fillMode);
  28558. }
  28559. var world = this.getWorldMatrix();
  28560. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28561. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28562. }
  28563. else {
  28564. this._effectiveMaterial.bind(world, this);
  28565. }
  28566. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28567. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28568. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28569. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28570. }
  28571. // Draw
  28572. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28573. // Unbind
  28574. this._effectiveMaterial.unbind();
  28575. // Outline - step 2
  28576. if (this.renderOutline && savedDepthWrite) {
  28577. engine.setDepthWrite(true);
  28578. engine.setColorWrite(false);
  28579. scene.getOutlineRenderer().render(subMesh, batch);
  28580. engine.setColorWrite(true);
  28581. }
  28582. // Overlay
  28583. if (this.renderOverlay) {
  28584. var currentMode = engine.getAlphaMode();
  28585. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28586. scene.getOutlineRenderer().render(subMesh, batch, true);
  28587. engine.setAlphaMode(currentMode);
  28588. }
  28589. this.onAfterRenderObservable.notifyObservers(this);
  28590. return this;
  28591. };
  28592. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28593. if (isInstance && effectiveMaterial) {
  28594. effectiveMaterial.bindOnlyWorldMatrix(world);
  28595. }
  28596. };
  28597. /**
  28598. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28599. */
  28600. Mesh.prototype.getEmittedParticleSystems = function () {
  28601. var results = new Array();
  28602. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28603. var particleSystem = this.getScene().particleSystems[index];
  28604. if (particleSystem.emitter === this) {
  28605. results.push(particleSystem);
  28606. }
  28607. }
  28608. return results;
  28609. };
  28610. /**
  28611. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28612. */
  28613. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28614. var results = new Array();
  28615. var descendants = this.getDescendants();
  28616. descendants.push(this);
  28617. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28618. var particleSystem = this.getScene().particleSystems[index];
  28619. var emitter = particleSystem.emitter;
  28620. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28621. results.push(particleSystem);
  28622. }
  28623. }
  28624. return results;
  28625. };
  28626. Mesh.prototype._checkDelayState = function () {
  28627. var scene = this.getScene();
  28628. if (this._geometry) {
  28629. this._geometry.load(scene);
  28630. }
  28631. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28632. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28633. this._queueLoad(scene);
  28634. }
  28635. return this;
  28636. };
  28637. Mesh.prototype._queueLoad = function (scene) {
  28638. var _this = this;
  28639. scene._addPendingData(this);
  28640. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28641. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28642. if (data instanceof ArrayBuffer) {
  28643. _this._delayLoadingFunction(data, _this);
  28644. }
  28645. else {
  28646. _this._delayLoadingFunction(JSON.parse(data), _this);
  28647. }
  28648. _this.instances.forEach(function (instance) {
  28649. instance._syncSubMeshes();
  28650. });
  28651. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28652. scene._removePendingData(_this);
  28653. }, function () { }, scene.database, getBinaryData);
  28654. return this;
  28655. };
  28656. /**
  28657. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28658. */
  28659. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28660. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28661. return false;
  28662. }
  28663. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28664. return false;
  28665. }
  28666. this._checkDelayState();
  28667. return true;
  28668. };
  28669. /**
  28670. * Sets the mesh material by the material or multiMaterial `id` property.
  28671. * The material `id` is a string identifying the material or the multiMaterial.
  28672. * This method returns the Mesh.
  28673. */
  28674. Mesh.prototype.setMaterialByID = function (id) {
  28675. var materials = this.getScene().materials;
  28676. var index;
  28677. for (index = materials.length - 1; index > -1; index--) {
  28678. if (materials[index].id === id) {
  28679. this.material = materials[index];
  28680. return this;
  28681. }
  28682. }
  28683. // Multi
  28684. var multiMaterials = this.getScene().multiMaterials;
  28685. for (index = multiMaterials.length - 1; index > -1; index--) {
  28686. if (multiMaterials[index].id === id) {
  28687. this.material = multiMaterials[index];
  28688. return this;
  28689. }
  28690. }
  28691. return this;
  28692. };
  28693. /**
  28694. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28695. */
  28696. Mesh.prototype.getAnimatables = function () {
  28697. var results = new Array();
  28698. if (this.material) {
  28699. results.push(this.material);
  28700. }
  28701. if (this.skeleton) {
  28702. results.push(this.skeleton);
  28703. }
  28704. return results;
  28705. };
  28706. /**
  28707. * Modifies the mesh geometry according to the passed transformation matrix.
  28708. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28709. * The mesh normals are modified accordingly the same transformation.
  28710. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28711. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28712. * Returns the Mesh.
  28713. */
  28714. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28715. // Position
  28716. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28717. return this;
  28718. }
  28719. var submeshes = this.subMeshes.splice(0);
  28720. this._resetPointsArrayCache();
  28721. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28722. var temp = new Array();
  28723. var index;
  28724. for (index = 0; index < data.length; index += 3) {
  28725. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28726. }
  28727. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28728. // Normals
  28729. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28730. return this;
  28731. }
  28732. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28733. temp = [];
  28734. for (index = 0; index < data.length; index += 3) {
  28735. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28736. }
  28737. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28738. // flip faces?
  28739. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28740. this.flipFaces();
  28741. }
  28742. // Restore submeshes
  28743. this.releaseSubMeshes();
  28744. this.subMeshes = submeshes;
  28745. return this;
  28746. };
  28747. /**
  28748. * Modifies the mesh geometry according to its own current World Matrix.
  28749. * The mesh World Matrix is then reset.
  28750. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28751. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28752. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28753. * Returns the Mesh.
  28754. */
  28755. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28756. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28757. this.scaling.copyFromFloats(1, 1, 1);
  28758. this.position.copyFromFloats(0, 0, 0);
  28759. this.rotation.copyFromFloats(0, 0, 0);
  28760. //only if quaternion is already set
  28761. if (this.rotationQuaternion) {
  28762. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28763. }
  28764. this._worldMatrix = BABYLON.Matrix.Identity();
  28765. return this;
  28766. };
  28767. Object.defineProperty(Mesh.prototype, "_positions", {
  28768. // Cache
  28769. get: function () {
  28770. if (this._geometry) {
  28771. return this._geometry._positions;
  28772. }
  28773. return null;
  28774. },
  28775. enumerable: true,
  28776. configurable: true
  28777. });
  28778. Mesh.prototype._resetPointsArrayCache = function () {
  28779. if (this._geometry) {
  28780. this._geometry._resetPointsArrayCache();
  28781. }
  28782. return this;
  28783. };
  28784. Mesh.prototype._generatePointsArray = function () {
  28785. if (this._geometry) {
  28786. return this._geometry._generatePointsArray();
  28787. }
  28788. return false;
  28789. };
  28790. /**
  28791. * Returns a new Mesh object generated from the current mesh properties.
  28792. * This method must not get confused with createInstance().
  28793. * The parameter `name` is a string, the name given to the new mesh.
  28794. * The optional parameter `newParent` can be any Node object (default `null`).
  28795. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28796. * 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.
  28797. */
  28798. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28799. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28800. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28801. };
  28802. /**
  28803. * Disposes the Mesh.
  28804. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28805. * Returns nothing.
  28806. */
  28807. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28808. var _this = this;
  28809. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28810. this.morphTargetManager = null;
  28811. if (this._geometry) {
  28812. this._geometry.releaseForMesh(this, true);
  28813. }
  28814. // Sources
  28815. var meshes = this.getScene().meshes;
  28816. meshes.forEach(function (abstractMesh) {
  28817. var mesh = abstractMesh;
  28818. if (mesh._source && mesh._source === _this) {
  28819. mesh._source = null;
  28820. }
  28821. });
  28822. this._source = null;
  28823. // Instances
  28824. if (this._instancesBuffer) {
  28825. this._instancesBuffer.dispose();
  28826. this._instancesBuffer = null;
  28827. }
  28828. while (this.instances.length) {
  28829. this.instances[0].dispose();
  28830. }
  28831. // Effect layers.
  28832. var effectLayers = this.getScene().effectLayers;
  28833. for (var i = 0; i < effectLayers.length; i++) {
  28834. var effectLayer = effectLayers[i];
  28835. if (effectLayer) {
  28836. effectLayer._disposeMesh(this);
  28837. }
  28838. }
  28839. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28840. };
  28841. /**
  28842. * Modifies the mesh geometry according to a displacement map.
  28843. * 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.
  28844. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28845. * This method returns nothing.
  28846. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28847. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28848. * 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.
  28849. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28850. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28851. *
  28852. * Returns the Mesh.
  28853. */
  28854. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28855. var _this = this;
  28856. var scene = this.getScene();
  28857. var onload = function (img) {
  28858. // Getting height map data
  28859. var canvas = document.createElement("canvas");
  28860. var context = canvas.getContext("2d");
  28861. var heightMapWidth = img.width;
  28862. var heightMapHeight = img.height;
  28863. canvas.width = heightMapWidth;
  28864. canvas.height = heightMapHeight;
  28865. context.drawImage(img, 0, 0);
  28866. // Create VertexData from map data
  28867. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28868. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28869. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28870. //execute success callback, if set
  28871. if (onSuccess) {
  28872. onSuccess(_this);
  28873. }
  28874. };
  28875. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28876. return this;
  28877. };
  28878. /**
  28879. * Modifies the mesh geometry according to a displacementMap buffer.
  28880. * 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.
  28881. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28882. * This method returns nothing.
  28883. * 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.
  28884. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28885. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28886. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28887. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28888. *
  28889. * Returns the Mesh.
  28890. */
  28891. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28892. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28893. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28894. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28895. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28896. return this;
  28897. }
  28898. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28899. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28900. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28901. var position = BABYLON.Vector3.Zero();
  28902. var normal = BABYLON.Vector3.Zero();
  28903. var uv = BABYLON.Vector2.Zero();
  28904. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28905. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28906. for (var index = 0; index < positions.length; index += 3) {
  28907. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28908. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28909. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28910. // Compute height
  28911. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28912. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28913. var pos = (u + v * heightMapWidth) * 4;
  28914. var r = buffer[pos] / 255.0;
  28915. var g = buffer[pos + 1] / 255.0;
  28916. var b = buffer[pos + 2] / 255.0;
  28917. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28918. normal.normalize();
  28919. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28920. position = position.add(normal);
  28921. position.toArray(positions, index);
  28922. }
  28923. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28924. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28925. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28926. return this;
  28927. };
  28928. /**
  28929. * Modify the mesh to get a flat shading rendering.
  28930. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28931. * This method returns the Mesh.
  28932. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28933. */
  28934. Mesh.prototype.convertToFlatShadedMesh = function () {
  28935. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28936. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28937. var kinds = this.getVerticesDataKinds();
  28938. var vbs = {};
  28939. var data = {};
  28940. var newdata = {};
  28941. var updatableNormals = false;
  28942. var kindIndex;
  28943. var kind;
  28944. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28945. kind = kinds[kindIndex];
  28946. var vertexBuffer = this.getVertexBuffer(kind);
  28947. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28948. updatableNormals = vertexBuffer.isUpdatable();
  28949. kinds.splice(kindIndex, 1);
  28950. kindIndex--;
  28951. continue;
  28952. }
  28953. vbs[kind] = vertexBuffer;
  28954. data[kind] = vbs[kind].getData();
  28955. newdata[kind] = [];
  28956. }
  28957. // Save previous submeshes
  28958. var previousSubmeshes = this.subMeshes.slice(0);
  28959. var indices = this.getIndices();
  28960. var totalIndices = this.getTotalIndices();
  28961. // Generating unique vertices per face
  28962. var index;
  28963. for (index = 0; index < totalIndices; index++) {
  28964. var vertexIndex = indices[index];
  28965. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28966. kind = kinds[kindIndex];
  28967. var stride = vbs[kind].getStrideSize();
  28968. for (var offset = 0; offset < stride; offset++) {
  28969. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28970. }
  28971. }
  28972. }
  28973. // Updating faces & normal
  28974. var normals = [];
  28975. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28976. for (index = 0; index < totalIndices; index += 3) {
  28977. indices[index] = index;
  28978. indices[index + 1] = index + 1;
  28979. indices[index + 2] = index + 2;
  28980. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28981. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28982. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28983. var p1p2 = p1.subtract(p2);
  28984. var p3p2 = p3.subtract(p2);
  28985. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28986. // Store same normals for every vertex
  28987. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28988. normals.push(normal.x);
  28989. normals.push(normal.y);
  28990. normals.push(normal.z);
  28991. }
  28992. }
  28993. this.setIndices(indices);
  28994. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28995. // Updating vertex buffers
  28996. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28997. kind = kinds[kindIndex];
  28998. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28999. }
  29000. // Updating submeshes
  29001. this.releaseSubMeshes();
  29002. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29003. var previousOne = previousSubmeshes[submeshIndex];
  29004. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29005. }
  29006. this.synchronizeInstances();
  29007. return this;
  29008. };
  29009. /**
  29010. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29011. * In other words, more vertices, no more indices and a single bigger VBO.
  29012. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29013. * Returns the Mesh.
  29014. */
  29015. Mesh.prototype.convertToUnIndexedMesh = function () {
  29016. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29017. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29018. var kinds = this.getVerticesDataKinds();
  29019. var vbs = {};
  29020. var data = {};
  29021. var newdata = {};
  29022. var kindIndex;
  29023. var kind;
  29024. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29025. kind = kinds[kindIndex];
  29026. var vertexBuffer = this.getVertexBuffer(kind);
  29027. vbs[kind] = vertexBuffer;
  29028. data[kind] = vbs[kind].getData();
  29029. newdata[kind] = [];
  29030. }
  29031. // Save previous submeshes
  29032. var previousSubmeshes = this.subMeshes.slice(0);
  29033. var indices = this.getIndices();
  29034. var totalIndices = this.getTotalIndices();
  29035. // Generating unique vertices per face
  29036. var index;
  29037. for (index = 0; index < totalIndices; index++) {
  29038. var vertexIndex = indices[index];
  29039. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29040. kind = kinds[kindIndex];
  29041. var stride = vbs[kind].getStrideSize();
  29042. for (var offset = 0; offset < stride; offset++) {
  29043. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29044. }
  29045. }
  29046. }
  29047. // Updating indices
  29048. for (index = 0; index < totalIndices; index += 3) {
  29049. indices[index] = index;
  29050. indices[index + 1] = index + 1;
  29051. indices[index + 2] = index + 2;
  29052. }
  29053. this.setIndices(indices);
  29054. // Updating vertex buffers
  29055. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29056. kind = kinds[kindIndex];
  29057. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29058. }
  29059. // Updating submeshes
  29060. this.releaseSubMeshes();
  29061. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29062. var previousOne = previousSubmeshes[submeshIndex];
  29063. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29064. }
  29065. this._unIndexed = true;
  29066. this.synchronizeInstances();
  29067. return this;
  29068. };
  29069. /**
  29070. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29071. * This method returns the Mesh.
  29072. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29073. */
  29074. Mesh.prototype.flipFaces = function (flipNormals) {
  29075. if (flipNormals === void 0) { flipNormals = false; }
  29076. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29077. var i;
  29078. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29079. for (i = 0; i < vertex_data.normals.length; i++) {
  29080. vertex_data.normals[i] *= -1;
  29081. }
  29082. }
  29083. if (vertex_data.indices) {
  29084. var temp;
  29085. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29086. // reassign indices
  29087. temp = vertex_data.indices[i + 1];
  29088. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29089. vertex_data.indices[i + 2] = temp;
  29090. }
  29091. }
  29092. vertex_data.applyToMesh(this);
  29093. return this;
  29094. };
  29095. // Instances
  29096. /**
  29097. * Creates a new InstancedMesh object from the mesh model.
  29098. * An instance shares the same properties and the same material than its model.
  29099. * Only these properties of each instance can then be set individually :
  29100. * - position
  29101. * - rotation
  29102. * - rotationQuaternion
  29103. * - setPivotMatrix
  29104. * - scaling
  29105. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29106. * Warning : this method is not supported for Line mesh and LineSystem
  29107. */
  29108. Mesh.prototype.createInstance = function (name) {
  29109. return new BABYLON.InstancedMesh(name, this);
  29110. };
  29111. /**
  29112. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29113. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29114. * This method returns the Mesh.
  29115. */
  29116. Mesh.prototype.synchronizeInstances = function () {
  29117. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29118. var instance = this.instances[instanceIndex];
  29119. instance._syncSubMeshes();
  29120. }
  29121. return this;
  29122. };
  29123. /**
  29124. * Simplify the mesh according to the given array of settings.
  29125. * Function will return immediately and will simplify async. It returns the Mesh.
  29126. * @param settings a collection of simplification settings.
  29127. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29128. * @param type the type of simplification to run.
  29129. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29130. */
  29131. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29132. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29133. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29134. this.getScene().simplificationQueue.addTask({
  29135. settings: settings,
  29136. parallelProcessing: parallelProcessing,
  29137. mesh: this,
  29138. simplificationType: simplificationType,
  29139. successCallback: successCallback
  29140. });
  29141. return this;
  29142. };
  29143. /**
  29144. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29145. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29146. * This should be used together with the simplification to avoid disappearing triangles.
  29147. * Returns the Mesh.
  29148. * @param successCallback an optional success callback to be called after the optimization finished.
  29149. */
  29150. Mesh.prototype.optimizeIndices = function (successCallback) {
  29151. var _this = this;
  29152. var indices = this.getIndices();
  29153. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29154. if (!positions || !indices) {
  29155. return this;
  29156. }
  29157. var vectorPositions = new Array();
  29158. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29159. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29160. }
  29161. var dupes = new Array();
  29162. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29163. var realPos = vectorPositions.length - 1 - iteration;
  29164. var testedPosition = vectorPositions[realPos];
  29165. for (var j = 0; j < realPos; ++j) {
  29166. var againstPosition = vectorPositions[j];
  29167. if (testedPosition.equals(againstPosition)) {
  29168. dupes[realPos] = j;
  29169. break;
  29170. }
  29171. }
  29172. }, function () {
  29173. for (var i = 0; i < indices.length; ++i) {
  29174. indices[i] = dupes[indices[i]] || indices[i];
  29175. }
  29176. //indices are now reordered
  29177. var originalSubMeshes = _this.subMeshes.slice(0);
  29178. _this.setIndices(indices);
  29179. _this.subMeshes = originalSubMeshes;
  29180. if (successCallback) {
  29181. successCallback(_this);
  29182. }
  29183. });
  29184. return this;
  29185. };
  29186. Mesh.prototype.serialize = function (serializationObject) {
  29187. serializationObject.name = this.name;
  29188. serializationObject.id = this.id;
  29189. serializationObject.type = this.getClassName();
  29190. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29191. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29192. }
  29193. serializationObject.position = this.position.asArray();
  29194. if (this.rotationQuaternion) {
  29195. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29196. }
  29197. else if (this.rotation) {
  29198. serializationObject.rotation = this.rotation.asArray();
  29199. }
  29200. serializationObject.scaling = this.scaling.asArray();
  29201. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29202. serializationObject.isEnabled = this.isEnabled(false);
  29203. serializationObject.isVisible = this.isVisible;
  29204. serializationObject.infiniteDistance = this.infiniteDistance;
  29205. serializationObject.pickable = this.isPickable;
  29206. serializationObject.receiveShadows = this.receiveShadows;
  29207. serializationObject.billboardMode = this.billboardMode;
  29208. serializationObject.visibility = this.visibility;
  29209. serializationObject.checkCollisions = this.checkCollisions;
  29210. serializationObject.isBlocker = this.isBlocker;
  29211. // Parent
  29212. if (this.parent) {
  29213. serializationObject.parentId = this.parent.id;
  29214. }
  29215. // Geometry
  29216. serializationObject.isUnIndexed = this.isUnIndexed;
  29217. var geometry = this._geometry;
  29218. if (geometry) {
  29219. var geometryId = geometry.id;
  29220. serializationObject.geometryId = geometryId;
  29221. // SubMeshes
  29222. serializationObject.subMeshes = [];
  29223. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29224. var subMesh = this.subMeshes[subIndex];
  29225. serializationObject.subMeshes.push({
  29226. materialIndex: subMesh.materialIndex,
  29227. verticesStart: subMesh.verticesStart,
  29228. verticesCount: subMesh.verticesCount,
  29229. indexStart: subMesh.indexStart,
  29230. indexCount: subMesh.indexCount
  29231. });
  29232. }
  29233. }
  29234. // Material
  29235. if (this.material) {
  29236. serializationObject.materialId = this.material.id;
  29237. }
  29238. else {
  29239. this.material = null;
  29240. }
  29241. // Morph targets
  29242. if (this.morphTargetManager) {
  29243. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29244. }
  29245. // Skeleton
  29246. if (this.skeleton) {
  29247. serializationObject.skeletonId = this.skeleton.id;
  29248. }
  29249. // Physics
  29250. //TODO implement correct serialization for physics impostors.
  29251. var impostor = this.getPhysicsImpostor();
  29252. if (impostor) {
  29253. serializationObject.physicsMass = impostor.getParam("mass");
  29254. serializationObject.physicsFriction = impostor.getParam("friction");
  29255. serializationObject.physicsRestitution = impostor.getParam("mass");
  29256. serializationObject.physicsImpostor = impostor.type;
  29257. }
  29258. // Metadata
  29259. if (this.metadata) {
  29260. serializationObject.metadata = this.metadata;
  29261. }
  29262. // Instances
  29263. serializationObject.instances = [];
  29264. for (var index = 0; index < this.instances.length; index++) {
  29265. var instance = this.instances[index];
  29266. var serializationInstance = {
  29267. name: instance.name,
  29268. id: instance.id,
  29269. position: instance.position.asArray(),
  29270. scaling: instance.scaling.asArray()
  29271. };
  29272. if (instance.rotationQuaternion) {
  29273. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29274. }
  29275. else if (instance.rotation) {
  29276. serializationInstance.rotation = instance.rotation.asArray();
  29277. }
  29278. serializationObject.instances.push(serializationInstance);
  29279. // Animations
  29280. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29281. serializationInstance.ranges = instance.serializeAnimationRanges();
  29282. }
  29283. //
  29284. // Animations
  29285. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29286. serializationObject.ranges = this.serializeAnimationRanges();
  29287. // Layer mask
  29288. serializationObject.layerMask = this.layerMask;
  29289. // Alpha
  29290. serializationObject.alphaIndex = this.alphaIndex;
  29291. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29292. // Overlay
  29293. serializationObject.overlayAlpha = this.overlayAlpha;
  29294. serializationObject.overlayColor = this.overlayColor.asArray();
  29295. serializationObject.renderOverlay = this.renderOverlay;
  29296. // Fog
  29297. serializationObject.applyFog = this.applyFog;
  29298. // Action Manager
  29299. if (this.actionManager) {
  29300. serializationObject.actions = this.actionManager.serialize(this.name);
  29301. }
  29302. };
  29303. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29304. if (!this.geometry) {
  29305. return;
  29306. }
  29307. this._markSubMeshesAsAttributesDirty();
  29308. var morphTargetManager = this._morphTargetManager;
  29309. if (morphTargetManager && morphTargetManager.vertexCount) {
  29310. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29311. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29312. this.morphTargetManager = null;
  29313. return;
  29314. }
  29315. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29316. var morphTarget = morphTargetManager.getActiveTarget(index);
  29317. var positions = morphTarget.getPositions();
  29318. if (!positions) {
  29319. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29320. return;
  29321. }
  29322. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29323. var normals = morphTarget.getNormals();
  29324. if (normals) {
  29325. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29326. }
  29327. var tangents = morphTarget.getTangents();
  29328. if (tangents) {
  29329. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29330. }
  29331. }
  29332. }
  29333. else {
  29334. var index = 0;
  29335. // Positions
  29336. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29337. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29338. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29339. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29340. }
  29341. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29342. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29343. }
  29344. index++;
  29345. }
  29346. }
  29347. };
  29348. // Statics
  29349. /**
  29350. * Returns a new Mesh object parsed from the source provided.
  29351. * The parameter `parsedMesh` is the source.
  29352. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29353. */
  29354. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29355. var mesh;
  29356. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29357. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29358. }
  29359. else {
  29360. mesh = new Mesh(parsedMesh.name, scene);
  29361. }
  29362. mesh.id = parsedMesh.id;
  29363. if (BABYLON.Tags) {
  29364. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29365. }
  29366. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29367. if (parsedMesh.metadata !== undefined) {
  29368. mesh.metadata = parsedMesh.metadata;
  29369. }
  29370. if (parsedMesh.rotationQuaternion) {
  29371. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29372. }
  29373. else if (parsedMesh.rotation) {
  29374. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29375. }
  29376. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29377. if (parsedMesh.localMatrix) {
  29378. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29379. }
  29380. else if (parsedMesh.pivotMatrix) {
  29381. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29382. }
  29383. mesh.setEnabled(parsedMesh.isEnabled);
  29384. mesh.isVisible = parsedMesh.isVisible;
  29385. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29386. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29387. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29388. if (parsedMesh.applyFog !== undefined) {
  29389. mesh.applyFog = parsedMesh.applyFog;
  29390. }
  29391. if (parsedMesh.pickable !== undefined) {
  29392. mesh.isPickable = parsedMesh.pickable;
  29393. }
  29394. if (parsedMesh.alphaIndex !== undefined) {
  29395. mesh.alphaIndex = parsedMesh.alphaIndex;
  29396. }
  29397. mesh.receiveShadows = parsedMesh.receiveShadows;
  29398. mesh.billboardMode = parsedMesh.billboardMode;
  29399. if (parsedMesh.visibility !== undefined) {
  29400. mesh.visibility = parsedMesh.visibility;
  29401. }
  29402. mesh.checkCollisions = parsedMesh.checkCollisions;
  29403. if (parsedMesh.isBlocker !== undefined) {
  29404. mesh.isBlocker = parsedMesh.isBlocker;
  29405. }
  29406. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29407. // freezeWorldMatrix
  29408. if (parsedMesh.freezeWorldMatrix) {
  29409. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29410. }
  29411. // Parent
  29412. if (parsedMesh.parentId) {
  29413. mesh._waitingParentId = parsedMesh.parentId;
  29414. }
  29415. // Actions
  29416. if (parsedMesh.actions !== undefined) {
  29417. mesh._waitingActions = parsedMesh.actions;
  29418. }
  29419. // Overlay
  29420. if (parsedMesh.overlayAlpha !== undefined) {
  29421. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29422. }
  29423. if (parsedMesh.overlayColor !== undefined) {
  29424. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29425. }
  29426. if (parsedMesh.renderOverlay !== undefined) {
  29427. mesh.renderOverlay = parsedMesh.renderOverlay;
  29428. }
  29429. // Geometry
  29430. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29431. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29432. if (parsedMesh.delayLoadingFile) {
  29433. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29434. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29435. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29436. if (parsedMesh._binaryInfo) {
  29437. mesh._binaryInfo = parsedMesh._binaryInfo;
  29438. }
  29439. mesh._delayInfo = [];
  29440. if (parsedMesh.hasUVs) {
  29441. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29442. }
  29443. if (parsedMesh.hasUVs2) {
  29444. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29445. }
  29446. if (parsedMesh.hasUVs3) {
  29447. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29448. }
  29449. if (parsedMesh.hasUVs4) {
  29450. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29451. }
  29452. if (parsedMesh.hasUVs5) {
  29453. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29454. }
  29455. if (parsedMesh.hasUVs6) {
  29456. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29457. }
  29458. if (parsedMesh.hasColors) {
  29459. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29460. }
  29461. if (parsedMesh.hasMatricesIndices) {
  29462. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29463. }
  29464. if (parsedMesh.hasMatricesWeights) {
  29465. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29466. }
  29467. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29468. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29469. mesh._checkDelayState();
  29470. }
  29471. }
  29472. else {
  29473. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29474. }
  29475. // Material
  29476. if (parsedMesh.materialId) {
  29477. mesh.setMaterialByID(parsedMesh.materialId);
  29478. }
  29479. else {
  29480. mesh.material = null;
  29481. }
  29482. // Morph targets
  29483. if (parsedMesh.morphTargetManagerId > -1) {
  29484. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29485. }
  29486. // Skeleton
  29487. if (parsedMesh.skeletonId > -1) {
  29488. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29489. if (parsedMesh.numBoneInfluencers) {
  29490. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29491. }
  29492. }
  29493. // Animations
  29494. if (parsedMesh.animations) {
  29495. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29496. var parsedAnimation = parsedMesh.animations[animationIndex];
  29497. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29498. }
  29499. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29500. }
  29501. if (parsedMesh.autoAnimate) {
  29502. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29503. }
  29504. // Layer Mask
  29505. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29506. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29507. }
  29508. else {
  29509. mesh.layerMask = 0x0FFFFFFF;
  29510. }
  29511. // Physics
  29512. if (parsedMesh.physicsImpostor) {
  29513. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29514. mass: parsedMesh.physicsMass,
  29515. friction: parsedMesh.physicsFriction,
  29516. restitution: parsedMesh.physicsRestitution
  29517. }, scene);
  29518. }
  29519. // Instances
  29520. if (parsedMesh.instances) {
  29521. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29522. var parsedInstance = parsedMesh.instances[index];
  29523. var instance = mesh.createInstance(parsedInstance.name);
  29524. if (parsedInstance.id) {
  29525. instance.id = parsedInstance.id;
  29526. }
  29527. if (BABYLON.Tags) {
  29528. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29529. }
  29530. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29531. if (parsedInstance.parentId) {
  29532. instance._waitingParentId = parsedInstance.parentId;
  29533. }
  29534. if (parsedInstance.rotationQuaternion) {
  29535. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29536. }
  29537. else if (parsedInstance.rotation) {
  29538. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29539. }
  29540. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29541. instance.checkCollisions = mesh.checkCollisions;
  29542. if (parsedMesh.animations) {
  29543. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29544. parsedAnimation = parsedMesh.animations[animationIndex];
  29545. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29546. }
  29547. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29548. }
  29549. }
  29550. }
  29551. return mesh;
  29552. };
  29553. /**
  29554. * Creates a ribbon mesh.
  29555. * Please consider using the same method from the MeshBuilder class instead.
  29556. * 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.
  29557. *
  29558. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29559. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29560. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29561. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29562. * 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.
  29563. * 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.
  29564. * 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
  29565. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29566. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29567. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29568. */
  29569. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29570. if (closeArray === void 0) { closeArray = false; }
  29571. if (updatable === void 0) { updatable = false; }
  29572. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29573. pathArray: pathArray,
  29574. closeArray: closeArray,
  29575. closePath: closePath,
  29576. offset: offset,
  29577. updatable: updatable,
  29578. sideOrientation: sideOrientation,
  29579. instance: instance
  29580. }, scene);
  29581. };
  29582. /**
  29583. * Creates a plane polygonal mesh. By default, this is a disc.
  29584. * Please consider using the same method from the MeshBuilder class instead.
  29585. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29586. * 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.
  29587. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29588. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29589. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29590. */
  29591. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29592. if (scene === void 0) { scene = null; }
  29593. var options = {
  29594. radius: radius,
  29595. tessellation: tessellation,
  29596. sideOrientation: sideOrientation,
  29597. updatable: updatable
  29598. };
  29599. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29600. };
  29601. /**
  29602. * Creates a box mesh.
  29603. * Please consider using the same method from the MeshBuilder class instead.
  29604. * The parameter `size` sets the size (float) of each box side (default 1).
  29605. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29606. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29607. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29608. */
  29609. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29610. if (scene === void 0) { scene = null; }
  29611. var options = {
  29612. size: size,
  29613. sideOrientation: sideOrientation,
  29614. updatable: updatable
  29615. };
  29616. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29617. };
  29618. /**
  29619. * Creates a sphere mesh.
  29620. * Please consider using the same method from the MeshBuilder class instead.
  29621. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29622. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29624. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29625. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29626. */
  29627. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29628. var options = {
  29629. segments: segments,
  29630. diameterX: diameter,
  29631. diameterY: diameter,
  29632. diameterZ: diameter,
  29633. sideOrientation: sideOrientation,
  29634. updatable: updatable
  29635. };
  29636. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29637. };
  29638. /**
  29639. * Creates a cylinder or a cone mesh.
  29640. * Please consider using the same method from the MeshBuilder class instead.
  29641. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29642. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29643. * 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.
  29644. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29645. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29646. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29647. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29648. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29649. */
  29650. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29651. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29652. if (scene !== undefined) {
  29653. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29654. updatable = scene;
  29655. }
  29656. scene = subdivisions;
  29657. subdivisions = 1;
  29658. }
  29659. var options = {
  29660. height: height,
  29661. diameterTop: diameterTop,
  29662. diameterBottom: diameterBottom,
  29663. tessellation: tessellation,
  29664. subdivisions: subdivisions,
  29665. sideOrientation: sideOrientation,
  29666. updatable: updatable
  29667. };
  29668. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29669. };
  29670. // Torus (Code from SharpDX.org)
  29671. /**
  29672. * Creates a torus mesh.
  29673. * Please consider using the same method from the MeshBuilder class instead.
  29674. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29675. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29676. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29677. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29678. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29679. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29680. */
  29681. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29682. var options = {
  29683. diameter: diameter,
  29684. thickness: thickness,
  29685. tessellation: tessellation,
  29686. sideOrientation: sideOrientation,
  29687. updatable: updatable
  29688. };
  29689. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29690. };
  29691. /**
  29692. * Creates a torus knot mesh.
  29693. * Please consider using the same method from the MeshBuilder class instead.
  29694. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29695. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29696. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29697. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29698. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29699. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29700. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29701. */
  29702. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29703. var options = {
  29704. radius: radius,
  29705. tube: tube,
  29706. radialSegments: radialSegments,
  29707. tubularSegments: tubularSegments,
  29708. p: p,
  29709. q: q,
  29710. sideOrientation: sideOrientation,
  29711. updatable: updatable
  29712. };
  29713. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29714. };
  29715. /**
  29716. * Creates a line mesh.
  29717. * Please consider using the same method from the MeshBuilder class instead.
  29718. * 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.
  29719. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29720. * The parameter `points` is an array successive Vector3.
  29721. * 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
  29722. * When updating an instance, remember that only point positions can change, not the number of points.
  29723. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29724. */
  29725. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29726. if (scene === void 0) { scene = null; }
  29727. if (updatable === void 0) { updatable = false; }
  29728. if (instance === void 0) { instance = null; }
  29729. var options = {
  29730. points: points,
  29731. updatable: updatable,
  29732. instance: instance
  29733. };
  29734. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29735. };
  29736. /**
  29737. * Creates a dashed line mesh.
  29738. * Please consider using the same method from the MeshBuilder class instead.
  29739. * 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.
  29740. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29741. * The parameter `points` is an array successive Vector3.
  29742. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29743. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29744. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29745. * 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
  29746. * When updating an instance, remember that only point positions can change, not the number of points.
  29747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29748. */
  29749. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29750. if (scene === void 0) { scene = null; }
  29751. var options = {
  29752. points: points,
  29753. dashSize: dashSize,
  29754. gapSize: gapSize,
  29755. dashNb: dashNb,
  29756. updatable: updatable,
  29757. instance: instance
  29758. };
  29759. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29760. };
  29761. /**
  29762. * Creates a polygon mesh.
  29763. * Please consider using the same method from the MeshBuilder class instead.
  29764. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29765. * 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.
  29766. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29767. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29768. * Remember you can only change the shape positions, not their number when updating a polygon.
  29769. */
  29770. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29771. var options = {
  29772. shape: shape,
  29773. holes: holes,
  29774. updatable: updatable,
  29775. sideOrientation: sideOrientation
  29776. };
  29777. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29778. };
  29779. /**
  29780. * Creates an extruded polygon mesh, with depth in the Y direction.
  29781. * Please consider using the same method from the MeshBuilder class instead.
  29782. */
  29783. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29784. var options = {
  29785. shape: shape,
  29786. holes: holes,
  29787. depth: depth,
  29788. updatable: updatable,
  29789. sideOrientation: sideOrientation
  29790. };
  29791. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29792. };
  29793. /**
  29794. * Creates an extruded shape mesh.
  29795. * 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.
  29796. * Please consider using the same method from the MeshBuilder class instead.
  29797. *
  29798. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29799. * 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
  29800. * extruded along the Z axis.
  29801. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29802. * 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.
  29803. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29804. * 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
  29805. * 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
  29806. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29808. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29810. */
  29811. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29812. if (scene === void 0) { scene = null; }
  29813. var options = {
  29814. shape: shape,
  29815. path: path,
  29816. scale: scale,
  29817. rotation: rotation,
  29818. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29819. sideOrientation: sideOrientation,
  29820. instance: instance,
  29821. updatable: updatable
  29822. };
  29823. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29824. };
  29825. /**
  29826. * Creates an custom extruded shape mesh.
  29827. * 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.
  29828. * Please consider using the same method from the MeshBuilder class instead.
  29829. *
  29830. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29831. * 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
  29832. * extruded along the Z axis.
  29833. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29834. * 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
  29835. * and the distance of this point from the begining of the path :
  29836. * ```javascript
  29837. * var rotationFunction = function(i, distance) {
  29838. * // do things
  29839. * return rotationValue; }
  29840. * ```
  29841. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29842. * 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
  29843. * and the distance of this point from the begining of the path :
  29844. * ```javascript
  29845. * var scaleFunction = function(i, distance) {
  29846. * // do things
  29847. * return scaleValue;}
  29848. * ```
  29849. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29850. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29851. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29852. * 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
  29853. * 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
  29854. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29855. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29856. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29857. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29858. */
  29859. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29860. var options = {
  29861. shape: shape,
  29862. path: path,
  29863. scaleFunction: scaleFunction,
  29864. rotationFunction: rotationFunction,
  29865. ribbonCloseArray: ribbonCloseArray,
  29866. ribbonClosePath: ribbonClosePath,
  29867. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29868. sideOrientation: sideOrientation,
  29869. instance: instance,
  29870. updatable: updatable
  29871. };
  29872. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29873. };
  29874. /**
  29875. * Creates lathe mesh.
  29876. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29877. * Please consider using the same method from the MeshBuilder class instead.
  29878. * 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
  29879. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29880. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29881. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29882. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29883. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29885. */
  29886. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29887. var options = {
  29888. shape: shape,
  29889. radius: radius,
  29890. tessellation: tessellation,
  29891. sideOrientation: sideOrientation,
  29892. updatable: updatable
  29893. };
  29894. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29895. };
  29896. /**
  29897. * Creates a plane mesh.
  29898. * Please consider using the same method from the MeshBuilder class instead.
  29899. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29900. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29901. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29903. */
  29904. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29905. var options = {
  29906. size: size,
  29907. width: size,
  29908. height: size,
  29909. sideOrientation: sideOrientation,
  29910. updatable: updatable
  29911. };
  29912. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29913. };
  29914. /**
  29915. * Creates a ground mesh.
  29916. * Please consider using the same method from the MeshBuilder class instead.
  29917. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29918. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29920. */
  29921. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29922. var options = {
  29923. width: width,
  29924. height: height,
  29925. subdivisions: subdivisions,
  29926. updatable: updatable
  29927. };
  29928. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29929. };
  29930. /**
  29931. * Creates a tiled ground mesh.
  29932. * Please consider using the same method from the MeshBuilder class instead.
  29933. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29934. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29935. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29936. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29937. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29938. * numbers of subdivisions on the ground width and height of each tile.
  29939. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29940. */
  29941. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29942. var options = {
  29943. xmin: xmin,
  29944. zmin: zmin,
  29945. xmax: xmax,
  29946. zmax: zmax,
  29947. subdivisions: subdivisions,
  29948. precision: precision,
  29949. updatable: updatable
  29950. };
  29951. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29952. };
  29953. /**
  29954. * Creates a ground mesh from a height map.
  29955. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29956. * Please consider using the same method from the MeshBuilder class instead.
  29957. * The parameter `url` sets the URL of the height map image resource.
  29958. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29959. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29960. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29961. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29962. * 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).
  29963. * This function is passed the newly built mesh :
  29964. * ```javascript
  29965. * function(mesh) { // do things
  29966. * return; }
  29967. * ```
  29968. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29969. */
  29970. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29971. var options = {
  29972. width: width,
  29973. height: height,
  29974. subdivisions: subdivisions,
  29975. minHeight: minHeight,
  29976. maxHeight: maxHeight,
  29977. updatable: updatable,
  29978. onReady: onReady
  29979. };
  29980. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29981. };
  29982. /**
  29983. * Creates a tube mesh.
  29984. * 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.
  29985. * Please consider using the same method from the MeshBuilder class instead.
  29986. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29987. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29988. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29989. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29990. * 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.
  29991. * It must return a radius value (positive float) :
  29992. * ```javascript
  29993. * var radiusFunction = function(i, distance) {
  29994. * // do things
  29995. * return radius; }
  29996. * ```
  29997. * 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
  29998. * 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
  29999. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30000. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30002. */
  30003. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30004. var options = {
  30005. path: path,
  30006. radius: radius,
  30007. tessellation: tessellation,
  30008. radiusFunction: radiusFunction,
  30009. arc: 1,
  30010. cap: cap,
  30011. updatable: updatable,
  30012. sideOrientation: sideOrientation,
  30013. instance: instance
  30014. };
  30015. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30016. };
  30017. /**
  30018. * Creates a polyhedron mesh.
  30019. * Please consider using the same method from the MeshBuilder class instead.
  30020. * 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
  30021. * to choose the wanted type.
  30022. * The parameter `size` (positive float, default 1) sets the polygon size.
  30023. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30024. * 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`.
  30025. * 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
  30026. * 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)`).
  30027. * 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
  30028. * 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.
  30029. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30030. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30032. */
  30033. Mesh.CreatePolyhedron = function (name, options, scene) {
  30034. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30035. };
  30036. /**
  30037. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30038. * Please consider using the same method from the MeshBuilder class instead.
  30039. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30040. * 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`).
  30041. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30042. * 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.
  30043. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30044. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30046. */
  30047. Mesh.CreateIcoSphere = function (name, options, scene) {
  30048. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30049. };
  30050. /**
  30051. * Creates a decal mesh.
  30052. * Please consider using the same method from the MeshBuilder class instead.
  30053. * 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.
  30054. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30055. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30056. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30057. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30058. */
  30059. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30060. var options = {
  30061. position: position,
  30062. normal: normal,
  30063. size: size,
  30064. angle: angle
  30065. };
  30066. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30067. };
  30068. // Skeletons
  30069. /**
  30070. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30071. */
  30072. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30073. if (!this._sourcePositions) {
  30074. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30075. if (!source) {
  30076. return this._sourcePositions;
  30077. }
  30078. this._sourcePositions = new Float32Array(source);
  30079. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30080. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30081. }
  30082. }
  30083. return this._sourcePositions;
  30084. };
  30085. /**
  30086. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30087. */
  30088. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30089. if (!this._sourceNormals) {
  30090. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30091. if (!source) {
  30092. return this._sourceNormals;
  30093. }
  30094. this._sourceNormals = new Float32Array(source);
  30095. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30096. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30097. }
  30098. }
  30099. return this._sourceNormals;
  30100. };
  30101. /**
  30102. * Updates the vertex buffer by applying transformation from the bones.
  30103. * Returns the Mesh.
  30104. *
  30105. * @param {skeleton} skeleton to apply
  30106. */
  30107. Mesh.prototype.applySkeleton = function (skeleton) {
  30108. if (!this.geometry) {
  30109. return this;
  30110. }
  30111. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30112. return this;
  30113. }
  30114. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30115. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30116. return this;
  30117. }
  30118. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30119. return this;
  30120. }
  30121. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30122. return this;
  30123. }
  30124. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30125. return this;
  30126. }
  30127. if (!this._sourcePositions) {
  30128. var submeshes = this.subMeshes.slice();
  30129. this.setPositionsForCPUSkinning();
  30130. this.subMeshes = submeshes;
  30131. }
  30132. if (!this._sourceNormals) {
  30133. this.setNormalsForCPUSkinning();
  30134. }
  30135. // positionsData checks for not being Float32Array will only pass at most once
  30136. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30137. if (!positionsData) {
  30138. return this;
  30139. }
  30140. if (!(positionsData instanceof Float32Array)) {
  30141. positionsData = new Float32Array(positionsData);
  30142. }
  30143. // normalsData checks for not being Float32Array will only pass at most once
  30144. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30145. if (!normalsData) {
  30146. return this;
  30147. }
  30148. if (!(normalsData instanceof Float32Array)) {
  30149. normalsData = new Float32Array(normalsData);
  30150. }
  30151. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30152. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30153. if (!matricesWeightsData || !matricesIndicesData) {
  30154. return this;
  30155. }
  30156. var needExtras = this.numBoneInfluencers > 4;
  30157. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30158. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30159. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30160. var tempVector3 = BABYLON.Vector3.Zero();
  30161. var finalMatrix = new BABYLON.Matrix();
  30162. var tempMatrix = new BABYLON.Matrix();
  30163. var matWeightIdx = 0;
  30164. var inf;
  30165. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30166. var weight;
  30167. for (inf = 0; inf < 4; inf++) {
  30168. weight = matricesWeightsData[matWeightIdx + inf];
  30169. if (weight > 0) {
  30170. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30171. finalMatrix.addToSelf(tempMatrix);
  30172. }
  30173. else
  30174. break;
  30175. }
  30176. if (needExtras) {
  30177. for (inf = 0; inf < 4; inf++) {
  30178. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30179. if (weight > 0) {
  30180. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30181. finalMatrix.addToSelf(tempMatrix);
  30182. }
  30183. else
  30184. break;
  30185. }
  30186. }
  30187. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30188. tempVector3.toArray(positionsData, index);
  30189. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30190. tempVector3.toArray(normalsData, index);
  30191. finalMatrix.reset();
  30192. }
  30193. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30194. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30195. return this;
  30196. };
  30197. // Tools
  30198. /**
  30199. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30200. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30201. */
  30202. Mesh.MinMax = function (meshes) {
  30203. var minVector = null;
  30204. var maxVector = null;
  30205. meshes.forEach(function (mesh, index, array) {
  30206. var boundingInfo = mesh.getBoundingInfo();
  30207. var boundingBox = boundingInfo.boundingBox;
  30208. if (!minVector || !maxVector) {
  30209. minVector = boundingBox.minimumWorld;
  30210. maxVector = boundingBox.maximumWorld;
  30211. }
  30212. else {
  30213. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30214. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30215. }
  30216. });
  30217. if (!minVector || !maxVector) {
  30218. return {
  30219. min: BABYLON.Vector3.Zero(),
  30220. max: BABYLON.Vector3.Zero()
  30221. };
  30222. }
  30223. return {
  30224. min: minVector,
  30225. max: maxVector
  30226. };
  30227. };
  30228. /**
  30229. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30230. */
  30231. Mesh.Center = function (meshesOrMinMaxVector) {
  30232. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30233. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30234. };
  30235. /**
  30236. * Merge the array of meshes into a single mesh for performance reasons.
  30237. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30238. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30239. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30240. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30241. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30242. */
  30243. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30244. if (disposeSource === void 0) { disposeSource = true; }
  30245. var index;
  30246. if (!allow32BitsIndices) {
  30247. var totalVertices = 0;
  30248. // Counting vertices
  30249. for (index = 0; index < meshes.length; index++) {
  30250. if (meshes[index]) {
  30251. totalVertices += meshes[index].getTotalVertices();
  30252. if (totalVertices > 65536) {
  30253. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30254. return null;
  30255. }
  30256. }
  30257. }
  30258. }
  30259. // Merge
  30260. var vertexData = null;
  30261. var otherVertexData;
  30262. var indiceArray = new Array();
  30263. var source = null;
  30264. for (index = 0; index < meshes.length; index++) {
  30265. if (meshes[index]) {
  30266. meshes[index].computeWorldMatrix(true);
  30267. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30268. otherVertexData.transform(meshes[index].getWorldMatrix());
  30269. if (vertexData) {
  30270. vertexData.merge(otherVertexData);
  30271. }
  30272. else {
  30273. vertexData = otherVertexData;
  30274. source = meshes[index];
  30275. }
  30276. if (subdivideWithSubMeshes) {
  30277. indiceArray.push(meshes[index].getTotalIndices());
  30278. }
  30279. }
  30280. }
  30281. source = source;
  30282. if (!meshSubclass) {
  30283. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30284. }
  30285. vertexData.applyToMesh(meshSubclass);
  30286. // Setting properties
  30287. meshSubclass.material = source.material;
  30288. meshSubclass.checkCollisions = source.checkCollisions;
  30289. // Cleaning
  30290. if (disposeSource) {
  30291. for (index = 0; index < meshes.length; index++) {
  30292. if (meshes[index]) {
  30293. meshes[index].dispose();
  30294. }
  30295. }
  30296. }
  30297. // Subdivide
  30298. if (subdivideWithSubMeshes) {
  30299. //-- Suppresions du submesh global
  30300. meshSubclass.releaseSubMeshes();
  30301. index = 0;
  30302. var offset = 0;
  30303. //-- aplique la subdivision en fonction du tableau d'indices
  30304. while (index < indiceArray.length) {
  30305. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30306. offset += indiceArray[index];
  30307. index++;
  30308. }
  30309. }
  30310. return meshSubclass;
  30311. };
  30312. // Consts
  30313. Mesh._FRONTSIDE = 0;
  30314. Mesh._BACKSIDE = 1;
  30315. Mesh._DOUBLESIDE = 2;
  30316. Mesh._DEFAULTSIDE = 0;
  30317. Mesh._NO_CAP = 0;
  30318. Mesh._CAP_START = 1;
  30319. Mesh._CAP_END = 2;
  30320. Mesh._CAP_ALL = 3;
  30321. return Mesh;
  30322. }(BABYLON.AbstractMesh));
  30323. BABYLON.Mesh = Mesh;
  30324. })(BABYLON || (BABYLON = {}));
  30325. //# sourceMappingURL=babylon.mesh.js.map
  30326. var BABYLON;
  30327. (function (BABYLON) {
  30328. var BaseSubMesh = /** @class */ (function () {
  30329. function BaseSubMesh() {
  30330. }
  30331. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30332. get: function () {
  30333. return this._materialEffect;
  30334. },
  30335. enumerable: true,
  30336. configurable: true
  30337. });
  30338. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30339. if (defines === void 0) { defines = null; }
  30340. if (this._materialEffect === effect) {
  30341. if (!effect) {
  30342. this._materialDefines = null;
  30343. }
  30344. return;
  30345. }
  30346. this._materialDefines = defines;
  30347. this._materialEffect = effect;
  30348. };
  30349. return BaseSubMesh;
  30350. }());
  30351. BABYLON.BaseSubMesh = BaseSubMesh;
  30352. var SubMesh = /** @class */ (function (_super) {
  30353. __extends(SubMesh, _super);
  30354. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30355. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30356. var _this = _super.call(this) || this;
  30357. _this.materialIndex = materialIndex;
  30358. _this.verticesStart = verticesStart;
  30359. _this.verticesCount = verticesCount;
  30360. _this.indexStart = indexStart;
  30361. _this.indexCount = indexCount;
  30362. _this._renderId = 0;
  30363. _this._mesh = mesh;
  30364. _this._renderingMesh = renderingMesh || mesh;
  30365. mesh.subMeshes.push(_this);
  30366. _this._trianglePlanes = [];
  30367. _this._id = mesh.subMeshes.length - 1;
  30368. if (createBoundingBox) {
  30369. _this.refreshBoundingInfo();
  30370. mesh.computeWorldMatrix(true);
  30371. }
  30372. return _this;
  30373. }
  30374. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30375. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30376. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30377. };
  30378. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30379. get: function () {
  30380. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30381. },
  30382. enumerable: true,
  30383. configurable: true
  30384. });
  30385. /**
  30386. * Returns the submesh BoudingInfo object.
  30387. */
  30388. SubMesh.prototype.getBoundingInfo = function () {
  30389. if (this.IsGlobal) {
  30390. return this._mesh.getBoundingInfo();
  30391. }
  30392. return this._boundingInfo;
  30393. };
  30394. /**
  30395. * Sets the submesh BoundingInfo.
  30396. * Return the SubMesh.
  30397. */
  30398. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30399. this._boundingInfo = boundingInfo;
  30400. return this;
  30401. };
  30402. /**
  30403. * Returns the mesh of the current submesh.
  30404. */
  30405. SubMesh.prototype.getMesh = function () {
  30406. return this._mesh;
  30407. };
  30408. /**
  30409. * Returns the rendering mesh of the submesh.
  30410. */
  30411. SubMesh.prototype.getRenderingMesh = function () {
  30412. return this._renderingMesh;
  30413. };
  30414. /**
  30415. * Returns the submesh material.
  30416. */
  30417. SubMesh.prototype.getMaterial = function () {
  30418. var rootMaterial = this._renderingMesh.material;
  30419. if (rootMaterial === null || rootMaterial === undefined) {
  30420. return this._mesh.getScene().defaultMaterial;
  30421. }
  30422. else if (rootMaterial.getSubMaterial) {
  30423. var multiMaterial = rootMaterial;
  30424. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30425. if (this._currentMaterial !== effectiveMaterial) {
  30426. this._currentMaterial = effectiveMaterial;
  30427. this._materialDefines = null;
  30428. }
  30429. return effectiveMaterial;
  30430. }
  30431. return rootMaterial;
  30432. };
  30433. // Methods
  30434. /**
  30435. * Sets a new updated BoundingInfo object to the submesh.
  30436. * Returns the SubMesh.
  30437. */
  30438. SubMesh.prototype.refreshBoundingInfo = function () {
  30439. this._lastColliderWorldVertices = null;
  30440. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30441. return this;
  30442. }
  30443. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30444. if (!data) {
  30445. this._boundingInfo = this._mesh.getBoundingInfo();
  30446. return this;
  30447. }
  30448. var indices = this._renderingMesh.getIndices();
  30449. var extend;
  30450. //is this the only submesh?
  30451. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30452. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30453. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30454. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30455. }
  30456. else {
  30457. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30458. }
  30459. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30460. return this;
  30461. };
  30462. SubMesh.prototype._checkCollision = function (collider) {
  30463. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30464. return boundingInfo._checkCollision(collider);
  30465. };
  30466. /**
  30467. * Updates the submesh BoundingInfo.
  30468. * Returns the Submesh.
  30469. */
  30470. SubMesh.prototype.updateBoundingInfo = function (world) {
  30471. var boundingInfo = this.getBoundingInfo();
  30472. if (!boundingInfo) {
  30473. this.refreshBoundingInfo();
  30474. boundingInfo = this.getBoundingInfo();
  30475. }
  30476. boundingInfo.update(world);
  30477. return this;
  30478. };
  30479. /**
  30480. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30481. * Boolean returned.
  30482. */
  30483. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30484. var boundingInfo = this.getBoundingInfo();
  30485. if (!boundingInfo) {
  30486. return false;
  30487. }
  30488. return boundingInfo.isInFrustum(frustumPlanes);
  30489. };
  30490. /**
  30491. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30492. * Boolean returned.
  30493. */
  30494. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30495. var boundingInfo = this.getBoundingInfo();
  30496. if (!boundingInfo) {
  30497. return false;
  30498. }
  30499. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30500. };
  30501. /**
  30502. * Renders the submesh.
  30503. * Returns it.
  30504. */
  30505. SubMesh.prototype.render = function (enableAlphaMode) {
  30506. this._renderingMesh.render(this, enableAlphaMode);
  30507. return this;
  30508. };
  30509. /**
  30510. * Returns a new Index Buffer.
  30511. * Type returned : WebGLBuffer.
  30512. */
  30513. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30514. if (!this._linesIndexBuffer) {
  30515. var linesIndices = [];
  30516. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30517. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30518. }
  30519. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30520. this.linesIndexCount = linesIndices.length;
  30521. }
  30522. return this._linesIndexBuffer;
  30523. };
  30524. /**
  30525. * True is the passed Ray intersects the submesh bounding box.
  30526. * Boolean returned.
  30527. */
  30528. SubMesh.prototype.canIntersects = function (ray) {
  30529. var boundingInfo = this.getBoundingInfo();
  30530. if (!boundingInfo) {
  30531. return false;
  30532. }
  30533. return ray.intersectsBox(boundingInfo.boundingBox);
  30534. };
  30535. /**
  30536. * Returns an object IntersectionInfo.
  30537. */
  30538. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30539. var intersectInfo = null;
  30540. // LineMesh first as it's also a Mesh...
  30541. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30542. var lineMesh = this._mesh;
  30543. // Line test
  30544. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30545. var p0 = positions[indices[index]];
  30546. var p1 = positions[indices[index + 1]];
  30547. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30548. if (length < 0) {
  30549. continue;
  30550. }
  30551. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30552. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30553. if (fastCheck) {
  30554. break;
  30555. }
  30556. }
  30557. }
  30558. }
  30559. else {
  30560. // Triangles test
  30561. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30562. var p0 = positions[indices[index]];
  30563. var p1 = positions[indices[index + 1]];
  30564. var p2 = positions[indices[index + 2]];
  30565. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30566. if (currentIntersectInfo) {
  30567. if (currentIntersectInfo.distance < 0) {
  30568. continue;
  30569. }
  30570. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30571. intersectInfo = currentIntersectInfo;
  30572. intersectInfo.faceId = index / 3;
  30573. if (fastCheck) {
  30574. break;
  30575. }
  30576. }
  30577. }
  30578. }
  30579. }
  30580. return intersectInfo;
  30581. };
  30582. SubMesh.prototype._rebuild = function () {
  30583. if (this._linesIndexBuffer) {
  30584. this._linesIndexBuffer = null;
  30585. }
  30586. };
  30587. // Clone
  30588. /**
  30589. * Creates a new Submesh from the passed Mesh.
  30590. */
  30591. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30592. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30593. if (!this.IsGlobal) {
  30594. var boundingInfo = this.getBoundingInfo();
  30595. if (!boundingInfo) {
  30596. return result;
  30597. }
  30598. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30599. }
  30600. return result;
  30601. };
  30602. // Dispose
  30603. /**
  30604. * Disposes the Submesh.
  30605. * Returns nothing.
  30606. */
  30607. SubMesh.prototype.dispose = function () {
  30608. if (this._linesIndexBuffer) {
  30609. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30610. this._linesIndexBuffer = null;
  30611. }
  30612. // Remove from mesh
  30613. var index = this._mesh.subMeshes.indexOf(this);
  30614. this._mesh.subMeshes.splice(index, 1);
  30615. };
  30616. // Statics
  30617. /**
  30618. * Creates a new Submesh from the passed parameters :
  30619. * - materialIndex (integer) : the index of the main mesh material.
  30620. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30621. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30622. * - mesh (Mesh) : the main mesh to create the submesh from.
  30623. * - renderingMesh (optional Mesh) : rendering mesh.
  30624. */
  30625. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30626. var minVertexIndex = Number.MAX_VALUE;
  30627. var maxVertexIndex = -Number.MAX_VALUE;
  30628. renderingMesh = (renderingMesh || mesh);
  30629. var indices = renderingMesh.getIndices();
  30630. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30631. var vertexIndex = indices[index];
  30632. if (vertexIndex < minVertexIndex)
  30633. minVertexIndex = vertexIndex;
  30634. if (vertexIndex > maxVertexIndex)
  30635. maxVertexIndex = vertexIndex;
  30636. }
  30637. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30638. };
  30639. return SubMesh;
  30640. }(BaseSubMesh));
  30641. BABYLON.SubMesh = SubMesh;
  30642. })(BABYLON || (BABYLON = {}));
  30643. //# sourceMappingURL=babylon.subMesh.js.map
  30644. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30645. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30646. s = arguments[i];
  30647. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30648. t[p] = s[p];
  30649. }
  30650. return t;
  30651. };
  30652. var BABYLON;
  30653. (function (BABYLON) {
  30654. /**
  30655. * Manages the defines for the Material.
  30656. */
  30657. var MaterialDefines = /** @class */ (function () {
  30658. function MaterialDefines() {
  30659. this._isDirty = true;
  30660. this._areLightsDirty = true;
  30661. this._areAttributesDirty = true;
  30662. this._areTexturesDirty = true;
  30663. this._areFresnelDirty = true;
  30664. this._areMiscDirty = true;
  30665. this._areImageProcessingDirty = true;
  30666. this._normals = false;
  30667. this._uvs = false;
  30668. this._needNormals = false;
  30669. this._needUVs = false;
  30670. }
  30671. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30672. /**
  30673. * Specifies if the material needs to be re-calculated.
  30674. */
  30675. get: function () {
  30676. return this._isDirty;
  30677. },
  30678. enumerable: true,
  30679. configurable: true
  30680. });
  30681. /**
  30682. * Marks the material to indicate that it has been re-calculated.
  30683. */
  30684. MaterialDefines.prototype.markAsProcessed = function () {
  30685. this._isDirty = false;
  30686. this._areAttributesDirty = false;
  30687. this._areTexturesDirty = false;
  30688. this._areFresnelDirty = false;
  30689. this._areLightsDirty = false;
  30690. this._areMiscDirty = false;
  30691. this._areImageProcessingDirty = false;
  30692. };
  30693. /**
  30694. * Marks the material to indicate that it needs to be re-calculated.
  30695. */
  30696. MaterialDefines.prototype.markAsUnprocessed = function () {
  30697. this._isDirty = true;
  30698. };
  30699. /**
  30700. * Marks the material to indicate all of its defines need to be re-calculated.
  30701. */
  30702. MaterialDefines.prototype.markAllAsDirty = function () {
  30703. this._areTexturesDirty = true;
  30704. this._areAttributesDirty = true;
  30705. this._areLightsDirty = true;
  30706. this._areFresnelDirty = true;
  30707. this._areMiscDirty = true;
  30708. this._areImageProcessingDirty = true;
  30709. this._isDirty = true;
  30710. };
  30711. /**
  30712. * Marks the material to indicate that image processing needs to be re-calculated.
  30713. */
  30714. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30715. this._areImageProcessingDirty = true;
  30716. this._isDirty = true;
  30717. };
  30718. /**
  30719. * Marks the material to indicate the lights need to be re-calculated.
  30720. */
  30721. MaterialDefines.prototype.markAsLightDirty = function () {
  30722. this._areLightsDirty = true;
  30723. this._isDirty = true;
  30724. };
  30725. /**
  30726. * Marks the attribute state as changed.
  30727. */
  30728. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30729. this._areAttributesDirty = true;
  30730. this._isDirty = true;
  30731. };
  30732. /**
  30733. * Marks the texture state as changed.
  30734. */
  30735. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30736. this._areTexturesDirty = true;
  30737. this._isDirty = true;
  30738. };
  30739. /**
  30740. * Marks the fresnel state as changed.
  30741. */
  30742. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30743. this._areFresnelDirty = true;
  30744. this._isDirty = true;
  30745. };
  30746. /**
  30747. * Marks the misc state as changed.
  30748. */
  30749. MaterialDefines.prototype.markAsMiscDirty = function () {
  30750. this._areMiscDirty = true;
  30751. this._isDirty = true;
  30752. };
  30753. /**
  30754. * Rebuilds the material defines.
  30755. */
  30756. MaterialDefines.prototype.rebuild = function () {
  30757. if (this._keys) {
  30758. delete this._keys;
  30759. }
  30760. this._keys = [];
  30761. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30762. var key = _a[_i];
  30763. if (key[0] === "_") {
  30764. continue;
  30765. }
  30766. this._keys.push(key);
  30767. }
  30768. };
  30769. /**
  30770. * Specifies if two material defines are equal.
  30771. * @param other - A material define instance to compare to.
  30772. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30773. */
  30774. MaterialDefines.prototype.isEqual = function (other) {
  30775. if (this._keys.length !== other._keys.length) {
  30776. return false;
  30777. }
  30778. for (var index = 0; index < this._keys.length; index++) {
  30779. var prop = this._keys[index];
  30780. if (this[prop] !== other[prop]) {
  30781. return false;
  30782. }
  30783. }
  30784. return true;
  30785. };
  30786. /**
  30787. * Clones this instance's defines to another instance.
  30788. * @param other - material defines to clone values to.
  30789. */
  30790. MaterialDefines.prototype.cloneTo = function (other) {
  30791. if (this._keys.length !== other._keys.length) {
  30792. other._keys = this._keys.slice(0);
  30793. }
  30794. for (var index = 0; index < this._keys.length; index++) {
  30795. var prop = this._keys[index];
  30796. other[prop] = this[prop];
  30797. }
  30798. };
  30799. /**
  30800. * Resets the material define values.
  30801. */
  30802. MaterialDefines.prototype.reset = function () {
  30803. for (var index = 0; index < this._keys.length; index++) {
  30804. var prop = this._keys[index];
  30805. if (typeof (this[prop]) === "number") {
  30806. this[prop] = 0;
  30807. }
  30808. else {
  30809. this[prop] = false;
  30810. }
  30811. }
  30812. };
  30813. /**
  30814. * Converts the material define values to a string.
  30815. * @returns - String of material define information.
  30816. */
  30817. MaterialDefines.prototype.toString = function () {
  30818. var result = "";
  30819. for (var index = 0; index < this._keys.length; index++) {
  30820. var prop = this._keys[index];
  30821. var value = this[prop];
  30822. if (typeof (value) === "number") {
  30823. result += "#define " + prop + " " + this[prop] + "\n";
  30824. }
  30825. else if (value) {
  30826. result += "#define " + prop + "\n";
  30827. }
  30828. }
  30829. return result;
  30830. };
  30831. return MaterialDefines;
  30832. }());
  30833. BABYLON.MaterialDefines = MaterialDefines;
  30834. /**
  30835. * This offers the main features of a material in BJS.
  30836. */
  30837. var Material = /** @class */ (function () {
  30838. /**
  30839. * Creates a material instance.
  30840. * @param name - The name of the material.
  30841. * @param scene - The BJS scene to reference.
  30842. * @param doNotAdd - Specifies if the material should be added to the scene.
  30843. */
  30844. function Material(name, scene, doNotAdd) {
  30845. /**
  30846. * Specifies if the ready state should be checked on each call.
  30847. */
  30848. this.checkReadyOnEveryCall = false;
  30849. /**
  30850. * Specifies if the ready state should be checked once.
  30851. */
  30852. this.checkReadyOnlyOnce = false;
  30853. /**
  30854. * The state of the material.
  30855. */
  30856. this.state = "";
  30857. /**
  30858. * The alpha value of the material.
  30859. */
  30860. this._alpha = 1.0;
  30861. /**
  30862. * Specifies if back face culling is enabled.
  30863. */
  30864. this._backFaceCulling = true;
  30865. /**
  30866. * Specifies if the material should be serialized.
  30867. */
  30868. this.doNotSerialize = false;
  30869. /**
  30870. * Specifies if the effect should be stored on sub meshes.
  30871. */
  30872. this.storeEffectOnSubMeshes = false;
  30873. /**
  30874. * An event triggered when the material is disposed.
  30875. * @type {BABYLON.Observable}
  30876. */
  30877. this.onDisposeObservable = new BABYLON.Observable();
  30878. /**
  30879. * An event triggered when the material is bound.
  30880. * @type {BABYLON.Observable}
  30881. */
  30882. this.onBindObservable = new BABYLON.Observable();
  30883. /**
  30884. * An event triggered when the material is unbound.
  30885. * @type {BABYLON.Observable}
  30886. */
  30887. this.onUnBindObservable = new BABYLON.Observable();
  30888. /**
  30889. * Stores the value of the alpha mode.
  30890. */
  30891. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30892. /**
  30893. * Stores the state of the need depth pre-pass value.
  30894. */
  30895. this._needDepthPrePass = false;
  30896. /**
  30897. * Specifies if depth writing should be disabled.
  30898. */
  30899. this.disableDepthWrite = false;
  30900. /**
  30901. * Specifies if depth writing should be forced.
  30902. */
  30903. this.forceDepthWrite = false;
  30904. /**
  30905. * Specifies if there should be a separate pass for culling.
  30906. */
  30907. this.separateCullingPass = false;
  30908. /**
  30909. * Stores the state specifing if fog should be enabled.
  30910. */
  30911. this._fogEnabled = true;
  30912. /**
  30913. * Stores the size of points.
  30914. */
  30915. this.pointSize = 1.0;
  30916. /**
  30917. * Stores the z offset value.
  30918. */
  30919. this.zOffset = 0;
  30920. /**
  30921. * Specifies if the material was previously ready.
  30922. */
  30923. this._wasPreviouslyReady = false;
  30924. /**
  30925. * Stores the fill mode state.
  30926. */
  30927. this._fillMode = Material.TriangleFillMode;
  30928. this.name = name;
  30929. this.id = name || BABYLON.Tools.RandomId();
  30930. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30931. if (this._scene.useRightHandedSystem) {
  30932. this.sideOrientation = Material.ClockWiseSideOrientation;
  30933. }
  30934. else {
  30935. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30936. }
  30937. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30938. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30939. if (!doNotAdd) {
  30940. this._scene.materials.push(this);
  30941. }
  30942. }
  30943. Object.defineProperty(Material, "TriangleFillMode", {
  30944. /**
  30945. * Returns the triangle fill mode.
  30946. */
  30947. get: function () {
  30948. return Material._TriangleFillMode;
  30949. },
  30950. enumerable: true,
  30951. configurable: true
  30952. });
  30953. Object.defineProperty(Material, "WireFrameFillMode", {
  30954. /**
  30955. * Returns the wireframe mode.
  30956. */
  30957. get: function () {
  30958. return Material._WireFrameFillMode;
  30959. },
  30960. enumerable: true,
  30961. configurable: true
  30962. });
  30963. Object.defineProperty(Material, "PointFillMode", {
  30964. /**
  30965. * Returns the point fill mode.
  30966. */
  30967. get: function () {
  30968. return Material._PointFillMode;
  30969. },
  30970. enumerable: true,
  30971. configurable: true
  30972. });
  30973. Object.defineProperty(Material, "PointListDrawMode", {
  30974. /**
  30975. * Returns the point list draw mode.
  30976. */
  30977. get: function () {
  30978. return Material._PointListDrawMode;
  30979. },
  30980. enumerable: true,
  30981. configurable: true
  30982. });
  30983. Object.defineProperty(Material, "LineListDrawMode", {
  30984. /**
  30985. * Returns the line list draw mode.
  30986. */
  30987. get: function () {
  30988. return Material._LineListDrawMode;
  30989. },
  30990. enumerable: true,
  30991. configurable: true
  30992. });
  30993. Object.defineProperty(Material, "LineLoopDrawMode", {
  30994. /**
  30995. * Returns the line loop draw mode.
  30996. */
  30997. get: function () {
  30998. return Material._LineLoopDrawMode;
  30999. },
  31000. enumerable: true,
  31001. configurable: true
  31002. });
  31003. Object.defineProperty(Material, "LineStripDrawMode", {
  31004. /**
  31005. * Returns the line strip draw mode.
  31006. */
  31007. get: function () {
  31008. return Material._LineStripDrawMode;
  31009. },
  31010. enumerable: true,
  31011. configurable: true
  31012. });
  31013. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31014. /**
  31015. * Returns the triangle strip draw mode.
  31016. */
  31017. get: function () {
  31018. return Material._TriangleStripDrawMode;
  31019. },
  31020. enumerable: true,
  31021. configurable: true
  31022. });
  31023. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31024. /**
  31025. * Returns the triangle fan draw mode.
  31026. */
  31027. get: function () {
  31028. return Material._TriangleFanDrawMode;
  31029. },
  31030. enumerable: true,
  31031. configurable: true
  31032. });
  31033. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31034. /**
  31035. * Returns the clock-wise side orientation.
  31036. */
  31037. get: function () {
  31038. return Material._ClockWiseSideOrientation;
  31039. },
  31040. enumerable: true,
  31041. configurable: true
  31042. });
  31043. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31044. /**
  31045. * Returns the counter clock-wise side orientation.
  31046. */
  31047. get: function () {
  31048. return Material._CounterClockWiseSideOrientation;
  31049. },
  31050. enumerable: true,
  31051. configurable: true
  31052. });
  31053. Object.defineProperty(Material, "TextureDirtyFlag", {
  31054. /**
  31055. * Returns the dirty texture flag value.
  31056. */
  31057. get: function () {
  31058. return Material._TextureDirtyFlag;
  31059. },
  31060. enumerable: true,
  31061. configurable: true
  31062. });
  31063. Object.defineProperty(Material, "LightDirtyFlag", {
  31064. /**
  31065. * Returns the dirty light flag value.
  31066. */
  31067. get: function () {
  31068. return Material._LightDirtyFlag;
  31069. },
  31070. enumerable: true,
  31071. configurable: true
  31072. });
  31073. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31074. /**
  31075. * Returns the dirty fresnel flag value.
  31076. */
  31077. get: function () {
  31078. return Material._FresnelDirtyFlag;
  31079. },
  31080. enumerable: true,
  31081. configurable: true
  31082. });
  31083. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31084. /**
  31085. * Returns the dirty attributes flag value.
  31086. */
  31087. get: function () {
  31088. return Material._AttributesDirtyFlag;
  31089. },
  31090. enumerable: true,
  31091. configurable: true
  31092. });
  31093. Object.defineProperty(Material, "MiscDirtyFlag", {
  31094. /**
  31095. * Returns the dirty misc flag value.
  31096. */
  31097. get: function () {
  31098. return Material._MiscDirtyFlag;
  31099. },
  31100. enumerable: true,
  31101. configurable: true
  31102. });
  31103. Object.defineProperty(Material.prototype, "alpha", {
  31104. /**
  31105. * Gets the alpha value of the material.
  31106. */
  31107. get: function () {
  31108. return this._alpha;
  31109. },
  31110. /**
  31111. * Sets the alpha value of the material.
  31112. */
  31113. set: function (value) {
  31114. if (this._alpha === value) {
  31115. return;
  31116. }
  31117. this._alpha = value;
  31118. this.markAsDirty(Material.MiscDirtyFlag);
  31119. },
  31120. enumerable: true,
  31121. configurable: true
  31122. });
  31123. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31124. /**
  31125. * Gets the back-face culling state.
  31126. */
  31127. get: function () {
  31128. return this._backFaceCulling;
  31129. },
  31130. /**
  31131. * Sets the back-face culling state.
  31132. */
  31133. set: function (value) {
  31134. if (this._backFaceCulling === value) {
  31135. return;
  31136. }
  31137. this._backFaceCulling = value;
  31138. this.markAsDirty(Material.TextureDirtyFlag);
  31139. },
  31140. enumerable: true,
  31141. configurable: true
  31142. });
  31143. Object.defineProperty(Material.prototype, "onDispose", {
  31144. /**
  31145. * Called during a dispose event.
  31146. */
  31147. set: function (callback) {
  31148. if (this._onDisposeObserver) {
  31149. this.onDisposeObservable.remove(this._onDisposeObserver);
  31150. }
  31151. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31152. },
  31153. enumerable: true,
  31154. configurable: true
  31155. });
  31156. Object.defineProperty(Material.prototype, "onBind", {
  31157. /**
  31158. * Called during a bind event.
  31159. */
  31160. set: function (callback) {
  31161. if (this._onBindObserver) {
  31162. this.onBindObservable.remove(this._onBindObserver);
  31163. }
  31164. this._onBindObserver = this.onBindObservable.add(callback);
  31165. },
  31166. enumerable: true,
  31167. configurable: true
  31168. });
  31169. Object.defineProperty(Material.prototype, "alphaMode", {
  31170. /**
  31171. * Gets the value of the alpha mode.
  31172. */
  31173. get: function () {
  31174. return this._alphaMode;
  31175. },
  31176. /**
  31177. * Sets the value of the alpha mode.
  31178. */
  31179. set: function (value) {
  31180. if (this._alphaMode === value) {
  31181. return;
  31182. }
  31183. this._alphaMode = value;
  31184. this.markAsDirty(Material.TextureDirtyFlag);
  31185. },
  31186. enumerable: true,
  31187. configurable: true
  31188. });
  31189. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31190. /**
  31191. * Gets the depth pre-pass value.
  31192. */
  31193. get: function () {
  31194. return this._needDepthPrePass;
  31195. },
  31196. /**
  31197. * Sets the need depth pre-pass value.
  31198. */
  31199. set: function (value) {
  31200. if (this._needDepthPrePass === value) {
  31201. return;
  31202. }
  31203. this._needDepthPrePass = value;
  31204. if (this._needDepthPrePass) {
  31205. this.checkReadyOnEveryCall = true;
  31206. }
  31207. },
  31208. enumerable: true,
  31209. configurable: true
  31210. });
  31211. Object.defineProperty(Material.prototype, "fogEnabled", {
  31212. /**
  31213. * Gets the value of the fog enabled state.
  31214. */
  31215. get: function () {
  31216. return this._fogEnabled;
  31217. },
  31218. /**
  31219. * Sets the state for enabling fog.
  31220. */
  31221. set: function (value) {
  31222. if (this._fogEnabled === value) {
  31223. return;
  31224. }
  31225. this._fogEnabled = value;
  31226. this.markAsDirty(Material.MiscDirtyFlag);
  31227. },
  31228. enumerable: true,
  31229. configurable: true
  31230. });
  31231. Object.defineProperty(Material.prototype, "wireframe", {
  31232. /**
  31233. * Gets a value specifying if wireframe mode is enabled.
  31234. */
  31235. get: function () {
  31236. return this._fillMode === Material.WireFrameFillMode;
  31237. },
  31238. /**
  31239. * Sets the state of wireframe mode.
  31240. */
  31241. set: function (value) {
  31242. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31243. },
  31244. enumerable: true,
  31245. configurable: true
  31246. });
  31247. Object.defineProperty(Material.prototype, "pointsCloud", {
  31248. /**
  31249. * Gets the value specifying if point clouds are enabled.
  31250. */
  31251. get: function () {
  31252. return this._fillMode === Material.PointFillMode;
  31253. },
  31254. /**
  31255. * Sets the state of point cloud mode.
  31256. */
  31257. set: function (value) {
  31258. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31259. },
  31260. enumerable: true,
  31261. configurable: true
  31262. });
  31263. Object.defineProperty(Material.prototype, "fillMode", {
  31264. /**
  31265. * Gets the material fill mode.
  31266. */
  31267. get: function () {
  31268. return this._fillMode;
  31269. },
  31270. /**
  31271. * Sets the material fill mode.
  31272. */
  31273. set: function (value) {
  31274. if (this._fillMode === value) {
  31275. return;
  31276. }
  31277. this._fillMode = value;
  31278. this.markAsDirty(Material.MiscDirtyFlag);
  31279. },
  31280. enumerable: true,
  31281. configurable: true
  31282. });
  31283. /**
  31284. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31285. * subclasses should override adding information pertainent to themselves.
  31286. * @returns - String with material information.
  31287. */
  31288. Material.prototype.toString = function (fullDetails) {
  31289. var ret = "Name: " + this.name;
  31290. if (fullDetails) {
  31291. }
  31292. return ret;
  31293. };
  31294. /**
  31295. * Gets the class name of the material.
  31296. * @returns - String with the class name of the material.
  31297. */
  31298. Material.prototype.getClassName = function () {
  31299. return "Material";
  31300. };
  31301. Object.defineProperty(Material.prototype, "isFrozen", {
  31302. /**
  31303. * Specifies if updates for the material been locked.
  31304. */
  31305. get: function () {
  31306. return this.checkReadyOnlyOnce;
  31307. },
  31308. enumerable: true,
  31309. configurable: true
  31310. });
  31311. /**
  31312. * Locks updates for the material.
  31313. */
  31314. Material.prototype.freeze = function () {
  31315. this.checkReadyOnlyOnce = true;
  31316. };
  31317. /**
  31318. * Unlocks updates for the material.
  31319. */
  31320. Material.prototype.unfreeze = function () {
  31321. this.checkReadyOnlyOnce = false;
  31322. };
  31323. /**
  31324. * Specifies if the material is ready to be used.
  31325. * @param mesh - BJS mesh.
  31326. * @param useInstances - Specifies if instances should be used.
  31327. * @returns - Boolean indicating if the material is ready to be used.
  31328. */
  31329. Material.prototype.isReady = function (mesh, useInstances) {
  31330. return true;
  31331. };
  31332. /**
  31333. * Specifies that the submesh is ready to be used.
  31334. * @param mesh - BJS mesh.
  31335. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31336. * @param useInstances - Specifies that instances should be used.
  31337. * @returns - boolean indicating that the submesh is ready or not.
  31338. */
  31339. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31340. return false;
  31341. };
  31342. /**
  31343. * Returns the material effect.
  31344. * @returns - Nullable material effect.
  31345. */
  31346. Material.prototype.getEffect = function () {
  31347. return this._effect;
  31348. };
  31349. /**
  31350. * Returns the BJS scene.
  31351. * @returns - BJS Scene.
  31352. */
  31353. Material.prototype.getScene = function () {
  31354. return this._scene;
  31355. };
  31356. /**
  31357. * Specifies if the material will require alpha blending
  31358. * @returns - Boolean specifying if alpha blending is needed.
  31359. */
  31360. Material.prototype.needAlphaBlending = function () {
  31361. return (this.alpha < 1.0);
  31362. };
  31363. /**
  31364. * Specifies if the mesh will require alpha blending.
  31365. * @param mesh - BJS mesh.
  31366. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31367. */
  31368. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31369. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31370. };
  31371. /**
  31372. * Specifies if this material should be rendered in alpha test mode.
  31373. * @returns - Boolean specifying if an alpha test is needed.
  31374. */
  31375. Material.prototype.needAlphaTesting = function () {
  31376. return false;
  31377. };
  31378. /**
  31379. * Gets the texture used for the alpha test.
  31380. * @returns - Nullable alpha test texture.
  31381. */
  31382. Material.prototype.getAlphaTestTexture = function () {
  31383. return null;
  31384. };
  31385. /**
  31386. * Marks the material to indicate that it needs to be re-calculated.
  31387. */
  31388. Material.prototype.markDirty = function () {
  31389. this._wasPreviouslyReady = false;
  31390. };
  31391. Material.prototype._preBind = function (effect, overrideOrientation) {
  31392. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31393. var engine = this._scene.getEngine();
  31394. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31395. var reverse = orientation === Material.ClockWiseSideOrientation;
  31396. engine.enableEffect(effect ? effect : this._effect);
  31397. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31398. return reverse;
  31399. };
  31400. /**
  31401. * Binds the material to the mesh.
  31402. * @param world - World transformation matrix.
  31403. * @param mesh - Mesh to bind the material to.
  31404. */
  31405. Material.prototype.bind = function (world, mesh) {
  31406. };
  31407. /**
  31408. * Binds the submesh to the material.
  31409. * @param world - World transformation matrix.
  31410. * @param mesh - Mesh containing the submesh.
  31411. * @param subMesh - Submesh to bind the material to.
  31412. */
  31413. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31414. };
  31415. /**
  31416. * Binds the world matrix to the material.
  31417. * @param world - World transformation matrix.
  31418. */
  31419. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31420. };
  31421. /**
  31422. * Binds the scene's uniform buffer to the effect.
  31423. * @param effect - Effect to bind to the scene uniform buffer.
  31424. * @param sceneUbo - Scene uniform buffer.
  31425. */
  31426. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31427. sceneUbo.bindToEffect(effect, "Scene");
  31428. };
  31429. /**
  31430. * Binds the view matrix to the effect.
  31431. * @param effect - Effect to bind the view matrix to.
  31432. */
  31433. Material.prototype.bindView = function (effect) {
  31434. if (!this._useUBO) {
  31435. effect.setMatrix("view", this.getScene().getViewMatrix());
  31436. }
  31437. else {
  31438. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31439. }
  31440. };
  31441. /**
  31442. * Binds the view projection matrix to the effect.
  31443. * @param effect - Effect to bind the view projection matrix to.
  31444. */
  31445. Material.prototype.bindViewProjection = function (effect) {
  31446. if (!this._useUBO) {
  31447. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31448. }
  31449. else {
  31450. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31451. }
  31452. };
  31453. /**
  31454. * Specifies if material alpha testing should be turned on for the mesh.
  31455. * @param mesh - BJS mesh.
  31456. */
  31457. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31458. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31459. };
  31460. /**
  31461. * Processes to execute after binding the material to a mesh.
  31462. * @param mesh - BJS mesh.
  31463. */
  31464. Material.prototype._afterBind = function (mesh) {
  31465. this._scene._cachedMaterial = this;
  31466. if (mesh) {
  31467. this._scene._cachedVisibility = mesh.visibility;
  31468. }
  31469. else {
  31470. this._scene._cachedVisibility = 1;
  31471. }
  31472. if (mesh) {
  31473. this.onBindObservable.notifyObservers(mesh);
  31474. }
  31475. if (this.disableDepthWrite) {
  31476. var engine = this._scene.getEngine();
  31477. this._cachedDepthWriteState = engine.getDepthWrite();
  31478. engine.setDepthWrite(false);
  31479. }
  31480. };
  31481. /**
  31482. * Unbinds the material from the mesh.
  31483. */
  31484. Material.prototype.unbind = function () {
  31485. this.onUnBindObservable.notifyObservers(this);
  31486. if (this.disableDepthWrite) {
  31487. var engine = this._scene.getEngine();
  31488. engine.setDepthWrite(this._cachedDepthWriteState);
  31489. }
  31490. };
  31491. /**
  31492. * Gets the active textures from the material.
  31493. * @returns - Array of textures.
  31494. */
  31495. Material.prototype.getActiveTextures = function () {
  31496. return [];
  31497. };
  31498. /**
  31499. * Specifies if the material uses a texture.
  31500. * @param texture - Texture to check against the material.
  31501. * @returns - Boolean specifying if the material uses the texture.
  31502. */
  31503. Material.prototype.hasTexture = function (texture) {
  31504. return false;
  31505. };
  31506. /**
  31507. * Makes a duplicate of the material, and gives it a new name.
  31508. * @param name - Name to call the duplicated material.
  31509. * @returns - Nullable cloned material
  31510. */
  31511. Material.prototype.clone = function (name) {
  31512. return null;
  31513. };
  31514. /**
  31515. * Gets the meshes bound to the material.
  31516. * @returns - Array of meshes bound to the material.
  31517. */
  31518. Material.prototype.getBindedMeshes = function () {
  31519. var result = new Array();
  31520. for (var index = 0; index < this._scene.meshes.length; index++) {
  31521. var mesh = this._scene.meshes[index];
  31522. if (mesh.material === this) {
  31523. result.push(mesh);
  31524. }
  31525. }
  31526. return result;
  31527. };
  31528. /**
  31529. * Force shader compilation
  31530. * @param mesh - BJS mesh.
  31531. * @param onCompiled - function to execute once the material is compiled.
  31532. * @param options - options to pass to this function.
  31533. */
  31534. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31535. var _this = this;
  31536. var localOptions = __assign({ clipPlane: false }, options);
  31537. var subMesh = new BABYLON.BaseSubMesh();
  31538. var scene = this.getScene();
  31539. var checkReady = function () {
  31540. if (!_this._scene || !_this._scene.getEngine()) {
  31541. return;
  31542. }
  31543. if (subMesh._materialDefines) {
  31544. subMesh._materialDefines._renderId = -1;
  31545. }
  31546. var clipPlaneState = scene.clipPlane;
  31547. if (localOptions.clipPlane) {
  31548. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31549. }
  31550. if (_this.storeEffectOnSubMeshes) {
  31551. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31552. if (onCompiled) {
  31553. onCompiled(_this);
  31554. }
  31555. }
  31556. else {
  31557. setTimeout(checkReady, 16);
  31558. }
  31559. }
  31560. else {
  31561. if (_this.isReady(mesh)) {
  31562. if (onCompiled) {
  31563. onCompiled(_this);
  31564. }
  31565. }
  31566. else {
  31567. setTimeout(checkReady, 16);
  31568. }
  31569. }
  31570. if (localOptions.clipPlane) {
  31571. scene.clipPlane = clipPlaneState;
  31572. }
  31573. };
  31574. checkReady();
  31575. };
  31576. /**
  31577. * Force shader compilation.
  31578. * @param mesh The mesh that will use this material
  31579. * @param options Additional options for compiling the shaders
  31580. * @returns A promise that resolves when the compilation completes
  31581. */
  31582. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31583. var _this = this;
  31584. return new Promise(function (resolve) {
  31585. _this.forceCompilation(mesh, function () {
  31586. resolve();
  31587. }, options);
  31588. });
  31589. };
  31590. /**
  31591. * Marks a define in the material to indicate that it needs to be re-computed.
  31592. * @param flag - Material define flag.
  31593. */
  31594. Material.prototype.markAsDirty = function (flag) {
  31595. if (flag & Material.TextureDirtyFlag) {
  31596. this._markAllSubMeshesAsTexturesDirty();
  31597. }
  31598. if (flag & Material.LightDirtyFlag) {
  31599. this._markAllSubMeshesAsLightsDirty();
  31600. }
  31601. if (flag & Material.FresnelDirtyFlag) {
  31602. this._markAllSubMeshesAsFresnelDirty();
  31603. }
  31604. if (flag & Material.AttributesDirtyFlag) {
  31605. this._markAllSubMeshesAsAttributesDirty();
  31606. }
  31607. if (flag & Material.MiscDirtyFlag) {
  31608. this._markAllSubMeshesAsMiscDirty();
  31609. }
  31610. this.getScene().resetCachedMaterial();
  31611. };
  31612. /**
  31613. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31614. * @param func - function which checks material defines against the submeshes.
  31615. */
  31616. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31617. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31618. var mesh = _a[_i];
  31619. if (!mesh.subMeshes) {
  31620. continue;
  31621. }
  31622. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31623. var subMesh = _c[_b];
  31624. if (subMesh.getMaterial() !== this) {
  31625. continue;
  31626. }
  31627. if (!subMesh._materialDefines) {
  31628. continue;
  31629. }
  31630. func(subMesh._materialDefines);
  31631. }
  31632. }
  31633. };
  31634. /**
  31635. * Indicates that image processing needs to be re-calculated for all submeshes.
  31636. */
  31637. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31638. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31639. };
  31640. /**
  31641. * Indicates that textures need to be re-calculated for all submeshes.
  31642. */
  31643. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31644. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31645. };
  31646. /**
  31647. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31648. */
  31649. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31650. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31651. };
  31652. /**
  31653. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31654. */
  31655. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31656. this._markAllSubMeshesAsDirty(function (defines) {
  31657. defines.markAsFresnelDirty();
  31658. defines.markAsMiscDirty();
  31659. });
  31660. };
  31661. /**
  31662. * Indicates that lights need to be re-calculated for all submeshes.
  31663. */
  31664. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31665. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31666. };
  31667. /**
  31668. * Indicates that attributes need to be re-calculated for all submeshes.
  31669. */
  31670. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31671. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31672. };
  31673. /**
  31674. * Indicates that misc needs to be re-calculated for all submeshes.
  31675. */
  31676. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31677. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31678. };
  31679. /**
  31680. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31681. */
  31682. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31683. this._markAllSubMeshesAsDirty(function (defines) {
  31684. defines.markAsTexturesDirty();
  31685. defines.markAsMiscDirty();
  31686. });
  31687. };
  31688. /**
  31689. * Disposes the material.
  31690. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31691. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31692. */
  31693. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31694. // Animations
  31695. this.getScene().stopAnimation(this);
  31696. // Remove from scene
  31697. var index = this._scene.materials.indexOf(this);
  31698. if (index >= 0) {
  31699. this._scene.materials.splice(index, 1);
  31700. }
  31701. // Remove from meshes
  31702. for (index = 0; index < this._scene.meshes.length; index++) {
  31703. var mesh = this._scene.meshes[index];
  31704. if (mesh.material === this) {
  31705. mesh.material = null;
  31706. if (mesh.geometry) {
  31707. var geometry = (mesh.geometry);
  31708. if (this.storeEffectOnSubMeshes) {
  31709. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31710. var subMesh = _a[_i];
  31711. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31712. if (forceDisposeEffect && subMesh._materialEffect) {
  31713. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31714. }
  31715. }
  31716. }
  31717. else {
  31718. geometry._releaseVertexArrayObject(this._effect);
  31719. }
  31720. }
  31721. }
  31722. }
  31723. this._uniformBuffer.dispose();
  31724. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31725. if (forceDisposeEffect && this._effect) {
  31726. if (!this.storeEffectOnSubMeshes) {
  31727. this._scene.getEngine()._releaseEffect(this._effect);
  31728. }
  31729. this._effect = null;
  31730. }
  31731. // Callback
  31732. this.onDisposeObservable.notifyObservers(this);
  31733. this.onDisposeObservable.clear();
  31734. this.onBindObservable.clear();
  31735. this.onUnBindObservable.clear();
  31736. };
  31737. /**
  31738. * Serializes this material.
  31739. * @returns - serialized material object.
  31740. */
  31741. Material.prototype.serialize = function () {
  31742. return BABYLON.SerializationHelper.Serialize(this);
  31743. };
  31744. /**
  31745. * Creates a MultiMaterial from parse MultiMaterial data.
  31746. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31747. * @param scene - BJS scene.
  31748. * @returns - MultiMaterial.
  31749. */
  31750. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31751. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31752. multiMaterial.id = parsedMultiMaterial.id;
  31753. if (BABYLON.Tags) {
  31754. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31755. }
  31756. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31757. var subMatId = parsedMultiMaterial.materials[matIndex];
  31758. if (subMatId) {
  31759. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31760. }
  31761. else {
  31762. multiMaterial.subMaterials.push(null);
  31763. }
  31764. }
  31765. return multiMaterial;
  31766. };
  31767. /**
  31768. * Creates a material from parsed material data.
  31769. * @param parsedMaterial - Parsed material data.
  31770. * @param scene - BJS scene.
  31771. * @param rootUrl - Root URL containing the material information.
  31772. * @returns - Parsed material.
  31773. */
  31774. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31775. if (!parsedMaterial.customType) {
  31776. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31777. }
  31778. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31779. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31780. if (!BABYLON.LegacyPBRMaterial) {
  31781. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31782. return;
  31783. }
  31784. }
  31785. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31786. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31787. ;
  31788. };
  31789. // Triangle views
  31790. Material._TriangleFillMode = 0;
  31791. Material._WireFrameFillMode = 1;
  31792. Material._PointFillMode = 2;
  31793. // Draw modes
  31794. Material._PointListDrawMode = 3;
  31795. Material._LineListDrawMode = 4;
  31796. Material._LineLoopDrawMode = 5;
  31797. Material._LineStripDrawMode = 6;
  31798. Material._TriangleStripDrawMode = 7;
  31799. Material._TriangleFanDrawMode = 8;
  31800. /**
  31801. * Stores the clock-wise side orientation.
  31802. */
  31803. Material._ClockWiseSideOrientation = 0;
  31804. /**
  31805. * Stores the counter clock-wise side orientation.
  31806. */
  31807. Material._CounterClockWiseSideOrientation = 1;
  31808. /**
  31809. * The dirty texture flag value.
  31810. */
  31811. Material._TextureDirtyFlag = 1;
  31812. /**
  31813. * The dirty light flag value.
  31814. */
  31815. Material._LightDirtyFlag = 2;
  31816. /**
  31817. * The dirty fresnel flag value.
  31818. */
  31819. Material._FresnelDirtyFlag = 4;
  31820. /**
  31821. * The dirty attribute flag value.
  31822. */
  31823. Material._AttributesDirtyFlag = 8;
  31824. /**
  31825. * The dirty misc flag value.
  31826. */
  31827. Material._MiscDirtyFlag = 16;
  31828. __decorate([
  31829. BABYLON.serialize()
  31830. ], Material.prototype, "id", void 0);
  31831. __decorate([
  31832. BABYLON.serialize()
  31833. ], Material.prototype, "name", void 0);
  31834. __decorate([
  31835. BABYLON.serialize()
  31836. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31837. __decorate([
  31838. BABYLON.serialize()
  31839. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31840. __decorate([
  31841. BABYLON.serialize()
  31842. ], Material.prototype, "state", void 0);
  31843. __decorate([
  31844. BABYLON.serialize("alpha")
  31845. ], Material.prototype, "_alpha", void 0);
  31846. __decorate([
  31847. BABYLON.serialize("backFaceCulling")
  31848. ], Material.prototype, "_backFaceCulling", void 0);
  31849. __decorate([
  31850. BABYLON.serialize()
  31851. ], Material.prototype, "sideOrientation", void 0);
  31852. __decorate([
  31853. BABYLON.serialize("alphaMode")
  31854. ], Material.prototype, "_alphaMode", void 0);
  31855. __decorate([
  31856. BABYLON.serialize()
  31857. ], Material.prototype, "_needDepthPrePass", void 0);
  31858. __decorate([
  31859. BABYLON.serialize()
  31860. ], Material.prototype, "disableDepthWrite", void 0);
  31861. __decorate([
  31862. BABYLON.serialize()
  31863. ], Material.prototype, "forceDepthWrite", void 0);
  31864. __decorate([
  31865. BABYLON.serialize()
  31866. ], Material.prototype, "separateCullingPass", void 0);
  31867. __decorate([
  31868. BABYLON.serialize("fogEnabled")
  31869. ], Material.prototype, "_fogEnabled", void 0);
  31870. __decorate([
  31871. BABYLON.serialize()
  31872. ], Material.prototype, "pointSize", void 0);
  31873. __decorate([
  31874. BABYLON.serialize()
  31875. ], Material.prototype, "zOffset", void 0);
  31876. __decorate([
  31877. BABYLON.serialize()
  31878. ], Material.prototype, "wireframe", null);
  31879. __decorate([
  31880. BABYLON.serialize()
  31881. ], Material.prototype, "pointsCloud", null);
  31882. __decorate([
  31883. BABYLON.serialize()
  31884. ], Material.prototype, "fillMode", null);
  31885. return Material;
  31886. }());
  31887. BABYLON.Material = Material;
  31888. })(BABYLON || (BABYLON = {}));
  31889. //# sourceMappingURL=babylon.material.js.map
  31890. var BABYLON;
  31891. (function (BABYLON) {
  31892. var UniformBuffer = /** @class */ (function () {
  31893. /**
  31894. * Uniform buffer objects.
  31895. *
  31896. * Handles blocks of uniform on the GPU.
  31897. *
  31898. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31899. *
  31900. * For more information, please refer to :
  31901. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31902. */
  31903. function UniformBuffer(engine, data, dynamic) {
  31904. this._engine = engine;
  31905. this._noUBO = !engine.supportsUniformBuffers;
  31906. this._dynamic = dynamic;
  31907. this._data = data || [];
  31908. this._uniformLocations = {};
  31909. this._uniformSizes = {};
  31910. this._uniformLocationPointer = 0;
  31911. this._needSync = false;
  31912. if (this._noUBO) {
  31913. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31914. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31915. this.updateFloat = this._updateFloatForEffect;
  31916. this.updateFloat2 = this._updateFloat2ForEffect;
  31917. this.updateFloat3 = this._updateFloat3ForEffect;
  31918. this.updateFloat4 = this._updateFloat4ForEffect;
  31919. this.updateMatrix = this._updateMatrixForEffect;
  31920. this.updateVector3 = this._updateVector3ForEffect;
  31921. this.updateVector4 = this._updateVector4ForEffect;
  31922. this.updateColor3 = this._updateColor3ForEffect;
  31923. this.updateColor4 = this._updateColor4ForEffect;
  31924. }
  31925. else {
  31926. this._engine._uniformBuffers.push(this);
  31927. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31928. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31929. this.updateFloat = this._updateFloatForUniform;
  31930. this.updateFloat2 = this._updateFloat2ForUniform;
  31931. this.updateFloat3 = this._updateFloat3ForUniform;
  31932. this.updateFloat4 = this._updateFloat4ForUniform;
  31933. this.updateMatrix = this._updateMatrixForUniform;
  31934. this.updateVector3 = this._updateVector3ForUniform;
  31935. this.updateVector4 = this._updateVector4ForUniform;
  31936. this.updateColor3 = this._updateColor3ForUniform;
  31937. this.updateColor4 = this._updateColor4ForUniform;
  31938. }
  31939. }
  31940. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31941. // Properties
  31942. /**
  31943. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31944. * or just falling back on setUniformXXX calls.
  31945. */
  31946. get: function () {
  31947. return !this._noUBO;
  31948. },
  31949. enumerable: true,
  31950. configurable: true
  31951. });
  31952. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31953. /**
  31954. * Indicates if the WebGL underlying uniform buffer is in sync
  31955. * with the javascript cache data.
  31956. */
  31957. get: function () {
  31958. return !this._needSync;
  31959. },
  31960. enumerable: true,
  31961. configurable: true
  31962. });
  31963. /**
  31964. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31965. * Also, a dynamic UniformBuffer will disable cache verification and always
  31966. * update the underlying WebGL uniform buffer to the GPU.
  31967. */
  31968. UniformBuffer.prototype.isDynamic = function () {
  31969. return this._dynamic !== undefined;
  31970. };
  31971. /**
  31972. * The data cache on JS side.
  31973. */
  31974. UniformBuffer.prototype.getData = function () {
  31975. return this._bufferData;
  31976. };
  31977. /**
  31978. * The underlying WebGL Uniform buffer.
  31979. */
  31980. UniformBuffer.prototype.getBuffer = function () {
  31981. return this._buffer;
  31982. };
  31983. /**
  31984. * std140 layout specifies how to align data within an UBO structure.
  31985. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31986. * for specs.
  31987. */
  31988. UniformBuffer.prototype._fillAlignment = function (size) {
  31989. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31990. // and 4x4 matrices
  31991. // TODO : change if other types are used
  31992. var alignment;
  31993. if (size <= 2) {
  31994. alignment = size;
  31995. }
  31996. else {
  31997. alignment = 4;
  31998. }
  31999. if ((this._uniformLocationPointer % alignment) !== 0) {
  32000. var oldPointer = this._uniformLocationPointer;
  32001. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32002. var diff = this._uniformLocationPointer - oldPointer;
  32003. for (var i = 0; i < diff; i++) {
  32004. this._data.push(0);
  32005. }
  32006. }
  32007. };
  32008. /**
  32009. * Adds an uniform in the buffer.
  32010. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32011. * for the layout to be correct !
  32012. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32013. * @param {number|number[]} size Data size, or data directly.
  32014. */
  32015. UniformBuffer.prototype.addUniform = function (name, size) {
  32016. if (this._noUBO) {
  32017. return;
  32018. }
  32019. if (this._uniformLocations[name] !== undefined) {
  32020. // Already existing uniform
  32021. return;
  32022. }
  32023. // This function must be called in the order of the shader layout !
  32024. // size can be the size of the uniform, or data directly
  32025. var data;
  32026. if (size instanceof Array) {
  32027. data = size;
  32028. size = data.length;
  32029. }
  32030. else {
  32031. size = size;
  32032. data = [];
  32033. // Fill with zeros
  32034. for (var i = 0; i < size; i++) {
  32035. data.push(0);
  32036. }
  32037. }
  32038. this._fillAlignment(size);
  32039. this._uniformSizes[name] = size;
  32040. this._uniformLocations[name] = this._uniformLocationPointer;
  32041. this._uniformLocationPointer += size;
  32042. for (var i = 0; i < size; i++) {
  32043. this._data.push(data[i]);
  32044. }
  32045. this._needSync = true;
  32046. };
  32047. /**
  32048. * Wrapper for addUniform.
  32049. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32050. * @param {Matrix} mat A 4x4 matrix.
  32051. */
  32052. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32053. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32054. };
  32055. /**
  32056. * Wrapper for addUniform.
  32057. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32058. * @param {number} x
  32059. * @param {number} y
  32060. */
  32061. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32062. var temp = [x, y];
  32063. this.addUniform(name, temp);
  32064. };
  32065. /**
  32066. * Wrapper for addUniform.
  32067. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32068. * @param {number} x
  32069. * @param {number} y
  32070. * @param {number} z
  32071. */
  32072. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32073. var temp = [x, y, z];
  32074. this.addUniform(name, temp);
  32075. };
  32076. /**
  32077. * Wrapper for addUniform.
  32078. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32079. * @param {Color3} color
  32080. */
  32081. UniformBuffer.prototype.addColor3 = function (name, color) {
  32082. var temp = new Array();
  32083. color.toArray(temp);
  32084. this.addUniform(name, temp);
  32085. };
  32086. /**
  32087. * Wrapper for addUniform.
  32088. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32089. * @param {Color3} color
  32090. * @param {number} alpha
  32091. */
  32092. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32093. var temp = new Array();
  32094. color.toArray(temp);
  32095. temp.push(alpha);
  32096. this.addUniform(name, temp);
  32097. };
  32098. /**
  32099. * Wrapper for addUniform.
  32100. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32101. * @param {Vector3} vector
  32102. */
  32103. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32104. var temp = new Array();
  32105. vector.toArray(temp);
  32106. this.addUniform(name, temp);
  32107. };
  32108. /**
  32109. * Wrapper for addUniform.
  32110. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32111. */
  32112. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32113. this.addUniform(name, 12);
  32114. };
  32115. /**
  32116. * Wrapper for addUniform.
  32117. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32118. */
  32119. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32120. this.addUniform(name, 8);
  32121. };
  32122. /**
  32123. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32124. */
  32125. UniformBuffer.prototype.create = function () {
  32126. if (this._noUBO) {
  32127. return;
  32128. }
  32129. if (this._buffer) {
  32130. return; // nothing to do
  32131. }
  32132. // See spec, alignment must be filled as a vec4
  32133. this._fillAlignment(4);
  32134. this._bufferData = new Float32Array(this._data);
  32135. this._rebuild();
  32136. this._needSync = true;
  32137. };
  32138. UniformBuffer.prototype._rebuild = function () {
  32139. if (this._noUBO) {
  32140. return;
  32141. }
  32142. if (this._dynamic) {
  32143. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32144. }
  32145. else {
  32146. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32147. }
  32148. };
  32149. /**
  32150. * Updates the WebGL Uniform Buffer on the GPU.
  32151. * If the `dynamic` flag is set to true, no cache comparison is done.
  32152. * Otherwise, the buffer will be updated only if the cache differs.
  32153. */
  32154. UniformBuffer.prototype.update = function () {
  32155. if (!this._buffer) {
  32156. this.create();
  32157. return;
  32158. }
  32159. if (!this._dynamic && !this._needSync) {
  32160. return;
  32161. }
  32162. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32163. this._needSync = false;
  32164. };
  32165. /**
  32166. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32167. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32168. * @param {number[]|Float32Array} data Flattened data
  32169. * @param {number} size Size of the data.
  32170. */
  32171. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32172. var location = this._uniformLocations[uniformName];
  32173. if (location === undefined) {
  32174. if (this._buffer) {
  32175. // Cannot add an uniform if the buffer is already created
  32176. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32177. return;
  32178. }
  32179. this.addUniform(uniformName, size);
  32180. location = this._uniformLocations[uniformName];
  32181. }
  32182. if (!this._buffer) {
  32183. this.create();
  32184. }
  32185. if (!this._dynamic) {
  32186. // Cache for static uniform buffers
  32187. var changed = false;
  32188. for (var i = 0; i < size; i++) {
  32189. if (this._bufferData[location + i] !== data[i]) {
  32190. changed = true;
  32191. this._bufferData[location + i] = data[i];
  32192. }
  32193. }
  32194. this._needSync = this._needSync || changed;
  32195. }
  32196. else {
  32197. // No cache for dynamic
  32198. for (var i = 0; i < size; i++) {
  32199. this._bufferData[location + i] = data[i];
  32200. }
  32201. }
  32202. };
  32203. // Update methods
  32204. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32205. // To match std140, matrix must be realigned
  32206. for (var i = 0; i < 3; i++) {
  32207. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32208. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32209. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32210. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32211. }
  32212. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32213. };
  32214. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32215. this._currentEffect.setMatrix3x3(name, matrix);
  32216. };
  32217. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32218. this._currentEffect.setMatrix2x2(name, matrix);
  32219. };
  32220. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32221. // To match std140, matrix must be realigned
  32222. for (var i = 0; i < 2; i++) {
  32223. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32224. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32225. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32226. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32227. }
  32228. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32229. };
  32230. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32231. this._currentEffect.setFloat(name, x);
  32232. };
  32233. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32234. UniformBuffer._tempBuffer[0] = x;
  32235. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32236. };
  32237. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32238. if (suffix === void 0) { suffix = ""; }
  32239. this._currentEffect.setFloat2(name + suffix, x, y);
  32240. };
  32241. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32242. if (suffix === void 0) { suffix = ""; }
  32243. UniformBuffer._tempBuffer[0] = x;
  32244. UniformBuffer._tempBuffer[1] = y;
  32245. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32246. };
  32247. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32248. if (suffix === void 0) { suffix = ""; }
  32249. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32250. };
  32251. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32252. if (suffix === void 0) { suffix = ""; }
  32253. UniformBuffer._tempBuffer[0] = x;
  32254. UniformBuffer._tempBuffer[1] = y;
  32255. UniformBuffer._tempBuffer[2] = z;
  32256. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32257. };
  32258. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32259. if (suffix === void 0) { suffix = ""; }
  32260. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32261. };
  32262. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32263. if (suffix === void 0) { suffix = ""; }
  32264. UniformBuffer._tempBuffer[0] = x;
  32265. UniformBuffer._tempBuffer[1] = y;
  32266. UniformBuffer._tempBuffer[2] = z;
  32267. UniformBuffer._tempBuffer[3] = w;
  32268. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32269. };
  32270. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32271. this._currentEffect.setMatrix(name, mat);
  32272. };
  32273. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32274. this.updateUniform(name, mat.toArray(), 16);
  32275. };
  32276. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32277. this._currentEffect.setVector3(name, vector);
  32278. };
  32279. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32280. vector.toArray(UniformBuffer._tempBuffer);
  32281. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32282. };
  32283. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32284. this._currentEffect.setVector4(name, vector);
  32285. };
  32286. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32287. vector.toArray(UniformBuffer._tempBuffer);
  32288. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32289. };
  32290. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32291. if (suffix === void 0) { suffix = ""; }
  32292. this._currentEffect.setColor3(name + suffix, color);
  32293. };
  32294. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32295. if (suffix === void 0) { suffix = ""; }
  32296. color.toArray(UniformBuffer._tempBuffer);
  32297. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32298. };
  32299. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32300. if (suffix === void 0) { suffix = ""; }
  32301. this._currentEffect.setColor4(name + suffix, color, alpha);
  32302. };
  32303. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32304. if (suffix === void 0) { suffix = ""; }
  32305. color.toArray(UniformBuffer._tempBuffer);
  32306. UniformBuffer._tempBuffer[3] = alpha;
  32307. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32308. };
  32309. /**
  32310. * Sets a sampler uniform on the effect.
  32311. * @param {string} name Name of the sampler.
  32312. * @param {Texture} texture
  32313. */
  32314. UniformBuffer.prototype.setTexture = function (name, texture) {
  32315. this._currentEffect.setTexture(name, texture);
  32316. };
  32317. /**
  32318. * Directly updates the value of the uniform in the cache AND on the GPU.
  32319. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32320. * @param {number[]|Float32Array} data Flattened data
  32321. */
  32322. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32323. this.updateUniform(uniformName, data, data.length);
  32324. this.update();
  32325. };
  32326. /**
  32327. * Binds this uniform buffer to an effect.
  32328. * @param {Effect} effect
  32329. * @param {string} name Name of the uniform block in the shader.
  32330. */
  32331. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32332. this._currentEffect = effect;
  32333. if (this._noUBO || !this._buffer) {
  32334. return;
  32335. }
  32336. effect.bindUniformBuffer(this._buffer, name);
  32337. };
  32338. /**
  32339. * Disposes the uniform buffer.
  32340. */
  32341. UniformBuffer.prototype.dispose = function () {
  32342. if (this._noUBO) {
  32343. return;
  32344. }
  32345. var index = this._engine._uniformBuffers.indexOf(this);
  32346. if (index !== -1) {
  32347. this._engine._uniformBuffers.splice(index, 1);
  32348. }
  32349. if (!this._buffer) {
  32350. return;
  32351. }
  32352. if (this._engine._releaseBuffer(this._buffer)) {
  32353. this._buffer = null;
  32354. }
  32355. };
  32356. // Pool for avoiding memory leaks
  32357. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32358. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32359. return UniformBuffer;
  32360. }());
  32361. BABYLON.UniformBuffer = UniformBuffer;
  32362. })(BABYLON || (BABYLON = {}));
  32363. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32364. var BABYLON;
  32365. (function (BABYLON) {
  32366. var VertexData = /** @class */ (function () {
  32367. function VertexData() {
  32368. }
  32369. VertexData.prototype.set = function (data, kind) {
  32370. switch (kind) {
  32371. case BABYLON.VertexBuffer.PositionKind:
  32372. this.positions = data;
  32373. break;
  32374. case BABYLON.VertexBuffer.NormalKind:
  32375. this.normals = data;
  32376. break;
  32377. case BABYLON.VertexBuffer.TangentKind:
  32378. this.tangents = data;
  32379. break;
  32380. case BABYLON.VertexBuffer.UVKind:
  32381. this.uvs = data;
  32382. break;
  32383. case BABYLON.VertexBuffer.UV2Kind:
  32384. this.uvs2 = data;
  32385. break;
  32386. case BABYLON.VertexBuffer.UV3Kind:
  32387. this.uvs3 = data;
  32388. break;
  32389. case BABYLON.VertexBuffer.UV4Kind:
  32390. this.uvs4 = data;
  32391. break;
  32392. case BABYLON.VertexBuffer.UV5Kind:
  32393. this.uvs5 = data;
  32394. break;
  32395. case BABYLON.VertexBuffer.UV6Kind:
  32396. this.uvs6 = data;
  32397. break;
  32398. case BABYLON.VertexBuffer.ColorKind:
  32399. this.colors = data;
  32400. break;
  32401. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32402. this.matricesIndices = data;
  32403. break;
  32404. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32405. this.matricesWeights = data;
  32406. break;
  32407. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32408. this.matricesIndicesExtra = data;
  32409. break;
  32410. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32411. this.matricesWeightsExtra = data;
  32412. break;
  32413. }
  32414. };
  32415. /**
  32416. * Associates the vertexData to the passed Mesh.
  32417. * Sets it as updatable or not (default `false`).
  32418. * Returns the VertexData.
  32419. */
  32420. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32421. this._applyTo(mesh, updatable);
  32422. return this;
  32423. };
  32424. /**
  32425. * Associates the vertexData to the passed Geometry.
  32426. * Sets it as updatable or not (default `false`).
  32427. * Returns the VertexData.
  32428. */
  32429. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32430. this._applyTo(geometry, updatable);
  32431. return this;
  32432. };
  32433. /**
  32434. * Updates the associated mesh.
  32435. * Returns the VertexData.
  32436. */
  32437. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32438. this._update(mesh);
  32439. return this;
  32440. };
  32441. /**
  32442. * Updates the associated geometry.
  32443. * Returns the VertexData.
  32444. */
  32445. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32446. this._update(geometry);
  32447. return this;
  32448. };
  32449. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32450. if (updatable === void 0) { updatable = false; }
  32451. if (this.positions) {
  32452. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32453. }
  32454. if (this.normals) {
  32455. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32456. }
  32457. if (this.tangents) {
  32458. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32459. }
  32460. if (this.uvs) {
  32461. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32462. }
  32463. if (this.uvs2) {
  32464. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32465. }
  32466. if (this.uvs3) {
  32467. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32468. }
  32469. if (this.uvs4) {
  32470. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32471. }
  32472. if (this.uvs5) {
  32473. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32474. }
  32475. if (this.uvs6) {
  32476. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32477. }
  32478. if (this.colors) {
  32479. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32480. }
  32481. if (this.matricesIndices) {
  32482. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32483. }
  32484. if (this.matricesWeights) {
  32485. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32486. }
  32487. if (this.matricesIndicesExtra) {
  32488. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32489. }
  32490. if (this.matricesWeightsExtra) {
  32491. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32492. }
  32493. if (this.indices) {
  32494. meshOrGeometry.setIndices(this.indices, null, updatable);
  32495. }
  32496. return this;
  32497. };
  32498. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32499. if (this.positions) {
  32500. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32501. }
  32502. if (this.normals) {
  32503. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32504. }
  32505. if (this.tangents) {
  32506. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32507. }
  32508. if (this.uvs) {
  32509. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32510. }
  32511. if (this.uvs2) {
  32512. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32513. }
  32514. if (this.uvs3) {
  32515. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32516. }
  32517. if (this.uvs4) {
  32518. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32519. }
  32520. if (this.uvs5) {
  32521. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32522. }
  32523. if (this.uvs6) {
  32524. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32525. }
  32526. if (this.colors) {
  32527. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32528. }
  32529. if (this.matricesIndices) {
  32530. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32531. }
  32532. if (this.matricesWeights) {
  32533. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32534. }
  32535. if (this.matricesIndicesExtra) {
  32536. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32537. }
  32538. if (this.matricesWeightsExtra) {
  32539. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32540. }
  32541. if (this.indices) {
  32542. meshOrGeometry.setIndices(this.indices, null);
  32543. }
  32544. return this;
  32545. };
  32546. /**
  32547. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32548. * Returns the VertexData.
  32549. */
  32550. VertexData.prototype.transform = function (matrix) {
  32551. var transformed = BABYLON.Vector3.Zero();
  32552. var index;
  32553. if (this.positions) {
  32554. var position = BABYLON.Vector3.Zero();
  32555. for (index = 0; index < this.positions.length; index += 3) {
  32556. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32557. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32558. this.positions[index] = transformed.x;
  32559. this.positions[index + 1] = transformed.y;
  32560. this.positions[index + 2] = transformed.z;
  32561. }
  32562. }
  32563. if (this.normals) {
  32564. var normal = BABYLON.Vector3.Zero();
  32565. for (index = 0; index < this.normals.length; index += 3) {
  32566. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32567. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32568. this.normals[index] = transformed.x;
  32569. this.normals[index + 1] = transformed.y;
  32570. this.normals[index + 2] = transformed.z;
  32571. }
  32572. }
  32573. if (this.tangents) {
  32574. var tangent = BABYLON.Vector4.Zero();
  32575. var tangentTransformed = BABYLON.Vector4.Zero();
  32576. for (index = 0; index < this.tangents.length; index += 4) {
  32577. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32578. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32579. this.tangents[index] = tangentTransformed.x;
  32580. this.tangents[index + 1] = tangentTransformed.y;
  32581. this.tangents[index + 2] = tangentTransformed.z;
  32582. this.tangents[index + 3] = tangentTransformed.w;
  32583. }
  32584. }
  32585. return this;
  32586. };
  32587. /**
  32588. * Merges the passed VertexData into the current one.
  32589. * Returns the modified VertexData.
  32590. */
  32591. VertexData.prototype.merge = function (other) {
  32592. this._validate();
  32593. other._validate();
  32594. if (!this.normals !== !other.normals ||
  32595. !this.tangents !== !other.tangents ||
  32596. !this.uvs !== !other.uvs ||
  32597. !this.uvs2 !== !other.uvs2 ||
  32598. !this.uvs3 !== !other.uvs3 ||
  32599. !this.uvs4 !== !other.uvs4 ||
  32600. !this.uvs5 !== !other.uvs5 ||
  32601. !this.uvs6 !== !other.uvs6 ||
  32602. !this.colors !== !other.colors ||
  32603. !this.matricesIndices !== !other.matricesIndices ||
  32604. !this.matricesWeights !== !other.matricesWeights ||
  32605. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32606. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32607. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32608. }
  32609. if (other.indices) {
  32610. if (!this.indices) {
  32611. this.indices = [];
  32612. }
  32613. var offset = this.positions ? this.positions.length / 3 : 0;
  32614. for (var index = 0; index < other.indices.length; index++) {
  32615. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32616. this.indices.push(other.indices[index] + offset);
  32617. }
  32618. }
  32619. this.positions = this._mergeElement(this.positions, other.positions);
  32620. this.normals = this._mergeElement(this.normals, other.normals);
  32621. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32622. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32623. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32624. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32625. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32626. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32627. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32628. this.colors = this._mergeElement(this.colors, other.colors);
  32629. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32630. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32631. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32632. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32633. return this;
  32634. };
  32635. VertexData.prototype._mergeElement = function (source, other) {
  32636. if (!source) {
  32637. return other;
  32638. }
  32639. if (!other) {
  32640. return source;
  32641. }
  32642. var len = other.length + source.length;
  32643. var isSrcTypedArray = source instanceof Float32Array;
  32644. var isOthTypedArray = other instanceof Float32Array;
  32645. // use non-loop method when the source is Float32Array
  32646. if (isSrcTypedArray) {
  32647. var ret32 = new Float32Array(len);
  32648. ret32.set(source);
  32649. ret32.set(other, source.length);
  32650. return ret32;
  32651. // source is number[], when other is also use concat
  32652. }
  32653. else if (!isOthTypedArray) {
  32654. return source.concat(other);
  32655. // source is a number[], but other is a Float32Array, loop required
  32656. }
  32657. else {
  32658. var ret = source.slice(0); // copy source to a separate array
  32659. for (var i = 0, len = other.length; i < len; i++) {
  32660. ret.push(other[i]);
  32661. }
  32662. return ret;
  32663. }
  32664. };
  32665. VertexData.prototype._validate = function () {
  32666. if (!this.positions) {
  32667. throw new Error("Positions are required");
  32668. }
  32669. var getElementCount = function (kind, values) {
  32670. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32671. if ((values.length % stride) !== 0) {
  32672. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32673. }
  32674. return values.length / stride;
  32675. };
  32676. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32677. var validateElementCount = function (kind, values) {
  32678. var elementCount = getElementCount(kind, values);
  32679. if (elementCount !== positionsElementCount) {
  32680. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32681. }
  32682. };
  32683. if (this.normals)
  32684. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32685. if (this.tangents)
  32686. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32687. if (this.uvs)
  32688. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32689. if (this.uvs2)
  32690. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32691. if (this.uvs3)
  32692. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32693. if (this.uvs4)
  32694. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32695. if (this.uvs5)
  32696. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32697. if (this.uvs6)
  32698. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32699. if (this.colors)
  32700. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32701. if (this.matricesIndices)
  32702. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32703. if (this.matricesWeights)
  32704. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32705. if (this.matricesIndicesExtra)
  32706. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32707. if (this.matricesWeightsExtra)
  32708. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32709. };
  32710. /**
  32711. * Serializes the VertexData.
  32712. * Returns a serialized object.
  32713. */
  32714. VertexData.prototype.serialize = function () {
  32715. var serializationObject = this.serialize();
  32716. if (this.positions) {
  32717. serializationObject.positions = this.positions;
  32718. }
  32719. if (this.normals) {
  32720. serializationObject.normals = this.normals;
  32721. }
  32722. if (this.tangents) {
  32723. serializationObject.tangents = this.tangents;
  32724. }
  32725. if (this.uvs) {
  32726. serializationObject.uvs = this.uvs;
  32727. }
  32728. if (this.uvs2) {
  32729. serializationObject.uvs2 = this.uvs2;
  32730. }
  32731. if (this.uvs3) {
  32732. serializationObject.uvs3 = this.uvs3;
  32733. }
  32734. if (this.uvs4) {
  32735. serializationObject.uvs4 = this.uvs4;
  32736. }
  32737. if (this.uvs5) {
  32738. serializationObject.uvs5 = this.uvs5;
  32739. }
  32740. if (this.uvs6) {
  32741. serializationObject.uvs6 = this.uvs6;
  32742. }
  32743. if (this.colors) {
  32744. serializationObject.colors = this.colors;
  32745. }
  32746. if (this.matricesIndices) {
  32747. serializationObject.matricesIndices = this.matricesIndices;
  32748. serializationObject.matricesIndices._isExpanded = true;
  32749. }
  32750. if (this.matricesWeights) {
  32751. serializationObject.matricesWeights = this.matricesWeights;
  32752. }
  32753. if (this.matricesIndicesExtra) {
  32754. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32755. serializationObject.matricesIndicesExtra._isExpanded = true;
  32756. }
  32757. if (this.matricesWeightsExtra) {
  32758. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32759. }
  32760. serializationObject.indices = this.indices;
  32761. return serializationObject;
  32762. };
  32763. // Statics
  32764. /**
  32765. * Returns the object VertexData associated to the passed mesh.
  32766. */
  32767. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32768. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32769. };
  32770. /**
  32771. * Returns the object VertexData associated to the passed geometry.
  32772. */
  32773. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32774. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32775. };
  32776. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32777. var result = new VertexData();
  32778. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32779. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32780. }
  32781. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32782. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32783. }
  32784. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32785. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32786. }
  32787. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32788. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32789. }
  32790. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32791. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32792. }
  32793. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32794. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32795. }
  32796. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32797. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32798. }
  32799. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32800. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32801. }
  32802. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32803. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32804. }
  32805. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32806. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32807. }
  32808. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32809. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32810. }
  32811. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32812. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32813. }
  32814. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32815. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32816. }
  32817. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32818. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32819. }
  32820. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32821. return result;
  32822. };
  32823. /**
  32824. * Creates the vertexData of the Ribbon.
  32825. */
  32826. VertexData.CreateRibbon = function (options) {
  32827. var pathArray = options.pathArray;
  32828. var closeArray = options.closeArray || false;
  32829. var closePath = options.closePath || false;
  32830. var invertUV = options.invertUV || false;
  32831. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32832. var offset = options.offset || defaultOffset;
  32833. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32834. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32835. var customUV = options.uvs;
  32836. var customColors = options.colors;
  32837. var positions = [];
  32838. var indices = [];
  32839. var normals = [];
  32840. var uvs = [];
  32841. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32842. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32843. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32844. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32845. var minlg; // minimal length among all paths from pathArray
  32846. var lg = []; // array of path lengths : nb of vertex per path
  32847. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32848. var p; // path iterator
  32849. var i; // point iterator
  32850. var j; // point iterator
  32851. // if single path in pathArray
  32852. if (pathArray.length < 2) {
  32853. var ar1 = [];
  32854. var ar2 = [];
  32855. for (i = 0; i < pathArray[0].length - offset; i++) {
  32856. ar1.push(pathArray[0][i]);
  32857. ar2.push(pathArray[0][i + offset]);
  32858. }
  32859. pathArray = [ar1, ar2];
  32860. }
  32861. // positions and horizontal distances (u)
  32862. var idc = 0;
  32863. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32864. var path;
  32865. var l;
  32866. minlg = pathArray[0].length;
  32867. var vectlg;
  32868. var dist;
  32869. for (p = 0; p < pathArray.length; p++) {
  32870. uTotalDistance[p] = 0;
  32871. us[p] = [0];
  32872. path = pathArray[p];
  32873. l = path.length;
  32874. minlg = (minlg < l) ? minlg : l;
  32875. j = 0;
  32876. while (j < l) {
  32877. positions.push(path[j].x, path[j].y, path[j].z);
  32878. if (j > 0) {
  32879. vectlg = path[j].subtract(path[j - 1]).length();
  32880. dist = vectlg + uTotalDistance[p];
  32881. us[p].push(dist);
  32882. uTotalDistance[p] = dist;
  32883. }
  32884. j++;
  32885. }
  32886. if (closePath) {
  32887. j--;
  32888. positions.push(path[0].x, path[0].y, path[0].z);
  32889. vectlg = path[j].subtract(path[0]).length();
  32890. dist = vectlg + uTotalDistance[p];
  32891. us[p].push(dist);
  32892. uTotalDistance[p] = dist;
  32893. }
  32894. lg[p] = l + closePathCorr;
  32895. idx[p] = idc;
  32896. idc += (l + closePathCorr);
  32897. }
  32898. // vertical distances (v)
  32899. var path1;
  32900. var path2;
  32901. var vertex1 = null;
  32902. var vertex2 = null;
  32903. for (i = 0; i < minlg + closePathCorr; i++) {
  32904. vTotalDistance[i] = 0;
  32905. vs[i] = [0];
  32906. for (p = 0; p < pathArray.length - 1; p++) {
  32907. path1 = pathArray[p];
  32908. path2 = pathArray[p + 1];
  32909. if (i === minlg) {
  32910. vertex1 = path1[0];
  32911. vertex2 = path2[0];
  32912. }
  32913. else {
  32914. vertex1 = path1[i];
  32915. vertex2 = path2[i];
  32916. }
  32917. vectlg = vertex2.subtract(vertex1).length();
  32918. dist = vectlg + vTotalDistance[i];
  32919. vs[i].push(dist);
  32920. vTotalDistance[i] = dist;
  32921. }
  32922. if (closeArray && vertex2 && vertex1) {
  32923. path1 = pathArray[p];
  32924. path2 = pathArray[0];
  32925. if (i === minlg) {
  32926. vertex2 = path2[0];
  32927. }
  32928. vectlg = vertex2.subtract(vertex1).length();
  32929. dist = vectlg + vTotalDistance[i];
  32930. vTotalDistance[i] = dist;
  32931. }
  32932. }
  32933. // uvs
  32934. var u;
  32935. var v;
  32936. if (customUV) {
  32937. for (p = 0; p < customUV.length; p++) {
  32938. uvs.push(customUV[p].x, customUV[p].y);
  32939. }
  32940. }
  32941. else {
  32942. for (p = 0; p < pathArray.length; p++) {
  32943. for (i = 0; i < minlg + closePathCorr; i++) {
  32944. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32945. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32946. if (invertUV) {
  32947. uvs.push(v, u);
  32948. }
  32949. else {
  32950. uvs.push(u, v);
  32951. }
  32952. }
  32953. }
  32954. }
  32955. // indices
  32956. p = 0; // path index
  32957. var pi = 0; // positions array index
  32958. var l1 = lg[p] - 1; // path1 length
  32959. var l2 = lg[p + 1] - 1; // path2 length
  32960. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32961. var shft = idx[1] - idx[0]; // shift
  32962. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32963. while (pi <= min && p < path1nb) {
  32964. // 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
  32965. indices.push(pi, pi + shft, pi + 1);
  32966. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32967. pi += 1;
  32968. if (pi === min) {
  32969. p++;
  32970. if (p === lg.length - 1) {
  32971. shft = idx[0] - idx[p];
  32972. l1 = lg[p] - 1;
  32973. l2 = lg[0] - 1;
  32974. }
  32975. else {
  32976. shft = idx[p + 1] - idx[p];
  32977. l1 = lg[p] - 1;
  32978. l2 = lg[p + 1] - 1;
  32979. }
  32980. pi = idx[p];
  32981. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32982. }
  32983. }
  32984. // normals
  32985. VertexData.ComputeNormals(positions, indices, normals);
  32986. if (closePath) {
  32987. var indexFirst = 0;
  32988. var indexLast = 0;
  32989. for (p = 0; p < pathArray.length; p++) {
  32990. indexFirst = idx[p] * 3;
  32991. if (p + 1 < pathArray.length) {
  32992. indexLast = (idx[p + 1] - 1) * 3;
  32993. }
  32994. else {
  32995. indexLast = normals.length - 3;
  32996. }
  32997. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32998. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32999. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33000. normals[indexLast] = normals[indexFirst];
  33001. normals[indexLast + 1] = normals[indexFirst + 1];
  33002. normals[indexLast + 2] = normals[indexFirst + 2];
  33003. }
  33004. }
  33005. // sides
  33006. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33007. // Colors
  33008. var colors = null;
  33009. if (customColors) {
  33010. colors = new Float32Array(customColors.length * 4);
  33011. for (var c = 0; c < customColors.length; c++) {
  33012. colors[c * 4] = customColors[c].r;
  33013. colors[c * 4 + 1] = customColors[c].g;
  33014. colors[c * 4 + 2] = customColors[c].b;
  33015. colors[c * 4 + 3] = customColors[c].a;
  33016. }
  33017. }
  33018. // Result
  33019. var vertexData = new VertexData();
  33020. var positions32 = new Float32Array(positions);
  33021. var normals32 = new Float32Array(normals);
  33022. var uvs32 = new Float32Array(uvs);
  33023. vertexData.indices = indices;
  33024. vertexData.positions = positions32;
  33025. vertexData.normals = normals32;
  33026. vertexData.uvs = uvs32;
  33027. if (colors) {
  33028. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33029. }
  33030. if (closePath) {
  33031. vertexData._idx = idx;
  33032. }
  33033. return vertexData;
  33034. };
  33035. /**
  33036. * Creates the VertexData of the Box.
  33037. */
  33038. VertexData.CreateBox = function (options) {
  33039. var normalsSource = [
  33040. new BABYLON.Vector3(0, 0, 1),
  33041. new BABYLON.Vector3(0, 0, -1),
  33042. new BABYLON.Vector3(1, 0, 0),
  33043. new BABYLON.Vector3(-1, 0, 0),
  33044. new BABYLON.Vector3(0, 1, 0),
  33045. new BABYLON.Vector3(0, -1, 0)
  33046. ];
  33047. var indices = [];
  33048. var positions = [];
  33049. var normals = [];
  33050. var uvs = [];
  33051. var width = options.width || options.size || 1;
  33052. var height = options.height || options.size || 1;
  33053. var depth = options.depth || options.size || 1;
  33054. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33055. var faceUV = options.faceUV || new Array(6);
  33056. var faceColors = options.faceColors;
  33057. var colors = [];
  33058. // default face colors and UV if undefined
  33059. for (var f = 0; f < 6; f++) {
  33060. if (faceUV[f] === undefined) {
  33061. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33062. }
  33063. if (faceColors && faceColors[f] === undefined) {
  33064. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33065. }
  33066. }
  33067. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33068. // Create each face in turn.
  33069. for (var index = 0; index < normalsSource.length; index++) {
  33070. var normal = normalsSource[index];
  33071. // Get two vectors perpendicular to the face normal and to each other.
  33072. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33073. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33074. // Six indices (two triangles) per face.
  33075. var verticesLength = positions.length / 3;
  33076. indices.push(verticesLength);
  33077. indices.push(verticesLength + 1);
  33078. indices.push(verticesLength + 2);
  33079. indices.push(verticesLength);
  33080. indices.push(verticesLength + 2);
  33081. indices.push(verticesLength + 3);
  33082. // Four vertices per face.
  33083. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33084. positions.push(vertex.x, vertex.y, vertex.z);
  33085. normals.push(normal.x, normal.y, normal.z);
  33086. uvs.push(faceUV[index].z, faceUV[index].w);
  33087. if (faceColors) {
  33088. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33089. }
  33090. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33091. positions.push(vertex.x, vertex.y, vertex.z);
  33092. normals.push(normal.x, normal.y, normal.z);
  33093. uvs.push(faceUV[index].x, faceUV[index].w);
  33094. if (faceColors) {
  33095. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33096. }
  33097. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33098. positions.push(vertex.x, vertex.y, vertex.z);
  33099. normals.push(normal.x, normal.y, normal.z);
  33100. uvs.push(faceUV[index].x, faceUV[index].y);
  33101. if (faceColors) {
  33102. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33103. }
  33104. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33105. positions.push(vertex.x, vertex.y, vertex.z);
  33106. normals.push(normal.x, normal.y, normal.z);
  33107. uvs.push(faceUV[index].z, faceUV[index].y);
  33108. if (faceColors) {
  33109. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33110. }
  33111. }
  33112. // sides
  33113. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33114. // Result
  33115. var vertexData = new VertexData();
  33116. vertexData.indices = indices;
  33117. vertexData.positions = positions;
  33118. vertexData.normals = normals;
  33119. vertexData.uvs = uvs;
  33120. if (faceColors) {
  33121. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33122. vertexData.colors = totalColors;
  33123. }
  33124. return vertexData;
  33125. };
  33126. /**
  33127. * Creates the VertexData of the Sphere.
  33128. */
  33129. VertexData.CreateSphere = function (options) {
  33130. var segments = options.segments || 32;
  33131. var diameterX = options.diameterX || options.diameter || 1;
  33132. var diameterY = options.diameterY || options.diameter || 1;
  33133. var diameterZ = options.diameterZ || options.diameter || 1;
  33134. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33135. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33136. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33137. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33138. var totalZRotationSteps = 2 + segments;
  33139. var totalYRotationSteps = 2 * totalZRotationSteps;
  33140. var indices = [];
  33141. var positions = [];
  33142. var normals = [];
  33143. var uvs = [];
  33144. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33145. var normalizedZ = zRotationStep / totalZRotationSteps;
  33146. var angleZ = normalizedZ * Math.PI * slice;
  33147. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33148. var normalizedY = yRotationStep / totalYRotationSteps;
  33149. var angleY = normalizedY * Math.PI * 2 * arc;
  33150. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33151. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33152. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33153. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33154. var vertex = complete.multiply(radius);
  33155. var normal = complete.divide(radius).normalize();
  33156. positions.push(vertex.x, vertex.y, vertex.z);
  33157. normals.push(normal.x, normal.y, normal.z);
  33158. uvs.push(normalizedY, normalizedZ);
  33159. }
  33160. if (zRotationStep > 0) {
  33161. var verticesCount = positions.length / 3;
  33162. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33163. indices.push((firstIndex));
  33164. indices.push((firstIndex + 1));
  33165. indices.push(firstIndex + totalYRotationSteps + 1);
  33166. indices.push((firstIndex + totalYRotationSteps + 1));
  33167. indices.push((firstIndex + 1));
  33168. indices.push((firstIndex + totalYRotationSteps + 2));
  33169. }
  33170. }
  33171. }
  33172. // Sides
  33173. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33174. // Result
  33175. var vertexData = new VertexData();
  33176. vertexData.indices = indices;
  33177. vertexData.positions = positions;
  33178. vertexData.normals = normals;
  33179. vertexData.uvs = uvs;
  33180. return vertexData;
  33181. };
  33182. /**
  33183. * Creates the VertexData of the Cylinder or Cone.
  33184. */
  33185. VertexData.CreateCylinder = function (options) {
  33186. var height = options.height || 2;
  33187. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33188. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33189. var tessellation = options.tessellation || 24;
  33190. var subdivisions = options.subdivisions || 1;
  33191. var hasRings = options.hasRings ? true : false;
  33192. var enclose = options.enclose ? true : false;
  33193. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33194. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33195. var faceUV = options.faceUV || new Array(3);
  33196. var faceColors = options.faceColors;
  33197. // default face colors and UV if undefined
  33198. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33199. var ringNb = (hasRings) ? subdivisions : 1;
  33200. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33201. var f;
  33202. for (f = 0; f < surfaceNb; f++) {
  33203. if (faceColors && faceColors[f] === undefined) {
  33204. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33205. }
  33206. }
  33207. for (f = 0; f < surfaceNb; f++) {
  33208. if (faceUV && faceUV[f] === undefined) {
  33209. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33210. }
  33211. }
  33212. var indices = new Array();
  33213. var positions = new Array();
  33214. var normals = new Array();
  33215. var uvs = new Array();
  33216. var colors = new Array();
  33217. var angle_step = Math.PI * 2 * arc / tessellation;
  33218. var angle;
  33219. var h;
  33220. var radius;
  33221. var tan = (diameterBottom - diameterTop) / 2 / height;
  33222. var ringVertex = BABYLON.Vector3.Zero();
  33223. var ringNormal = BABYLON.Vector3.Zero();
  33224. var ringFirstVertex = BABYLON.Vector3.Zero();
  33225. var ringFirstNormal = BABYLON.Vector3.Zero();
  33226. var quadNormal = BABYLON.Vector3.Zero();
  33227. var Y = BABYLON.Axis.Y;
  33228. // positions, normals, uvs
  33229. var i;
  33230. var j;
  33231. var r;
  33232. var ringIdx = 1;
  33233. var s = 1; // surface index
  33234. var cs = 0;
  33235. var v = 0;
  33236. for (i = 0; i <= subdivisions; i++) {
  33237. h = i / subdivisions;
  33238. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33239. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33240. for (r = 0; r < ringIdx; r++) {
  33241. if (hasRings) {
  33242. s += r;
  33243. }
  33244. if (enclose) {
  33245. s += 2 * r;
  33246. }
  33247. for (j = 0; j <= tessellation; j++) {
  33248. angle = j * angle_step;
  33249. // position
  33250. ringVertex.x = Math.cos(-angle) * radius;
  33251. ringVertex.y = -height / 2 + h * height;
  33252. ringVertex.z = Math.sin(-angle) * radius;
  33253. // normal
  33254. if (diameterTop === 0 && i === subdivisions) {
  33255. // if no top cap, reuse former normals
  33256. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33257. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33258. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33259. }
  33260. else {
  33261. ringNormal.x = ringVertex.x;
  33262. ringNormal.z = ringVertex.z;
  33263. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33264. ringNormal.normalize();
  33265. }
  33266. // keep first ring vertex values for enclose
  33267. if (j === 0) {
  33268. ringFirstVertex.copyFrom(ringVertex);
  33269. ringFirstNormal.copyFrom(ringNormal);
  33270. }
  33271. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33272. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33273. if (hasRings) {
  33274. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33275. }
  33276. else {
  33277. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33278. }
  33279. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33280. if (faceColors) {
  33281. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33282. }
  33283. }
  33284. // if enclose, add four vertices and their dedicated normals
  33285. if (arc !== 1 && enclose) {
  33286. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33287. positions.push(0, ringVertex.y, 0);
  33288. positions.push(0, ringVertex.y, 0);
  33289. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33290. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33291. quadNormal.normalize();
  33292. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33293. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33294. quadNormal.normalize();
  33295. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33296. if (hasRings) {
  33297. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33298. }
  33299. else {
  33300. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33301. }
  33302. uvs.push(faceUV[s + 1].x, v);
  33303. uvs.push(faceUV[s + 1].z, v);
  33304. if (hasRings) {
  33305. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33306. }
  33307. else {
  33308. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33309. }
  33310. uvs.push(faceUV[s + 2].x, v);
  33311. uvs.push(faceUV[s + 2].z, v);
  33312. if (faceColors) {
  33313. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33314. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33315. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33316. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33317. }
  33318. }
  33319. if (cs !== s) {
  33320. cs = s;
  33321. }
  33322. }
  33323. }
  33324. // indices
  33325. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33326. var s;
  33327. i = 0;
  33328. for (s = 0; s < subdivisions; s++) {
  33329. var i0 = 0;
  33330. var i1 = 0;
  33331. var i2 = 0;
  33332. var i3 = 0;
  33333. for (j = 0; j < tessellation; j++) {
  33334. i0 = i * (e + 1) + j;
  33335. i1 = (i + 1) * (e + 1) + j;
  33336. i2 = i * (e + 1) + (j + 1);
  33337. i3 = (i + 1) * (e + 1) + (j + 1);
  33338. indices.push(i0, i1, i2);
  33339. indices.push(i3, i2, i1);
  33340. }
  33341. if (arc !== 1 && enclose) {
  33342. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33343. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33344. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33345. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33346. }
  33347. i = (hasRings) ? (i + 2) : (i + 1);
  33348. }
  33349. // Caps
  33350. var createCylinderCap = function (isTop) {
  33351. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33352. if (radius === 0) {
  33353. return;
  33354. }
  33355. // Cap positions, normals & uvs
  33356. var angle;
  33357. var circleVector;
  33358. var i;
  33359. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33360. var c = null;
  33361. if (faceColors) {
  33362. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33363. }
  33364. // cap center
  33365. var vbase = positions.length / 3;
  33366. var offset = isTop ? height / 2 : -height / 2;
  33367. var center = new BABYLON.Vector3(0, offset, 0);
  33368. positions.push(center.x, center.y, center.z);
  33369. normals.push(0, isTop ? 1 : -1, 0);
  33370. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33371. if (c) {
  33372. colors.push(c.r, c.g, c.b, c.a);
  33373. }
  33374. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33375. for (i = 0; i <= tessellation; i++) {
  33376. angle = Math.PI * 2 * i * arc / tessellation;
  33377. var cos = Math.cos(-angle);
  33378. var sin = Math.sin(-angle);
  33379. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33380. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33381. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33382. normals.push(0, isTop ? 1 : -1, 0);
  33383. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33384. if (c) {
  33385. colors.push(c.r, c.g, c.b, c.a);
  33386. }
  33387. }
  33388. // Cap indices
  33389. for (i = 0; i < tessellation; i++) {
  33390. if (!isTop) {
  33391. indices.push(vbase);
  33392. indices.push(vbase + (i + 1));
  33393. indices.push(vbase + (i + 2));
  33394. }
  33395. else {
  33396. indices.push(vbase);
  33397. indices.push(vbase + (i + 2));
  33398. indices.push(vbase + (i + 1));
  33399. }
  33400. }
  33401. };
  33402. // add caps to geometry
  33403. createCylinderCap(false);
  33404. createCylinderCap(true);
  33405. // Sides
  33406. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33407. var vertexData = new VertexData();
  33408. vertexData.indices = indices;
  33409. vertexData.positions = positions;
  33410. vertexData.normals = normals;
  33411. vertexData.uvs = uvs;
  33412. if (faceColors) {
  33413. vertexData.colors = colors;
  33414. }
  33415. return vertexData;
  33416. };
  33417. /**
  33418. * Creates the VertexData of the Torus.
  33419. */
  33420. VertexData.CreateTorus = function (options) {
  33421. var indices = [];
  33422. var positions = [];
  33423. var normals = [];
  33424. var uvs = [];
  33425. var diameter = options.diameter || 1;
  33426. var thickness = options.thickness || 0.5;
  33427. var tessellation = options.tessellation || 16;
  33428. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33429. var stride = tessellation + 1;
  33430. for (var i = 0; i <= tessellation; i++) {
  33431. var u = i / tessellation;
  33432. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33433. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33434. for (var j = 0; j <= tessellation; j++) {
  33435. var v = 1 - j / tessellation;
  33436. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33437. var dx = Math.cos(innerAngle);
  33438. var dy = Math.sin(innerAngle);
  33439. // Create a vertex.
  33440. var normal = new BABYLON.Vector3(dx, dy, 0);
  33441. var position = normal.scale(thickness / 2);
  33442. var textureCoordinate = new BABYLON.Vector2(u, v);
  33443. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33444. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33445. positions.push(position.x, position.y, position.z);
  33446. normals.push(normal.x, normal.y, normal.z);
  33447. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33448. // And create indices for two triangles.
  33449. var nextI = (i + 1) % stride;
  33450. var nextJ = (j + 1) % stride;
  33451. indices.push(i * stride + j);
  33452. indices.push(i * stride + nextJ);
  33453. indices.push(nextI * stride + j);
  33454. indices.push(i * stride + nextJ);
  33455. indices.push(nextI * stride + nextJ);
  33456. indices.push(nextI * stride + j);
  33457. }
  33458. }
  33459. // Sides
  33460. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33461. // Result
  33462. var vertexData = new VertexData();
  33463. vertexData.indices = indices;
  33464. vertexData.positions = positions;
  33465. vertexData.normals = normals;
  33466. vertexData.uvs = uvs;
  33467. return vertexData;
  33468. };
  33469. /**
  33470. * Creates the VertexData of the LineSystem.
  33471. */
  33472. VertexData.CreateLineSystem = function (options) {
  33473. var indices = [];
  33474. var positions = [];
  33475. var lines = options.lines;
  33476. var colors = options.colors;
  33477. var vertexColors = [];
  33478. var idx = 0;
  33479. for (var l = 0; l < lines.length; l++) {
  33480. var points = lines[l];
  33481. for (var index = 0; index < points.length; index++) {
  33482. positions.push(points[index].x, points[index].y, points[index].z);
  33483. if (colors) {
  33484. var color = colors[l];
  33485. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33486. }
  33487. if (index > 0) {
  33488. indices.push(idx - 1);
  33489. indices.push(idx);
  33490. }
  33491. idx++;
  33492. }
  33493. }
  33494. var vertexData = new VertexData();
  33495. vertexData.indices = indices;
  33496. vertexData.positions = positions;
  33497. if (colors) {
  33498. vertexData.colors = vertexColors;
  33499. }
  33500. return vertexData;
  33501. };
  33502. /**
  33503. * Create the VertexData of the DashedLines.
  33504. */
  33505. VertexData.CreateDashedLines = function (options) {
  33506. var dashSize = options.dashSize || 3;
  33507. var gapSize = options.gapSize || 1;
  33508. var dashNb = options.dashNb || 200;
  33509. var points = options.points;
  33510. var positions = new Array();
  33511. var indices = new Array();
  33512. var curvect = BABYLON.Vector3.Zero();
  33513. var lg = 0;
  33514. var nb = 0;
  33515. var shft = 0;
  33516. var dashshft = 0;
  33517. var curshft = 0;
  33518. var idx = 0;
  33519. var i = 0;
  33520. for (i = 0; i < points.length - 1; i++) {
  33521. points[i + 1].subtractToRef(points[i], curvect);
  33522. lg += curvect.length();
  33523. }
  33524. shft = lg / dashNb;
  33525. dashshft = dashSize * shft / (dashSize + gapSize);
  33526. for (i = 0; i < points.length - 1; i++) {
  33527. points[i + 1].subtractToRef(points[i], curvect);
  33528. nb = Math.floor(curvect.length() / shft);
  33529. curvect.normalize();
  33530. for (var j = 0; j < nb; j++) {
  33531. curshft = shft * j;
  33532. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33533. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33534. indices.push(idx, idx + 1);
  33535. idx += 2;
  33536. }
  33537. }
  33538. // Result
  33539. var vertexData = new VertexData();
  33540. vertexData.positions = positions;
  33541. vertexData.indices = indices;
  33542. return vertexData;
  33543. };
  33544. /**
  33545. * Creates the VertexData of the Ground.
  33546. */
  33547. VertexData.CreateGround = function (options) {
  33548. var indices = [];
  33549. var positions = [];
  33550. var normals = [];
  33551. var uvs = [];
  33552. var row, col;
  33553. var width = options.width || 1;
  33554. var height = options.height || 1;
  33555. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33556. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33557. for (row = 0; row <= subdivisionsY; row++) {
  33558. for (col = 0; col <= subdivisionsX; col++) {
  33559. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33560. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33561. positions.push(position.x, position.y, position.z);
  33562. normals.push(normal.x, normal.y, normal.z);
  33563. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33564. }
  33565. }
  33566. for (row = 0; row < subdivisionsY; row++) {
  33567. for (col = 0; col < subdivisionsX; col++) {
  33568. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33569. indices.push(col + 1 + row * (subdivisionsX + 1));
  33570. indices.push(col + row * (subdivisionsX + 1));
  33571. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33572. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33573. indices.push(col + row * (subdivisionsX + 1));
  33574. }
  33575. }
  33576. // Result
  33577. var vertexData = new VertexData();
  33578. vertexData.indices = indices;
  33579. vertexData.positions = positions;
  33580. vertexData.normals = normals;
  33581. vertexData.uvs = uvs;
  33582. return vertexData;
  33583. };
  33584. /**
  33585. * Creates the VertexData of the TiledGround.
  33586. */
  33587. VertexData.CreateTiledGround = function (options) {
  33588. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33589. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33590. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33591. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33592. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33593. var precision = options.precision || { w: 1, h: 1 };
  33594. var indices = new Array();
  33595. var positions = new Array();
  33596. var normals = new Array();
  33597. var uvs = new Array();
  33598. var row, col, tileRow, tileCol;
  33599. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33600. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33601. precision.w = (precision.w < 1) ? 1 : precision.w;
  33602. precision.h = (precision.h < 1) ? 1 : precision.h;
  33603. var tileSize = {
  33604. 'w': (xmax - xmin) / subdivisions.w,
  33605. 'h': (zmax - zmin) / subdivisions.h
  33606. };
  33607. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33608. // Indices
  33609. var base = positions.length / 3;
  33610. var rowLength = precision.w + 1;
  33611. for (row = 0; row < precision.h; row++) {
  33612. for (col = 0; col < precision.w; col++) {
  33613. var square = [
  33614. base + col + row * rowLength,
  33615. base + (col + 1) + row * rowLength,
  33616. base + (col + 1) + (row + 1) * rowLength,
  33617. base + col + (row + 1) * rowLength
  33618. ];
  33619. indices.push(square[1]);
  33620. indices.push(square[2]);
  33621. indices.push(square[3]);
  33622. indices.push(square[0]);
  33623. indices.push(square[1]);
  33624. indices.push(square[3]);
  33625. }
  33626. }
  33627. // Position, normals and uvs
  33628. var position = BABYLON.Vector3.Zero();
  33629. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33630. for (row = 0; row <= precision.h; row++) {
  33631. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33632. for (col = 0; col <= precision.w; col++) {
  33633. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33634. position.y = 0;
  33635. positions.push(position.x, position.y, position.z);
  33636. normals.push(normal.x, normal.y, normal.z);
  33637. uvs.push(col / precision.w, row / precision.h);
  33638. }
  33639. }
  33640. }
  33641. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33642. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33643. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33644. }
  33645. }
  33646. // Result
  33647. var vertexData = new VertexData();
  33648. vertexData.indices = indices;
  33649. vertexData.positions = positions;
  33650. vertexData.normals = normals;
  33651. vertexData.uvs = uvs;
  33652. return vertexData;
  33653. };
  33654. /**
  33655. * Creates the VertexData of the Ground designed from a heightmap.
  33656. */
  33657. VertexData.CreateGroundFromHeightMap = function (options) {
  33658. var indices = [];
  33659. var positions = [];
  33660. var normals = [];
  33661. var uvs = [];
  33662. var row, col;
  33663. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33664. // Vertices
  33665. for (row = 0; row <= options.subdivisions; row++) {
  33666. for (col = 0; col <= options.subdivisions; col++) {
  33667. 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));
  33668. // Compute height
  33669. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33670. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33671. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33672. var r = options.buffer[pos] / 255.0;
  33673. var g = options.buffer[pos + 1] / 255.0;
  33674. var b = options.buffer[pos + 2] / 255.0;
  33675. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33676. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33677. // Add vertex
  33678. positions.push(position.x, position.y, position.z);
  33679. normals.push(0, 0, 0);
  33680. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33681. }
  33682. }
  33683. // Indices
  33684. for (row = 0; row < options.subdivisions; row++) {
  33685. for (col = 0; col < options.subdivisions; col++) {
  33686. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33687. indices.push(col + 1 + row * (options.subdivisions + 1));
  33688. indices.push(col + row * (options.subdivisions + 1));
  33689. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33690. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33691. indices.push(col + row * (options.subdivisions + 1));
  33692. }
  33693. }
  33694. // Normals
  33695. VertexData.ComputeNormals(positions, indices, normals);
  33696. // Result
  33697. var vertexData = new VertexData();
  33698. vertexData.indices = indices;
  33699. vertexData.positions = positions;
  33700. vertexData.normals = normals;
  33701. vertexData.uvs = uvs;
  33702. return vertexData;
  33703. };
  33704. /**
  33705. * Creates the VertexData of the Plane.
  33706. */
  33707. VertexData.CreatePlane = function (options) {
  33708. var indices = [];
  33709. var positions = [];
  33710. var normals = [];
  33711. var uvs = [];
  33712. var width = options.width || options.size || 1;
  33713. var height = options.height || options.size || 1;
  33714. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33715. // Vertices
  33716. var halfWidth = width / 2.0;
  33717. var halfHeight = height / 2.0;
  33718. positions.push(-halfWidth, -halfHeight, 0);
  33719. normals.push(0, 0, -1.0);
  33720. uvs.push(0.0, 0.0);
  33721. positions.push(halfWidth, -halfHeight, 0);
  33722. normals.push(0, 0, -1.0);
  33723. uvs.push(1.0, 0.0);
  33724. positions.push(halfWidth, halfHeight, 0);
  33725. normals.push(0, 0, -1.0);
  33726. uvs.push(1.0, 1.0);
  33727. positions.push(-halfWidth, halfHeight, 0);
  33728. normals.push(0, 0, -1.0);
  33729. uvs.push(0.0, 1.0);
  33730. // Indices
  33731. indices.push(0);
  33732. indices.push(1);
  33733. indices.push(2);
  33734. indices.push(0);
  33735. indices.push(2);
  33736. indices.push(3);
  33737. // Sides
  33738. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33739. // Result
  33740. var vertexData = new VertexData();
  33741. vertexData.indices = indices;
  33742. vertexData.positions = positions;
  33743. vertexData.normals = normals;
  33744. vertexData.uvs = uvs;
  33745. return vertexData;
  33746. };
  33747. /**
  33748. * Creates the VertexData of the Disc or regular Polygon.
  33749. */
  33750. VertexData.CreateDisc = function (options) {
  33751. var positions = new Array();
  33752. var indices = new Array();
  33753. var normals = new Array();
  33754. var uvs = new Array();
  33755. var radius = options.radius || 0.5;
  33756. var tessellation = options.tessellation || 64;
  33757. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33758. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33759. // positions and uvs
  33760. positions.push(0, 0, 0); // disc center first
  33761. uvs.push(0.5, 0.5);
  33762. var theta = Math.PI * 2 * arc;
  33763. var step = theta / tessellation;
  33764. for (var a = 0; a < theta; a += step) {
  33765. var x = Math.cos(a);
  33766. var y = Math.sin(a);
  33767. var u = (x + 1) / 2;
  33768. var v = (1 - y) / 2;
  33769. positions.push(radius * x, radius * y, 0);
  33770. uvs.push(u, v);
  33771. }
  33772. if (arc === 1) {
  33773. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33774. uvs.push(uvs[2], uvs[3]);
  33775. }
  33776. //indices
  33777. var vertexNb = positions.length / 3;
  33778. for (var i = 1; i < vertexNb - 1; i++) {
  33779. indices.push(i + 1, 0, i);
  33780. }
  33781. // result
  33782. VertexData.ComputeNormals(positions, indices, normals);
  33783. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33784. var vertexData = new VertexData();
  33785. vertexData.indices = indices;
  33786. vertexData.positions = positions;
  33787. vertexData.normals = normals;
  33788. vertexData.uvs = uvs;
  33789. return vertexData;
  33790. };
  33791. /**
  33792. * Re-creates the VertexData of the Polygon for sideOrientation.
  33793. */
  33794. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33795. var faceUV = fUV || new Array(3);
  33796. var faceColors = fColors;
  33797. var colors = [];
  33798. // default face colors and UV if undefined
  33799. for (var f = 0; f < 3; f++) {
  33800. if (faceUV[f] === undefined) {
  33801. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33802. }
  33803. if (faceColors && faceColors[f] === undefined) {
  33804. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33805. }
  33806. }
  33807. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33808. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33809. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33810. var indices = polygon.getIndices();
  33811. // set face colours and textures
  33812. var idx = 0;
  33813. var face = 0;
  33814. for (var index = 0; index < normals.length; index += 3) {
  33815. //Edge Face no. 1
  33816. if (Math.abs(normals[index + 1]) < 0.001) {
  33817. face = 1;
  33818. }
  33819. //Top Face no. 0
  33820. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33821. face = 0;
  33822. }
  33823. //Bottom Face no. 2
  33824. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33825. face = 2;
  33826. }
  33827. idx = index / 3;
  33828. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33829. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33830. if (faceColors) {
  33831. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33832. }
  33833. }
  33834. // sides
  33835. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33836. // Result
  33837. var vertexData = new VertexData();
  33838. vertexData.indices = indices;
  33839. vertexData.positions = positions;
  33840. vertexData.normals = normals;
  33841. vertexData.uvs = uvs;
  33842. if (faceColors) {
  33843. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33844. vertexData.colors = totalColors;
  33845. }
  33846. return vertexData;
  33847. };
  33848. /**
  33849. * Creates the VertexData of the IcoSphere.
  33850. */
  33851. VertexData.CreateIcoSphere = function (options) {
  33852. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33853. var radius = options.radius || 1;
  33854. var flat = (options.flat === undefined) ? true : options.flat;
  33855. var subdivisions = options.subdivisions || 4;
  33856. var radiusX = options.radiusX || radius;
  33857. var radiusY = options.radiusY || radius;
  33858. var radiusZ = options.radiusZ || radius;
  33859. var t = (1 + Math.sqrt(5)) / 2;
  33860. // 12 vertex x,y,z
  33861. var ico_vertices = [
  33862. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33863. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33864. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33865. ];
  33866. // index of 3 vertex makes a face of icopshere
  33867. var ico_indices = [
  33868. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33869. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33870. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33871. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33872. ];
  33873. // vertex for uv have aliased position, not for UV
  33874. var vertices_unalias_id = [
  33875. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33876. // vertex alias
  33877. 0,
  33878. 2,
  33879. 3,
  33880. 3,
  33881. 3,
  33882. 4,
  33883. 7,
  33884. 8,
  33885. 9,
  33886. 9,
  33887. 10,
  33888. 11 // 23: B + 12
  33889. ];
  33890. // uv as integer step (not pixels !)
  33891. var ico_vertexuv = [
  33892. 5, 1, 3, 1, 6, 4, 0, 0,
  33893. 5, 3, 4, 2, 2, 2, 4, 0,
  33894. 2, 0, 1, 1, 6, 0, 6, 2,
  33895. // vertex alias (for same vertex on different faces)
  33896. 0, 4,
  33897. 3, 3,
  33898. 4, 4,
  33899. 3, 1,
  33900. 4, 2,
  33901. 4, 4,
  33902. 0, 2,
  33903. 1, 1,
  33904. 2, 2,
  33905. 3, 3,
  33906. 1, 3,
  33907. 2, 4 // 23: B + 12
  33908. ];
  33909. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33910. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33911. // First island of uv mapping
  33912. // v = 4h 3+ 2
  33913. // v = 3h 9+ 4
  33914. // v = 2h 9+ 5 B
  33915. // v = 1h 9 1 0
  33916. // v = 0h 3 8 7 A
  33917. // u = 0 1 2 3 4 5 6 *a
  33918. // Second island of uv mapping
  33919. // v = 4h 0+ B+ 4+
  33920. // v = 3h A+ 2+
  33921. // v = 2h 7+ 6 3+
  33922. // v = 1h 8+ 3+
  33923. // v = 0h
  33924. // u = 0 1 2 3 4 5 6 *a
  33925. // Face layout on texture UV mapping
  33926. // ============
  33927. // \ 4 /\ 16 / ======
  33928. // \ / \ / /\ 11 /
  33929. // \/ 7 \/ / \ /
  33930. // ======= / 10 \/
  33931. // /\ 17 /\ =======
  33932. // / \ / \ \ 15 /\
  33933. // / 8 \/ 12 \ \ / \
  33934. // ============ \/ 6 \
  33935. // \ 18 /\ ============
  33936. // \ / \ \ 5 /\ 0 /
  33937. // \/ 13 \ \ / \ /
  33938. // ======= \/ 1 \/
  33939. // =============
  33940. // /\ 19 /\ 2 /\
  33941. // / \ / \ / \
  33942. // / 14 \/ 9 \/ 3 \
  33943. // ===================
  33944. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33945. var ustep = 138 / 1024;
  33946. var vstep = 239 / 1024;
  33947. var uoffset = 60 / 1024;
  33948. var voffset = 26 / 1024;
  33949. // Second island should have margin, not to touch the first island
  33950. // avoid any borderline artefact in pixel rounding
  33951. var island_u_offset = -40 / 1024;
  33952. var island_v_offset = +20 / 1024;
  33953. // face is either island 0 or 1 :
  33954. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33955. var island = [
  33956. 0, 0, 0, 0, 1,
  33957. 0, 0, 1, 1, 0,
  33958. 0, 0, 1, 1, 0,
  33959. 0, 1, 1, 1, 0 // 15 - 19
  33960. ];
  33961. var indices = new Array();
  33962. var positions = new Array();
  33963. var normals = new Array();
  33964. var uvs = new Array();
  33965. var current_indice = 0;
  33966. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33967. var face_vertex_pos = new Array(3);
  33968. var face_vertex_uv = new Array(3);
  33969. var v012;
  33970. for (v012 = 0; v012 < 3; v012++) {
  33971. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33972. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33973. }
  33974. // create all with normals
  33975. for (var face = 0; face < 20; face++) {
  33976. // 3 vertex per face
  33977. for (v012 = 0; v012 < 3; v012++) {
  33978. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33979. var v_id = ico_indices[3 * face + v012];
  33980. // vertex have 3D position (x,y,z)
  33981. 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]);
  33982. // Normalize to get normal, then scale to radius
  33983. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33984. // uv Coordinates from vertex ID
  33985. 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);
  33986. }
  33987. // Subdivide the face (interpolate pos, norm, uv)
  33988. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33989. // - norm is linear interpolation of vertex corner normal
  33990. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33991. // - uv is linear interpolation
  33992. //
  33993. // Topology is as below for sub-divide by 2
  33994. // vertex shown as v0,v1,v2
  33995. // interp index is i1 to progress in range [v0,v1[
  33996. // interp index is i2 to progress in range [v0,v2[
  33997. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33998. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33999. //
  34000. //
  34001. // i2 v2
  34002. // ^ ^
  34003. // / / \
  34004. // / / \
  34005. // / / \
  34006. // / / (0,1) \
  34007. // / #---------\
  34008. // / / \ (0,0)'/ \
  34009. // / / \ / \
  34010. // / / \ / \
  34011. // / / (0,0) \ / (1,0) \
  34012. // / #---------#---------\
  34013. // v0 v1
  34014. //
  34015. // --------------------> i1
  34016. //
  34017. // interp of (i1,i2):
  34018. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34019. // along i1 : lerp(x0,x1, i1/(S-i2))
  34020. //
  34021. // centroid of triangle is needed to get help normal computation
  34022. // (c1,c2) are used for centroid location
  34023. var interp_vertex = function (i1, i2, c1, c2) {
  34024. // vertex is interpolated from
  34025. // - face_vertex_pos[0..2]
  34026. // - face_vertex_uv[0..2]
  34027. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34028. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34029. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34030. pos_interp.normalize();
  34031. var vertex_normal;
  34032. if (flat) {
  34033. // in flat mode, recalculate normal as face centroid normal
  34034. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34035. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34036. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34037. }
  34038. else {
  34039. // in smooth mode, recalculate normal from each single vertex position
  34040. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34041. }
  34042. // Vertex normal need correction due to X,Y,Z radius scaling
  34043. vertex_normal.x /= radiusX;
  34044. vertex_normal.y /= radiusY;
  34045. vertex_normal.z /= radiusZ;
  34046. vertex_normal.normalize();
  34047. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34048. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34049. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34050. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34051. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34052. uvs.push(uv_interp.x, uv_interp.y);
  34053. // push each vertex has member of a face
  34054. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34055. indices.push(current_indice);
  34056. current_indice++;
  34057. };
  34058. for (var i2 = 0; i2 < subdivisions; i2++) {
  34059. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34060. // face : (i1,i2) for /\ :
  34061. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34062. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34063. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34064. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34065. if (i1 + i2 + 1 < subdivisions) {
  34066. // face : (i1,i2)' for \/ :
  34067. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34068. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34069. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34070. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34071. }
  34072. }
  34073. }
  34074. }
  34075. // Sides
  34076. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34077. // Result
  34078. var vertexData = new VertexData();
  34079. vertexData.indices = indices;
  34080. vertexData.positions = positions;
  34081. vertexData.normals = normals;
  34082. vertexData.uvs = uvs;
  34083. return vertexData;
  34084. };
  34085. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34086. /**
  34087. * Creates the VertexData of the Polyhedron.
  34088. */
  34089. VertexData.CreatePolyhedron = function (options) {
  34090. // provided polyhedron types :
  34091. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34092. // 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)
  34093. var polyhedra = [];
  34094. 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]] };
  34095. 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]] };
  34096. polyhedra[2] = {
  34097. 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]],
  34098. 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]]
  34099. };
  34100. polyhedra[3] = {
  34101. 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]],
  34102. 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]]
  34103. };
  34104. polyhedra[4] = {
  34105. 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]],
  34106. 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]]
  34107. };
  34108. 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]] };
  34109. 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]] };
  34110. 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]] };
  34111. 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]] };
  34112. 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]] };
  34113. 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]] };
  34114. 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]] };
  34115. 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]] };
  34116. 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]] };
  34117. polyhedra[14] = {
  34118. 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]],
  34119. 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]]
  34120. };
  34121. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34122. var size = options.size;
  34123. var sizeX = options.sizeX || size || 1;
  34124. var sizeY = options.sizeY || size || 1;
  34125. var sizeZ = options.sizeZ || size || 1;
  34126. var data = options.custom || polyhedra[type];
  34127. var nbfaces = data.face.length;
  34128. var faceUV = options.faceUV || new Array(nbfaces);
  34129. var faceColors = options.faceColors;
  34130. var flat = (options.flat === undefined) ? true : options.flat;
  34131. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34132. var positions = new Array();
  34133. var indices = new Array();
  34134. var normals = new Array();
  34135. var uvs = new Array();
  34136. var colors = new Array();
  34137. var index = 0;
  34138. var faceIdx = 0; // face cursor in the array "indexes"
  34139. var indexes = new Array();
  34140. var i = 0;
  34141. var f = 0;
  34142. var u, v, ang, x, y, tmp;
  34143. // default face colors and UV if undefined
  34144. if (flat) {
  34145. for (f = 0; f < nbfaces; f++) {
  34146. if (faceColors && faceColors[f] === undefined) {
  34147. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34148. }
  34149. if (faceUV && faceUV[f] === undefined) {
  34150. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34151. }
  34152. }
  34153. }
  34154. if (!flat) {
  34155. for (i = 0; i < data.vertex.length; i++) {
  34156. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34157. uvs.push(0, 0);
  34158. }
  34159. for (f = 0; f < nbfaces; f++) {
  34160. for (i = 0; i < data.face[f].length - 2; i++) {
  34161. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34162. }
  34163. }
  34164. }
  34165. else {
  34166. for (f = 0; f < nbfaces; f++) {
  34167. var fl = data.face[f].length; // number of vertices of the current face
  34168. ang = 2 * Math.PI / fl;
  34169. x = 0.5 * Math.tan(ang / 2);
  34170. y = 0.5;
  34171. // positions, uvs, colors
  34172. for (i = 0; i < fl; i++) {
  34173. // positions
  34174. 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);
  34175. indexes.push(index);
  34176. index++;
  34177. // uvs
  34178. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34179. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34180. uvs.push(u, v);
  34181. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34182. y = x * Math.sin(ang) + y * Math.cos(ang);
  34183. x = tmp;
  34184. // colors
  34185. if (faceColors) {
  34186. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34187. }
  34188. }
  34189. // indices from indexes
  34190. for (i = 0; i < fl - 2; i++) {
  34191. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34192. }
  34193. faceIdx += fl;
  34194. }
  34195. }
  34196. VertexData.ComputeNormals(positions, indices, normals);
  34197. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34198. var vertexData = new VertexData();
  34199. vertexData.positions = positions;
  34200. vertexData.indices = indices;
  34201. vertexData.normals = normals;
  34202. vertexData.uvs = uvs;
  34203. if (faceColors && flat) {
  34204. vertexData.colors = colors;
  34205. }
  34206. return vertexData;
  34207. };
  34208. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34209. /**
  34210. * Creates the VertexData of the Torus Knot.
  34211. */
  34212. VertexData.CreateTorusKnot = function (options) {
  34213. var indices = new Array();
  34214. var positions = new Array();
  34215. var normals = new Array();
  34216. var uvs = new Array();
  34217. var radius = options.radius || 2;
  34218. var tube = options.tube || 0.5;
  34219. var radialSegments = options.radialSegments || 32;
  34220. var tubularSegments = options.tubularSegments || 32;
  34221. var p = options.p || 2;
  34222. var q = options.q || 3;
  34223. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34224. // Helper
  34225. var getPos = function (angle) {
  34226. var cu = Math.cos(angle);
  34227. var su = Math.sin(angle);
  34228. var quOverP = q / p * angle;
  34229. var cs = Math.cos(quOverP);
  34230. var tx = radius * (2 + cs) * 0.5 * cu;
  34231. var ty = radius * (2 + cs) * su * 0.5;
  34232. var tz = radius * Math.sin(quOverP) * 0.5;
  34233. return new BABYLON.Vector3(tx, ty, tz);
  34234. };
  34235. // Vertices
  34236. var i;
  34237. var j;
  34238. for (i = 0; i <= radialSegments; i++) {
  34239. var modI = i % radialSegments;
  34240. var u = modI / radialSegments * 2 * p * Math.PI;
  34241. var p1 = getPos(u);
  34242. var p2 = getPos(u + 0.01);
  34243. var tang = p2.subtract(p1);
  34244. var n = p2.add(p1);
  34245. var bitan = BABYLON.Vector3.Cross(tang, n);
  34246. n = BABYLON.Vector3.Cross(bitan, tang);
  34247. bitan.normalize();
  34248. n.normalize();
  34249. for (j = 0; j < tubularSegments; j++) {
  34250. var modJ = j % tubularSegments;
  34251. var v = modJ / tubularSegments * 2 * Math.PI;
  34252. var cx = -tube * Math.cos(v);
  34253. var cy = tube * Math.sin(v);
  34254. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34255. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34256. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34257. uvs.push(i / radialSegments);
  34258. uvs.push(j / tubularSegments);
  34259. }
  34260. }
  34261. for (i = 0; i < radialSegments; i++) {
  34262. for (j = 0; j < tubularSegments; j++) {
  34263. var jNext = (j + 1) % tubularSegments;
  34264. var a = i * tubularSegments + j;
  34265. var b = (i + 1) * tubularSegments + j;
  34266. var c = (i + 1) * tubularSegments + jNext;
  34267. var d = i * tubularSegments + jNext;
  34268. indices.push(d);
  34269. indices.push(b);
  34270. indices.push(a);
  34271. indices.push(d);
  34272. indices.push(c);
  34273. indices.push(b);
  34274. }
  34275. }
  34276. // Normals
  34277. VertexData.ComputeNormals(positions, indices, normals);
  34278. // Sides
  34279. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34280. // Result
  34281. var vertexData = new VertexData();
  34282. vertexData.indices = indices;
  34283. vertexData.positions = positions;
  34284. vertexData.normals = normals;
  34285. vertexData.uvs = uvs;
  34286. return vertexData;
  34287. };
  34288. // Tools
  34289. /**
  34290. * @param {any} - positions (number[] or Float32Array)
  34291. * @param {any} - indices (number[] or Uint16Array)
  34292. * @param {any} - normals (number[] or Float32Array)
  34293. * options (optional) :
  34294. * facetPositions : optional array of facet positions (vector3)
  34295. * facetNormals : optional array of facet normals (vector3)
  34296. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34297. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34298. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34299. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34300. * bInfo : optional bounding info, required for facetPartitioning computation
  34301. * useRightHandedSystem: optional boolean to for right handed system computation
  34302. * depthSort : optional boolean to enable the facet depth sort computation
  34303. * distanceTo : optional Vector3 to compute the facet depth from this location
  34304. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34305. */
  34306. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34307. // temporary scalar variables
  34308. var index = 0; // facet index
  34309. var p1p2x = 0.0; // p1p2 vector x coordinate
  34310. var p1p2y = 0.0; // p1p2 vector y coordinate
  34311. var p1p2z = 0.0; // p1p2 vector z coordinate
  34312. var p3p2x = 0.0; // p3p2 vector x coordinate
  34313. var p3p2y = 0.0; // p3p2 vector y coordinate
  34314. var p3p2z = 0.0; // p3p2 vector z coordinate
  34315. var faceNormalx = 0.0; // facet normal x coordinate
  34316. var faceNormaly = 0.0; // facet normal y coordinate
  34317. var faceNormalz = 0.0; // facet normal z coordinate
  34318. var length = 0.0; // facet normal length before normalization
  34319. var v1x = 0; // vector1 x index in the positions array
  34320. var v1y = 0; // vector1 y index in the positions array
  34321. var v1z = 0; // vector1 z index in the positions array
  34322. var v2x = 0; // vector2 x index in the positions array
  34323. var v2y = 0; // vector2 y index in the positions array
  34324. var v2z = 0; // vector2 z index in the positions array
  34325. var v3x = 0; // vector3 x index in the positions array
  34326. var v3y = 0; // vector3 y index in the positions array
  34327. var v3z = 0; // vector3 z index in the positions array
  34328. var computeFacetNormals = false;
  34329. var computeFacetPositions = false;
  34330. var computeFacetPartitioning = false;
  34331. var computeDepthSort = false;
  34332. var faceNormalSign = 1;
  34333. var ratio = 0;
  34334. var distanceTo = null;
  34335. if (options) {
  34336. computeFacetNormals = (options.facetNormals) ? true : false;
  34337. computeFacetPositions = (options.facetPositions) ? true : false;
  34338. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34339. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34340. ratio = options.ratio || 0;
  34341. computeDepthSort = (options.depthSort) ? true : false;
  34342. distanceTo = (options.distanceTo);
  34343. if (computeDepthSort) {
  34344. if (distanceTo === undefined) {
  34345. distanceTo = BABYLON.Vector3.Zero();
  34346. }
  34347. var depthSortedFacets = options.depthSortedFacets;
  34348. }
  34349. }
  34350. // facetPartitioning reinit if needed
  34351. var xSubRatio = 0;
  34352. var ySubRatio = 0;
  34353. var zSubRatio = 0;
  34354. var subSq = 0;
  34355. if (computeFacetPartitioning && options && options.bbSize) {
  34356. var ox = 0; // X partitioning index for facet position
  34357. var oy = 0; // Y partinioning index for facet position
  34358. var oz = 0; // Z partinioning index for facet position
  34359. var b1x = 0; // X partitioning index for facet v1 vertex
  34360. var b1y = 0; // Y partitioning index for facet v1 vertex
  34361. var b1z = 0; // z partitioning index for facet v1 vertex
  34362. var b2x = 0; // X partitioning index for facet v2 vertex
  34363. var b2y = 0; // Y partitioning index for facet v2 vertex
  34364. var b2z = 0; // Z partitioning index for facet v2 vertex
  34365. var b3x = 0; // X partitioning index for facet v3 vertex
  34366. var b3y = 0; // Y partitioning index for facet v3 vertex
  34367. var b3z = 0; // Z partitioning index for facet v3 vertex
  34368. var block_idx_o = 0; // facet barycenter block index
  34369. var block_idx_v1 = 0; // v1 vertex block index
  34370. var block_idx_v2 = 0; // v2 vertex block index
  34371. var block_idx_v3 = 0; // v3 vertex block index
  34372. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34373. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34374. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34375. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34376. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34377. subSq = options.subDiv.max * options.subDiv.max;
  34378. options.facetPartitioning.length = 0;
  34379. }
  34380. // reset the normals
  34381. for (index = 0; index < positions.length; index++) {
  34382. normals[index] = 0.0;
  34383. }
  34384. // Loop : 1 indice triplet = 1 facet
  34385. var nbFaces = (indices.length / 3) | 0;
  34386. for (index = 0; index < nbFaces; index++) {
  34387. // get the indexes of the coordinates of each vertex of the facet
  34388. v1x = indices[index * 3] * 3;
  34389. v1y = v1x + 1;
  34390. v1z = v1x + 2;
  34391. v2x = indices[index * 3 + 1] * 3;
  34392. v2y = v2x + 1;
  34393. v2z = v2x + 2;
  34394. v3x = indices[index * 3 + 2] * 3;
  34395. v3y = v3x + 1;
  34396. v3z = v3x + 2;
  34397. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34398. p1p2y = positions[v1y] - positions[v2y];
  34399. p1p2z = positions[v1z] - positions[v2z];
  34400. p3p2x = positions[v3x] - positions[v2x];
  34401. p3p2y = positions[v3y] - positions[v2y];
  34402. p3p2z = positions[v3z] - positions[v2z];
  34403. // compute the face normal with the cross product
  34404. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34405. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34406. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34407. // normalize this normal and store it in the array facetData
  34408. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34409. length = (length === 0) ? 1.0 : length;
  34410. faceNormalx /= length;
  34411. faceNormaly /= length;
  34412. faceNormalz /= length;
  34413. if (computeFacetNormals && options) {
  34414. options.facetNormals[index].x = faceNormalx;
  34415. options.facetNormals[index].y = faceNormaly;
  34416. options.facetNormals[index].z = faceNormalz;
  34417. }
  34418. if (computeFacetPositions && options) {
  34419. // compute and the facet barycenter coordinates in the array facetPositions
  34420. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34421. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34422. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34423. }
  34424. if (computeFacetPartitioning && options) {
  34425. // store the facet indexes in arrays in the main facetPartitioning array :
  34426. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34427. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34428. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34429. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34430. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34431. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34432. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34433. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34434. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34435. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34436. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34437. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34438. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34439. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34440. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34441. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34442. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34443. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34444. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34445. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34446. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34447. // push each facet index in each block containing the vertex
  34448. options.facetPartitioning[block_idx_v1].push(index);
  34449. if (block_idx_v2 != block_idx_v1) {
  34450. options.facetPartitioning[block_idx_v2].push(index);
  34451. }
  34452. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34453. options.facetPartitioning[block_idx_v3].push(index);
  34454. }
  34455. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34456. options.facetPartitioning[block_idx_o].push(index);
  34457. }
  34458. }
  34459. if (computeDepthSort && options && options.facetPositions) {
  34460. var dsf = depthSortedFacets[index];
  34461. dsf.ind = index * 3;
  34462. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34463. }
  34464. // compute the normals anyway
  34465. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34466. normals[v1y] += faceNormaly;
  34467. normals[v1z] += faceNormalz;
  34468. normals[v2x] += faceNormalx;
  34469. normals[v2y] += faceNormaly;
  34470. normals[v2z] += faceNormalz;
  34471. normals[v3x] += faceNormalx;
  34472. normals[v3y] += faceNormaly;
  34473. normals[v3z] += faceNormalz;
  34474. }
  34475. // last normalization of each normal
  34476. for (index = 0; index < normals.length / 3; index++) {
  34477. faceNormalx = normals[index * 3];
  34478. faceNormaly = normals[index * 3 + 1];
  34479. faceNormalz = normals[index * 3 + 2];
  34480. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34481. length = (length === 0) ? 1.0 : length;
  34482. faceNormalx /= length;
  34483. faceNormaly /= length;
  34484. faceNormalz /= length;
  34485. normals[index * 3] = faceNormalx;
  34486. normals[index * 3 + 1] = faceNormaly;
  34487. normals[index * 3 + 2] = faceNormalz;
  34488. }
  34489. };
  34490. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34491. var li = indices.length;
  34492. var ln = normals.length;
  34493. var i;
  34494. var n;
  34495. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34496. switch (sideOrientation) {
  34497. case BABYLON.Mesh.FRONTSIDE:
  34498. // nothing changed
  34499. break;
  34500. case BABYLON.Mesh.BACKSIDE:
  34501. var tmp;
  34502. // indices
  34503. for (i = 0; i < li; i += 3) {
  34504. tmp = indices[i];
  34505. indices[i] = indices[i + 2];
  34506. indices[i + 2] = tmp;
  34507. }
  34508. // normals
  34509. for (n = 0; n < ln; n++) {
  34510. normals[n] = -normals[n];
  34511. }
  34512. break;
  34513. case BABYLON.Mesh.DOUBLESIDE:
  34514. // positions
  34515. var lp = positions.length;
  34516. var l = lp / 3;
  34517. for (var p = 0; p < lp; p++) {
  34518. positions[lp + p] = positions[p];
  34519. }
  34520. // indices
  34521. for (i = 0; i < li; i += 3) {
  34522. indices[i + li] = indices[i + 2] + l;
  34523. indices[i + 1 + li] = indices[i + 1] + l;
  34524. indices[i + 2 + li] = indices[i] + l;
  34525. }
  34526. // normals
  34527. for (n = 0; n < ln; n++) {
  34528. normals[ln + n] = -normals[n];
  34529. }
  34530. // uvs
  34531. var lu = uvs.length;
  34532. var u = 0;
  34533. for (u = 0; u < lu; u++) {
  34534. uvs[u + lu] = uvs[u];
  34535. }
  34536. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34537. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34538. u = 0;
  34539. for (i = 0; i < lu / 2; i++) {
  34540. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34541. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34542. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34543. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34544. u += 2;
  34545. }
  34546. break;
  34547. }
  34548. };
  34549. /**
  34550. * Creates a new VertexData from the imported parameters.
  34551. */
  34552. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34553. var vertexData = new VertexData();
  34554. // positions
  34555. var positions = parsedVertexData.positions;
  34556. if (positions) {
  34557. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34558. }
  34559. // normals
  34560. var normals = parsedVertexData.normals;
  34561. if (normals) {
  34562. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34563. }
  34564. // tangents
  34565. var tangents = parsedVertexData.tangents;
  34566. if (tangents) {
  34567. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34568. }
  34569. // uvs
  34570. var uvs = parsedVertexData.uvs;
  34571. if (uvs) {
  34572. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34573. }
  34574. // uv2s
  34575. var uv2s = parsedVertexData.uv2s;
  34576. if (uv2s) {
  34577. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34578. }
  34579. // uv3s
  34580. var uv3s = parsedVertexData.uv3s;
  34581. if (uv3s) {
  34582. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34583. }
  34584. // uv4s
  34585. var uv4s = parsedVertexData.uv4s;
  34586. if (uv4s) {
  34587. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34588. }
  34589. // uv5s
  34590. var uv5s = parsedVertexData.uv5s;
  34591. if (uv5s) {
  34592. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34593. }
  34594. // uv6s
  34595. var uv6s = parsedVertexData.uv6s;
  34596. if (uv6s) {
  34597. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34598. }
  34599. // colors
  34600. var colors = parsedVertexData.colors;
  34601. if (colors) {
  34602. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34603. }
  34604. // matricesIndices
  34605. var matricesIndices = parsedVertexData.matricesIndices;
  34606. if (matricesIndices) {
  34607. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34608. }
  34609. // matricesWeights
  34610. var matricesWeights = parsedVertexData.matricesWeights;
  34611. if (matricesWeights) {
  34612. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34613. }
  34614. // indices
  34615. var indices = parsedVertexData.indices;
  34616. if (indices) {
  34617. vertexData.indices = indices;
  34618. }
  34619. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34620. };
  34621. return VertexData;
  34622. }());
  34623. BABYLON.VertexData = VertexData;
  34624. })(BABYLON || (BABYLON = {}));
  34625. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34626. var BABYLON;
  34627. (function (BABYLON) {
  34628. /**
  34629. * Class used to store geometry data (vertex buffers + index buffer)
  34630. */
  34631. var Geometry = /** @class */ (function () {
  34632. /**
  34633. * Creates a new geometry
  34634. * @param id defines the unique ID
  34635. * @param scene defines the hosting scene
  34636. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34637. * @param updatable defines if geometry must be updatable (false by default)
  34638. * @param mesh defines the mesh that will be associated with the geometry
  34639. */
  34640. function Geometry(id, scene, vertexData, updatable, mesh) {
  34641. if (updatable === void 0) { updatable = false; }
  34642. if (mesh === void 0) { mesh = null; }
  34643. /**
  34644. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34645. */
  34646. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34647. this._totalVertices = 0;
  34648. this._isDisposed = false;
  34649. this._indexBufferIsUpdatable = false;
  34650. this.id = id;
  34651. this._engine = scene.getEngine();
  34652. this._meshes = [];
  34653. this._scene = scene;
  34654. //Init vertex buffer cache
  34655. this._vertexBuffers = {};
  34656. this._indices = [];
  34657. this._updatable = updatable;
  34658. // vertexData
  34659. if (vertexData) {
  34660. this.setAllVerticesData(vertexData, updatable);
  34661. }
  34662. else {
  34663. this._totalVertices = 0;
  34664. this._indices = [];
  34665. }
  34666. if (this._engine.getCaps().vertexArrayObject) {
  34667. this._vertexArrayObjects = {};
  34668. }
  34669. // applyToMesh
  34670. if (mesh) {
  34671. if (mesh.getClassName() === "LinesMesh") {
  34672. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34673. this.updateExtend();
  34674. }
  34675. this.applyToMesh(mesh);
  34676. mesh.computeWorldMatrix(true);
  34677. }
  34678. }
  34679. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34680. /**
  34681. * 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
  34682. */
  34683. get: function () {
  34684. return this._boundingBias;
  34685. },
  34686. /**
  34687. * 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
  34688. */
  34689. set: function (value) {
  34690. if (this._boundingBias && this._boundingBias.equals(value)) {
  34691. return;
  34692. }
  34693. this._boundingBias = value.clone();
  34694. this.updateBoundingInfo(true, null);
  34695. },
  34696. enumerable: true,
  34697. configurable: true
  34698. });
  34699. /**
  34700. * Static function used to attach a new empty geometry to a mesh
  34701. * @param mesh defines the mesh to attach the geometry to
  34702. * @returns the new {BABYLON.Geometry}
  34703. */
  34704. Geometry.CreateGeometryForMesh = function (mesh) {
  34705. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34706. geometry.applyToMesh(mesh);
  34707. return geometry;
  34708. };
  34709. Object.defineProperty(Geometry.prototype, "extend", {
  34710. /**
  34711. * Gets the current extend of the geometry
  34712. */
  34713. get: function () {
  34714. return this._extend;
  34715. },
  34716. enumerable: true,
  34717. configurable: true
  34718. });
  34719. /**
  34720. * Gets the hosting scene
  34721. * @returns the hosting {BABYLON.Scene}
  34722. */
  34723. Geometry.prototype.getScene = function () {
  34724. return this._scene;
  34725. };
  34726. /**
  34727. * Gets the hosting engine
  34728. * @returns the hosting {BABYLON.Engine}
  34729. */
  34730. Geometry.prototype.getEngine = function () {
  34731. return this._engine;
  34732. };
  34733. /**
  34734. * Defines if the geometry is ready to use
  34735. * @returns true if the geometry is ready to be used
  34736. */
  34737. Geometry.prototype.isReady = function () {
  34738. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34739. };
  34740. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34741. /**
  34742. * Gets a value indicating that the geometry should not be serialized
  34743. */
  34744. get: function () {
  34745. for (var index = 0; index < this._meshes.length; index++) {
  34746. if (!this._meshes[index].doNotSerialize) {
  34747. return false;
  34748. }
  34749. }
  34750. return true;
  34751. },
  34752. enumerable: true,
  34753. configurable: true
  34754. });
  34755. /** @ignore */
  34756. Geometry.prototype._rebuild = function () {
  34757. if (this._vertexArrayObjects) {
  34758. this._vertexArrayObjects = {};
  34759. }
  34760. // Index buffer
  34761. if (this._meshes.length !== 0 && this._indices) {
  34762. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34763. }
  34764. // Vertex buffers
  34765. for (var key in this._vertexBuffers) {
  34766. var vertexBuffer = this._vertexBuffers[key];
  34767. vertexBuffer._rebuild();
  34768. }
  34769. };
  34770. /**
  34771. * Affects all gemetry data in one call
  34772. * @param vertexData defines the geometry data
  34773. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34774. */
  34775. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34776. vertexData.applyToGeometry(this, updatable);
  34777. this.notifyUpdate();
  34778. };
  34779. /**
  34780. * Set specific vertex data
  34781. * @param kind defines the data kind (Position, normal, etc...)
  34782. * @param data defines the vertex data to use
  34783. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34784. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34785. */
  34786. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34787. if (updatable === void 0) { updatable = false; }
  34788. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34789. this.setVerticesBuffer(buffer);
  34790. };
  34791. /**
  34792. * Removes a specific vertex data
  34793. * @param kind defines the data kind (Position, normal, etc...)
  34794. */
  34795. Geometry.prototype.removeVerticesData = function (kind) {
  34796. if (this._vertexBuffers[kind]) {
  34797. this._vertexBuffers[kind].dispose();
  34798. delete this._vertexBuffers[kind];
  34799. }
  34800. };
  34801. /**
  34802. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34803. * @param buffer defines the vertex buffer to use
  34804. */
  34805. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34806. var kind = buffer.getKind();
  34807. if (this._vertexBuffers[kind]) {
  34808. this._vertexBuffers[kind].dispose();
  34809. }
  34810. this._vertexBuffers[kind] = buffer;
  34811. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34812. var data = buffer.getData();
  34813. var stride = buffer.getStrideSize();
  34814. this._totalVertices = data.length / stride;
  34815. this.updateExtend(data, stride);
  34816. this._resetPointsArrayCache();
  34817. var meshes = this._meshes;
  34818. var numOfMeshes = meshes.length;
  34819. for (var index = 0; index < numOfMeshes; index++) {
  34820. var mesh = meshes[index];
  34821. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34822. mesh._createGlobalSubMesh(false);
  34823. mesh.computeWorldMatrix(true);
  34824. }
  34825. }
  34826. this.notifyUpdate(kind);
  34827. if (this._vertexArrayObjects) {
  34828. this._disposeVertexArrayObjects();
  34829. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34830. }
  34831. };
  34832. /**
  34833. * Update a specific vertex buffer
  34834. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34835. * It will do nothing if the buffer is not updatable
  34836. * @param kind defines the data kind (Position, normal, etc...)
  34837. * @param data defines the data to use
  34838. * @param offset defines the offset in the target buffer where to store the data
  34839. */
  34840. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34841. var vertexBuffer = this.getVertexBuffer(kind);
  34842. if (!vertexBuffer) {
  34843. return;
  34844. }
  34845. vertexBuffer.updateDirectly(data, offset);
  34846. this.notifyUpdate(kind);
  34847. };
  34848. /**
  34849. * Update a specific vertex buffer
  34850. * This function will create a new buffer if the current one is not updatable
  34851. * @param kind defines the data kind (Position, normal, etc...)
  34852. * @param data defines the data to use
  34853. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34854. */
  34855. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34856. if (updateExtends === void 0) { updateExtends = false; }
  34857. var vertexBuffer = this.getVertexBuffer(kind);
  34858. if (!vertexBuffer) {
  34859. return;
  34860. }
  34861. vertexBuffer.update(data);
  34862. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34863. var stride = vertexBuffer.getStrideSize();
  34864. this._totalVertices = data.length / stride;
  34865. this.updateBoundingInfo(updateExtends, data);
  34866. }
  34867. this.notifyUpdate(kind);
  34868. };
  34869. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34870. if (updateExtends) {
  34871. this.updateExtend(data);
  34872. }
  34873. var meshes = this._meshes;
  34874. var numOfMeshes = meshes.length;
  34875. this._resetPointsArrayCache();
  34876. for (var index = 0; index < numOfMeshes; index++) {
  34877. var mesh = meshes[index];
  34878. if (updateExtends) {
  34879. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34880. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34881. var subMesh = mesh.subMeshes[subIndex];
  34882. subMesh.refreshBoundingInfo();
  34883. }
  34884. }
  34885. }
  34886. };
  34887. /** @ignore */
  34888. Geometry.prototype._bind = function (effect, indexToBind) {
  34889. if (!effect) {
  34890. return;
  34891. }
  34892. if (indexToBind === undefined) {
  34893. indexToBind = this._indexBuffer;
  34894. }
  34895. var vbs = this.getVertexBuffers();
  34896. if (!vbs) {
  34897. return;
  34898. }
  34899. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34900. this._engine.bindBuffers(vbs, indexToBind, effect);
  34901. return;
  34902. }
  34903. // Using VAO
  34904. if (!this._vertexArrayObjects[effect.key]) {
  34905. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34906. }
  34907. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34908. };
  34909. /**
  34910. * Gets total number of vertices
  34911. * @returns the total number of vertices
  34912. */
  34913. Geometry.prototype.getTotalVertices = function () {
  34914. if (!this.isReady()) {
  34915. return 0;
  34916. }
  34917. return this._totalVertices;
  34918. };
  34919. /**
  34920. * Gets a specific vertex data attached to this geometry
  34921. * @param kind defines the data kind (Position, normal, etc...)
  34922. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34923. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34924. * @returns a float array containing vertex data
  34925. */
  34926. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34927. var vertexBuffer = this.getVertexBuffer(kind);
  34928. if (!vertexBuffer) {
  34929. return null;
  34930. }
  34931. var orig = vertexBuffer.getData();
  34932. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34933. return orig;
  34934. }
  34935. else {
  34936. var len = orig.length;
  34937. var copy = [];
  34938. for (var i = 0; i < len; i++) {
  34939. copy.push(orig[i]);
  34940. }
  34941. return copy;
  34942. }
  34943. };
  34944. /**
  34945. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34946. * @param kind defines the data kind (Position, normal, etc...)
  34947. * @returns true if the vertex buffer with the specified kind is updatable
  34948. */
  34949. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34950. var vb = this._vertexBuffers[kind];
  34951. if (!vb) {
  34952. return false;
  34953. }
  34954. return vb.isUpdatable();
  34955. };
  34956. /**
  34957. * Gets a specific vertex buffer
  34958. * @param kind defines the data kind (Position, normal, etc...)
  34959. * @returns a {BABYLON.VertexBuffer}
  34960. */
  34961. Geometry.prototype.getVertexBuffer = function (kind) {
  34962. if (!this.isReady()) {
  34963. return null;
  34964. }
  34965. return this._vertexBuffers[kind];
  34966. };
  34967. /**
  34968. * Returns all vertex buffers
  34969. * @return an object holding all vertex buffers indexed by kind
  34970. */
  34971. Geometry.prototype.getVertexBuffers = function () {
  34972. if (!this.isReady()) {
  34973. return null;
  34974. }
  34975. return this._vertexBuffers;
  34976. };
  34977. /**
  34978. * Gets a boolean indicating if specific vertex buffer is present
  34979. * @param kind defines the data kind (Position, normal, etc...)
  34980. * @returns true if data is present
  34981. */
  34982. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34983. if (!this._vertexBuffers) {
  34984. if (this._delayInfo) {
  34985. return this._delayInfo.indexOf(kind) !== -1;
  34986. }
  34987. return false;
  34988. }
  34989. return this._vertexBuffers[kind] !== undefined;
  34990. };
  34991. /**
  34992. * Gets a list of all attached data kinds (Position, normal, etc...)
  34993. * @returns a list of string containing all kinds
  34994. */
  34995. Geometry.prototype.getVerticesDataKinds = function () {
  34996. var result = [];
  34997. var kind;
  34998. if (!this._vertexBuffers && this._delayInfo) {
  34999. for (kind in this._delayInfo) {
  35000. result.push(kind);
  35001. }
  35002. }
  35003. else {
  35004. for (kind in this._vertexBuffers) {
  35005. result.push(kind);
  35006. }
  35007. }
  35008. return result;
  35009. };
  35010. /**
  35011. * Update index buffer
  35012. * @param indices defines the indices to store in the index buffer
  35013. * @param offset defines the offset in the target buffer where to store the data
  35014. */
  35015. Geometry.prototype.updateIndices = function (indices, offset) {
  35016. if (!this._indexBuffer) {
  35017. return;
  35018. }
  35019. if (!this._indexBufferIsUpdatable) {
  35020. this.setIndices(indices, null, true);
  35021. }
  35022. else {
  35023. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35024. }
  35025. };
  35026. /**
  35027. * Creates a new index buffer
  35028. * @param indices defines the indices to store in the index buffer
  35029. * @param totalVertices defines the total number of vertices (could be null)
  35030. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35031. */
  35032. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35033. if (totalVertices === void 0) { totalVertices = null; }
  35034. if (updatable === void 0) { updatable = false; }
  35035. if (this._indexBuffer) {
  35036. this._engine._releaseBuffer(this._indexBuffer);
  35037. }
  35038. this._disposeVertexArrayObjects();
  35039. this._indices = indices;
  35040. this._indexBufferIsUpdatable = updatable;
  35041. if (this._meshes.length !== 0 && this._indices) {
  35042. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35043. }
  35044. if (totalVertices != undefined) {
  35045. this._totalVertices = totalVertices;
  35046. }
  35047. var meshes = this._meshes;
  35048. var numOfMeshes = meshes.length;
  35049. for (var index = 0; index < numOfMeshes; index++) {
  35050. meshes[index]._createGlobalSubMesh(true);
  35051. }
  35052. this.notifyUpdate();
  35053. };
  35054. /**
  35055. * Return the total number of indices
  35056. * @returns the total number of indices
  35057. */
  35058. Geometry.prototype.getTotalIndices = function () {
  35059. if (!this.isReady()) {
  35060. return 0;
  35061. }
  35062. return this._indices.length;
  35063. };
  35064. /**
  35065. * Gets the index buffer array
  35066. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35067. * @returns the index buffer array
  35068. */
  35069. Geometry.prototype.getIndices = function (copyWhenShared) {
  35070. if (!this.isReady()) {
  35071. return null;
  35072. }
  35073. var orig = this._indices;
  35074. if (!copyWhenShared || this._meshes.length === 1) {
  35075. return orig;
  35076. }
  35077. else {
  35078. var len = orig.length;
  35079. var copy = [];
  35080. for (var i = 0; i < len; i++) {
  35081. copy.push(orig[i]);
  35082. }
  35083. return copy;
  35084. }
  35085. };
  35086. /**
  35087. * Gets the index buffer
  35088. * @return the index buffer
  35089. */
  35090. Geometry.prototype.getIndexBuffer = function () {
  35091. if (!this.isReady()) {
  35092. return null;
  35093. }
  35094. return this._indexBuffer;
  35095. };
  35096. /** @ignore */
  35097. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35098. if (effect === void 0) { effect = null; }
  35099. if (!effect || !this._vertexArrayObjects) {
  35100. return;
  35101. }
  35102. if (this._vertexArrayObjects[effect.key]) {
  35103. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35104. delete this._vertexArrayObjects[effect.key];
  35105. }
  35106. };
  35107. /**
  35108. * Release the associated resources for a specific mesh
  35109. * @param mesh defines the source mesh
  35110. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35111. */
  35112. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35113. var meshes = this._meshes;
  35114. var index = meshes.indexOf(mesh);
  35115. if (index === -1) {
  35116. return;
  35117. }
  35118. meshes.splice(index, 1);
  35119. mesh._geometry = null;
  35120. if (meshes.length === 0 && shouldDispose) {
  35121. this.dispose();
  35122. }
  35123. };
  35124. /**
  35125. * Apply current geometry to a given mesh
  35126. * @param mesh defines the mesh to apply geometry to
  35127. */
  35128. Geometry.prototype.applyToMesh = function (mesh) {
  35129. if (mesh._geometry === this) {
  35130. return;
  35131. }
  35132. var previousGeometry = mesh._geometry;
  35133. if (previousGeometry) {
  35134. previousGeometry.releaseForMesh(mesh);
  35135. }
  35136. var meshes = this._meshes;
  35137. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35138. mesh._geometry = this;
  35139. this._scene.pushGeometry(this);
  35140. meshes.push(mesh);
  35141. if (this.isReady()) {
  35142. this._applyToMesh(mesh);
  35143. }
  35144. else {
  35145. mesh._boundingInfo = this._boundingInfo;
  35146. }
  35147. };
  35148. Geometry.prototype.updateExtend = function (data, stride) {
  35149. if (data === void 0) { data = null; }
  35150. if (!data) {
  35151. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35152. }
  35153. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35154. };
  35155. Geometry.prototype._applyToMesh = function (mesh) {
  35156. var numOfMeshes = this._meshes.length;
  35157. // vertexBuffers
  35158. for (var kind in this._vertexBuffers) {
  35159. if (numOfMeshes === 1) {
  35160. this._vertexBuffers[kind].create();
  35161. }
  35162. var buffer = this._vertexBuffers[kind].getBuffer();
  35163. if (buffer)
  35164. buffer.references = numOfMeshes;
  35165. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35166. if (!this._extend) {
  35167. this.updateExtend(this._vertexBuffers[kind].getData());
  35168. }
  35169. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35170. mesh._createGlobalSubMesh(false);
  35171. //bounding info was just created again, world matrix should be applied again.
  35172. mesh._updateBoundingInfo();
  35173. }
  35174. }
  35175. // indexBuffer
  35176. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35177. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35178. }
  35179. if (this._indexBuffer) {
  35180. this._indexBuffer.references = numOfMeshes;
  35181. }
  35182. };
  35183. Geometry.prototype.notifyUpdate = function (kind) {
  35184. if (this.onGeometryUpdated) {
  35185. this.onGeometryUpdated(this, kind);
  35186. }
  35187. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35188. var mesh = _a[_i];
  35189. mesh._markSubMeshesAsAttributesDirty();
  35190. }
  35191. };
  35192. /**
  35193. * Load the geometry if it was flagged as delay loaded
  35194. * @param scene defines the hosting scene
  35195. * @param onLoaded defines a callback called when the geometry is loaded
  35196. */
  35197. Geometry.prototype.load = function (scene, onLoaded) {
  35198. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35199. return;
  35200. }
  35201. if (this.isReady()) {
  35202. if (onLoaded) {
  35203. onLoaded();
  35204. }
  35205. return;
  35206. }
  35207. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35208. this._queueLoad(scene, onLoaded);
  35209. };
  35210. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35211. var _this = this;
  35212. if (!this.delayLoadingFile) {
  35213. return;
  35214. }
  35215. scene._addPendingData(this);
  35216. scene._loadFile(this.delayLoadingFile, function (data) {
  35217. if (!_this._delayLoadingFunction) {
  35218. return;
  35219. }
  35220. _this._delayLoadingFunction(JSON.parse(data), _this);
  35221. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35222. _this._delayInfo = [];
  35223. scene._removePendingData(_this);
  35224. var meshes = _this._meshes;
  35225. var numOfMeshes = meshes.length;
  35226. for (var index = 0; index < numOfMeshes; index++) {
  35227. _this._applyToMesh(meshes[index]);
  35228. }
  35229. if (onLoaded) {
  35230. onLoaded();
  35231. }
  35232. }, undefined, true);
  35233. };
  35234. /**
  35235. * Invert the geometry to move from a right handed system to a left handed one.
  35236. */
  35237. Geometry.prototype.toLeftHanded = function () {
  35238. // Flip faces
  35239. var tIndices = this.getIndices(false);
  35240. if (tIndices != null && tIndices.length > 0) {
  35241. for (var i = 0; i < tIndices.length; i += 3) {
  35242. var tTemp = tIndices[i + 0];
  35243. tIndices[i + 0] = tIndices[i + 2];
  35244. tIndices[i + 2] = tTemp;
  35245. }
  35246. this.setIndices(tIndices);
  35247. }
  35248. // Negate position.z
  35249. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35250. if (tPositions != null && tPositions.length > 0) {
  35251. for (var i = 0; i < tPositions.length; i += 3) {
  35252. tPositions[i + 2] = -tPositions[i + 2];
  35253. }
  35254. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35255. }
  35256. // Negate normal.z
  35257. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35258. if (tNormals != null && tNormals.length > 0) {
  35259. for (var i = 0; i < tNormals.length; i += 3) {
  35260. tNormals[i + 2] = -tNormals[i + 2];
  35261. }
  35262. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35263. }
  35264. };
  35265. // Cache
  35266. /** @ignore */
  35267. Geometry.prototype._resetPointsArrayCache = function () {
  35268. this._positions = null;
  35269. };
  35270. /** @ignore */
  35271. Geometry.prototype._generatePointsArray = function () {
  35272. if (this._positions)
  35273. return true;
  35274. this._positions = [];
  35275. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35276. if (!data) {
  35277. return false;
  35278. }
  35279. for (var index = 0; index < data.length; index += 3) {
  35280. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35281. }
  35282. return true;
  35283. };
  35284. /**
  35285. * Gets a value indicating if the geometry is disposed
  35286. * @returns true if the geometry was disposed
  35287. */
  35288. Geometry.prototype.isDisposed = function () {
  35289. return this._isDisposed;
  35290. };
  35291. Geometry.prototype._disposeVertexArrayObjects = function () {
  35292. if (this._vertexArrayObjects) {
  35293. for (var kind in this._vertexArrayObjects) {
  35294. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35295. }
  35296. this._vertexArrayObjects = {};
  35297. }
  35298. };
  35299. /**
  35300. * Free all associated resources
  35301. */
  35302. Geometry.prototype.dispose = function () {
  35303. var meshes = this._meshes;
  35304. var numOfMeshes = meshes.length;
  35305. var index;
  35306. for (index = 0; index < numOfMeshes; index++) {
  35307. this.releaseForMesh(meshes[index]);
  35308. }
  35309. this._meshes = [];
  35310. this._disposeVertexArrayObjects();
  35311. for (var kind in this._vertexBuffers) {
  35312. this._vertexBuffers[kind].dispose();
  35313. }
  35314. this._vertexBuffers = {};
  35315. this._totalVertices = 0;
  35316. if (this._indexBuffer) {
  35317. this._engine._releaseBuffer(this._indexBuffer);
  35318. }
  35319. this._indexBuffer = null;
  35320. this._indices = [];
  35321. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35322. this.delayLoadingFile = null;
  35323. this._delayLoadingFunction = null;
  35324. this._delayInfo = [];
  35325. this._boundingInfo = null;
  35326. this._scene.removeGeometry(this);
  35327. this._isDisposed = true;
  35328. };
  35329. /**
  35330. * Clone the current geometry into a new geometry
  35331. * @param id defines the unique ID of the new geometry
  35332. * @returns a new geometry object
  35333. */
  35334. Geometry.prototype.copy = function (id) {
  35335. var vertexData = new BABYLON.VertexData();
  35336. vertexData.indices = [];
  35337. var indices = this.getIndices();
  35338. if (indices) {
  35339. for (var index = 0; index < indices.length; index++) {
  35340. vertexData.indices.push(indices[index]);
  35341. }
  35342. }
  35343. var updatable = false;
  35344. var stopChecking = false;
  35345. var kind;
  35346. for (kind in this._vertexBuffers) {
  35347. // using slice() to make a copy of the array and not just reference it
  35348. var data = this.getVerticesData(kind);
  35349. if (data instanceof Float32Array) {
  35350. vertexData.set(new Float32Array(data), kind);
  35351. }
  35352. else {
  35353. vertexData.set(data.slice(0), kind);
  35354. }
  35355. if (!stopChecking) {
  35356. var vb = this.getVertexBuffer(kind);
  35357. if (vb) {
  35358. updatable = vb.isUpdatable();
  35359. stopChecking = !updatable;
  35360. }
  35361. }
  35362. }
  35363. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35364. geometry.delayLoadState = this.delayLoadState;
  35365. geometry.delayLoadingFile = this.delayLoadingFile;
  35366. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35367. for (kind in this._delayInfo) {
  35368. geometry._delayInfo = geometry._delayInfo || [];
  35369. geometry._delayInfo.push(kind);
  35370. }
  35371. // Bounding info
  35372. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35373. return geometry;
  35374. };
  35375. /**
  35376. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35377. * @return a JSON representation of the current geometry data (without the vertices data)
  35378. */
  35379. Geometry.prototype.serialize = function () {
  35380. var serializationObject = {};
  35381. serializationObject.id = this.id;
  35382. serializationObject.updatable = this._updatable;
  35383. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35384. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35385. }
  35386. return serializationObject;
  35387. };
  35388. Geometry.prototype.toNumberArray = function (origin) {
  35389. if (Array.isArray(origin)) {
  35390. return origin;
  35391. }
  35392. else {
  35393. return Array.prototype.slice.call(origin);
  35394. }
  35395. };
  35396. /**
  35397. * Serialize all vertices data into a JSON oject
  35398. * @returns a JSON representation of the current geometry data
  35399. */
  35400. Geometry.prototype.serializeVerticeData = function () {
  35401. var serializationObject = this.serialize();
  35402. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35403. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35404. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35405. serializationObject.positions._updatable = true;
  35406. }
  35407. }
  35408. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35409. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35410. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35411. serializationObject.normals._updatable = true;
  35412. }
  35413. }
  35414. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35415. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35416. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35417. serializationObject.tangets._updatable = true;
  35418. }
  35419. }
  35420. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35421. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35422. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35423. serializationObject.uvs._updatable = true;
  35424. }
  35425. }
  35426. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35427. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35428. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35429. serializationObject.uv2s._updatable = true;
  35430. }
  35431. }
  35432. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35433. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35434. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35435. serializationObject.uv3s._updatable = true;
  35436. }
  35437. }
  35438. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35439. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35440. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35441. serializationObject.uv4s._updatable = true;
  35442. }
  35443. }
  35444. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35445. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35446. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35447. serializationObject.uv5s._updatable = true;
  35448. }
  35449. }
  35450. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35451. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35452. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35453. serializationObject.uv6s._updatable = true;
  35454. }
  35455. }
  35456. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35457. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35458. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35459. serializationObject.colors._updatable = true;
  35460. }
  35461. }
  35462. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35463. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35464. serializationObject.matricesIndices._isExpanded = true;
  35465. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35466. serializationObject.matricesIndices._updatable = true;
  35467. }
  35468. }
  35469. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35470. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35471. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35472. serializationObject.matricesWeights._updatable = true;
  35473. }
  35474. }
  35475. serializationObject.indices = this.toNumberArray(this.getIndices());
  35476. return serializationObject;
  35477. };
  35478. // Statics
  35479. /**
  35480. * Extracts a clone of a mesh geometry
  35481. * @param mesh defines the source mesh
  35482. * @param id defines the unique ID of the new geometry object
  35483. * @returns the new geometry object
  35484. */
  35485. Geometry.ExtractFromMesh = function (mesh, id) {
  35486. var geometry = mesh._geometry;
  35487. if (!geometry) {
  35488. return null;
  35489. }
  35490. return geometry.copy(id);
  35491. };
  35492. /**
  35493. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35494. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35495. * Be aware Math.random() could cause collisions, but:
  35496. * "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"
  35497. * @returns a string containing a new GUID
  35498. */
  35499. Geometry.RandomId = function () {
  35500. return BABYLON.Tools.RandomId();
  35501. };
  35502. /** @ignore */
  35503. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35504. var scene = mesh.getScene();
  35505. // Geometry
  35506. var geometryId = parsedGeometry.geometryId;
  35507. if (geometryId) {
  35508. var geometry = scene.getGeometryByID(geometryId);
  35509. if (geometry) {
  35510. geometry.applyToMesh(mesh);
  35511. }
  35512. }
  35513. else if (parsedGeometry instanceof ArrayBuffer) {
  35514. var binaryInfo = mesh._binaryInfo;
  35515. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35516. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35517. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35518. }
  35519. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35520. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35521. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35522. }
  35523. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35524. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35525. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35526. }
  35527. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35528. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35529. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35530. }
  35531. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35532. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35533. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35534. }
  35535. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35536. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35537. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35538. }
  35539. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35540. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35541. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35542. }
  35543. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35544. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35545. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35546. }
  35547. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35548. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35549. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35550. }
  35551. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35552. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35553. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35554. }
  35555. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35556. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35557. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35558. }
  35559. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35560. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35561. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35562. }
  35563. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35564. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35565. mesh.setIndices(indicesData, null);
  35566. }
  35567. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35568. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35569. mesh.subMeshes = [];
  35570. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35571. var materialIndex = subMeshesData[(i * 5) + 0];
  35572. var verticesStart = subMeshesData[(i * 5) + 1];
  35573. var verticesCount = subMeshesData[(i * 5) + 2];
  35574. var indexStart = subMeshesData[(i * 5) + 3];
  35575. var indexCount = subMeshesData[(i * 5) + 4];
  35576. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35577. }
  35578. }
  35579. }
  35580. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35581. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35582. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35583. if (parsedGeometry.tangents) {
  35584. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35585. }
  35586. if (parsedGeometry.uvs) {
  35587. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35588. }
  35589. if (parsedGeometry.uvs2) {
  35590. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35591. }
  35592. if (parsedGeometry.uvs3) {
  35593. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35594. }
  35595. if (parsedGeometry.uvs4) {
  35596. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35597. }
  35598. if (parsedGeometry.uvs5) {
  35599. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35600. }
  35601. if (parsedGeometry.uvs6) {
  35602. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35603. }
  35604. if (parsedGeometry.colors) {
  35605. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35606. }
  35607. if (parsedGeometry.matricesIndices) {
  35608. if (!parsedGeometry.matricesIndices._isExpanded) {
  35609. var floatIndices = [];
  35610. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35611. var matricesIndex = parsedGeometry.matricesIndices[i];
  35612. floatIndices.push(matricesIndex & 0x000000FF);
  35613. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35614. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35615. floatIndices.push(matricesIndex >> 24);
  35616. }
  35617. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35618. }
  35619. else {
  35620. delete parsedGeometry.matricesIndices._isExpanded;
  35621. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35622. }
  35623. }
  35624. if (parsedGeometry.matricesIndicesExtra) {
  35625. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35626. var floatIndices = [];
  35627. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35628. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35629. floatIndices.push(matricesIndex & 0x000000FF);
  35630. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35631. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35632. floatIndices.push(matricesIndex >> 24);
  35633. }
  35634. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35635. }
  35636. else {
  35637. delete parsedGeometry.matricesIndices._isExpanded;
  35638. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35639. }
  35640. }
  35641. if (parsedGeometry.matricesWeights) {
  35642. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35643. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35644. }
  35645. if (parsedGeometry.matricesWeightsExtra) {
  35646. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35647. }
  35648. mesh.setIndices(parsedGeometry.indices, null);
  35649. }
  35650. // SubMeshes
  35651. if (parsedGeometry.subMeshes) {
  35652. mesh.subMeshes = [];
  35653. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35654. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35655. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35656. }
  35657. }
  35658. // Flat shading
  35659. if (mesh._shouldGenerateFlatShading) {
  35660. mesh.convertToFlatShadedMesh();
  35661. delete mesh._shouldGenerateFlatShading;
  35662. }
  35663. // Update
  35664. mesh.computeWorldMatrix(true);
  35665. // Octree
  35666. var sceneOctree = scene.selectionOctree;
  35667. if (sceneOctree !== undefined && sceneOctree !== null) {
  35668. sceneOctree.addMesh(mesh);
  35669. }
  35670. };
  35671. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35672. var epsilon = 1e-3;
  35673. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35674. return;
  35675. }
  35676. var noInfluenceBoneIndex = 0.0;
  35677. if (parsedGeometry.skeletonId > -1) {
  35678. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35679. if (!skeleton) {
  35680. return;
  35681. }
  35682. noInfluenceBoneIndex = skeleton.bones.length;
  35683. }
  35684. else {
  35685. return;
  35686. }
  35687. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35688. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35689. var matricesWeights = parsedGeometry.matricesWeights;
  35690. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35691. var influencers = parsedGeometry.numBoneInfluencer;
  35692. var size = matricesWeights.length;
  35693. for (var i = 0; i < size; i += 4) {
  35694. var weight = 0.0;
  35695. var firstZeroWeight = -1;
  35696. for (var j = 0; j < 4; j++) {
  35697. var w = matricesWeights[i + j];
  35698. weight += w;
  35699. if (w < epsilon && firstZeroWeight < 0) {
  35700. firstZeroWeight = j;
  35701. }
  35702. }
  35703. if (matricesWeightsExtra) {
  35704. for (var j = 0; j < 4; j++) {
  35705. var w = matricesWeightsExtra[i + j];
  35706. weight += w;
  35707. if (w < epsilon && firstZeroWeight < 0) {
  35708. firstZeroWeight = j + 4;
  35709. }
  35710. }
  35711. }
  35712. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35713. firstZeroWeight = influencers - 1;
  35714. }
  35715. if (weight > epsilon) {
  35716. var mweight = 1.0 / weight;
  35717. for (var j = 0; j < 4; j++) {
  35718. matricesWeights[i + j] *= mweight;
  35719. }
  35720. if (matricesWeightsExtra) {
  35721. for (var j = 0; j < 4; j++) {
  35722. matricesWeightsExtra[i + j] *= mweight;
  35723. }
  35724. }
  35725. }
  35726. else {
  35727. if (firstZeroWeight >= 4) {
  35728. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35729. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35730. }
  35731. else {
  35732. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35733. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35734. }
  35735. }
  35736. }
  35737. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35738. if (parsedGeometry.matricesWeightsExtra) {
  35739. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35740. }
  35741. };
  35742. /**
  35743. * Create a new geometry from persisted data (Using .babylon file format)
  35744. * @param parsedVertexData defines the persisted data
  35745. * @param scene defines the hosting scene
  35746. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35747. * @returns the new geometry object
  35748. */
  35749. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35750. if (scene.getGeometryByID(parsedVertexData.id)) {
  35751. return null; // null since geometry could be something else than a box...
  35752. }
  35753. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35754. if (BABYLON.Tags) {
  35755. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35756. }
  35757. if (parsedVertexData.delayLoadingFile) {
  35758. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35759. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35760. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35761. geometry._delayInfo = [];
  35762. if (parsedVertexData.hasUVs) {
  35763. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35764. }
  35765. if (parsedVertexData.hasUVs2) {
  35766. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35767. }
  35768. if (parsedVertexData.hasUVs3) {
  35769. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35770. }
  35771. if (parsedVertexData.hasUVs4) {
  35772. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35773. }
  35774. if (parsedVertexData.hasUVs5) {
  35775. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35776. }
  35777. if (parsedVertexData.hasUVs6) {
  35778. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35779. }
  35780. if (parsedVertexData.hasColors) {
  35781. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35782. }
  35783. if (parsedVertexData.hasMatricesIndices) {
  35784. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35785. }
  35786. if (parsedVertexData.hasMatricesWeights) {
  35787. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35788. }
  35789. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35790. }
  35791. else {
  35792. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35793. }
  35794. scene.pushGeometry(geometry, true);
  35795. return geometry;
  35796. };
  35797. return Geometry;
  35798. }());
  35799. BABYLON.Geometry = Geometry;
  35800. // Primitives
  35801. /// Abstract class
  35802. /**
  35803. * Abstract class used to provide common services for all typed geometries
  35804. */
  35805. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35806. __extends(_PrimitiveGeometry, _super);
  35807. /**
  35808. * Creates a new typed geometry
  35809. * @param id defines the unique ID of the geometry
  35810. * @param scene defines the hosting scene
  35811. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35812. * @param mesh defines the hosting mesh (can be null)
  35813. */
  35814. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35815. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35816. if (mesh === void 0) { mesh = null; }
  35817. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35818. _this._canBeRegenerated = _canBeRegenerated;
  35819. _this._beingRegenerated = true;
  35820. _this.regenerate();
  35821. _this._beingRegenerated = false;
  35822. return _this;
  35823. }
  35824. /**
  35825. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35826. * @returns true if the geometry can be regenerated
  35827. */
  35828. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35829. return this._canBeRegenerated;
  35830. };
  35831. /**
  35832. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35833. */
  35834. _PrimitiveGeometry.prototype.regenerate = function () {
  35835. if (!this._canBeRegenerated) {
  35836. return;
  35837. }
  35838. this._beingRegenerated = true;
  35839. this.setAllVerticesData(this._regenerateVertexData(), false);
  35840. this._beingRegenerated = false;
  35841. };
  35842. /**
  35843. * Clone the geometry
  35844. * @param id defines the unique ID of the new geometry
  35845. * @returns the new geometry
  35846. */
  35847. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35848. return _super.prototype.copy.call(this, id);
  35849. };
  35850. // overrides
  35851. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35852. if (!this._beingRegenerated) {
  35853. return;
  35854. }
  35855. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35856. };
  35857. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35858. if (!this._beingRegenerated) {
  35859. return;
  35860. }
  35861. _super.prototype.setVerticesData.call(this, kind, data, false);
  35862. };
  35863. // to override
  35864. /** @ignore */
  35865. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35866. throw new Error("Abstract method");
  35867. };
  35868. _PrimitiveGeometry.prototype.copy = function (id) {
  35869. throw new Error("Must be overriden in sub-classes.");
  35870. };
  35871. _PrimitiveGeometry.prototype.serialize = function () {
  35872. var serializationObject = _super.prototype.serialize.call(this);
  35873. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35874. return serializationObject;
  35875. };
  35876. return _PrimitiveGeometry;
  35877. }(Geometry));
  35878. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35879. /**
  35880. * Creates a ribbon geometry
  35881. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35882. */
  35883. var RibbonGeometry = /** @class */ (function (_super) {
  35884. __extends(RibbonGeometry, _super);
  35885. /**
  35886. * Creates a ribbon geometry
  35887. * @param id defines the unique ID of the geometry
  35888. * @param scene defines the hosting scene
  35889. * @param pathArray defines the array of paths to use
  35890. * @param closeArray defines if the last path and the first path must be joined
  35891. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35892. * @param offset defines the offset between points
  35893. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35894. * @param mesh defines the hosting mesh (can be null)
  35895. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35896. */
  35897. function RibbonGeometry(id, scene,
  35898. /**
  35899. * Defines the array of paths to use
  35900. */
  35901. pathArray,
  35902. /**
  35903. * Defines if the last and first points of each path in your pathArray must be joined
  35904. */
  35905. closeArray,
  35906. /**
  35907. * Defines if the last and first points of each path in your pathArray must be joined
  35908. */
  35909. closePath,
  35910. /**
  35911. * Defines the offset between points
  35912. */
  35913. offset, canBeRegenerated, mesh,
  35914. /**
  35915. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35916. */
  35917. side) {
  35918. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35919. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35920. _this.pathArray = pathArray;
  35921. _this.closeArray = closeArray;
  35922. _this.closePath = closePath;
  35923. _this.offset = offset;
  35924. _this.side = side;
  35925. return _this;
  35926. }
  35927. /** @ignore */
  35928. RibbonGeometry.prototype._regenerateVertexData = function () {
  35929. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35930. };
  35931. RibbonGeometry.prototype.copy = function (id) {
  35932. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35933. };
  35934. return RibbonGeometry;
  35935. }(_PrimitiveGeometry));
  35936. BABYLON.RibbonGeometry = RibbonGeometry;
  35937. /**
  35938. * Creates a box geometry
  35939. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35940. */
  35941. var BoxGeometry = /** @class */ (function (_super) {
  35942. __extends(BoxGeometry, _super);
  35943. /**
  35944. * Creates a box geometry
  35945. * @param id defines the unique ID of the geometry
  35946. * @param scene defines the hosting scene
  35947. * @param size defines the zise of the box (width, height and depth are the same)
  35948. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35949. * @param mesh defines the hosting mesh (can be null)
  35950. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35951. */
  35952. function BoxGeometry(id, scene,
  35953. /**
  35954. * Defines the zise of the box (width, height and depth are the same)
  35955. */
  35956. size, canBeRegenerated, mesh,
  35957. /**
  35958. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35959. */
  35960. side) {
  35961. if (mesh === void 0) { mesh = null; }
  35962. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35963. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35964. _this.size = size;
  35965. _this.side = side;
  35966. return _this;
  35967. }
  35968. BoxGeometry.prototype._regenerateVertexData = function () {
  35969. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35970. };
  35971. BoxGeometry.prototype.copy = function (id) {
  35972. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35973. };
  35974. BoxGeometry.prototype.serialize = function () {
  35975. var serializationObject = _super.prototype.serialize.call(this);
  35976. serializationObject.size = this.size;
  35977. return serializationObject;
  35978. };
  35979. BoxGeometry.Parse = function (parsedBox, scene) {
  35980. if (scene.getGeometryByID(parsedBox.id)) {
  35981. return null; // null since geometry could be something else than a box...
  35982. }
  35983. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35984. if (BABYLON.Tags) {
  35985. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35986. }
  35987. scene.pushGeometry(box, true);
  35988. return box;
  35989. };
  35990. return BoxGeometry;
  35991. }(_PrimitiveGeometry));
  35992. BABYLON.BoxGeometry = BoxGeometry;
  35993. /**
  35994. * Creates a sphere geometry
  35995. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35996. */
  35997. var SphereGeometry = /** @class */ (function (_super) {
  35998. __extends(SphereGeometry, _super);
  35999. /**
  36000. * Create a new sphere geometry
  36001. * @param id defines the unique ID of the geometry
  36002. * @param scene defines the hosting scene
  36003. * @param segments defines the number of segments to use to create the sphere
  36004. * @param diameter defines the diameter of the sphere
  36005. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36006. * @param mesh defines the hosting mesh (can be null)
  36007. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36008. */
  36009. function SphereGeometry(id, scene,
  36010. /**
  36011. * Defines the number of segments to use to create the sphere
  36012. */
  36013. segments,
  36014. /**
  36015. * Defines the diameter of the sphere
  36016. */
  36017. diameter, canBeRegenerated, mesh,
  36018. /**
  36019. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36020. */
  36021. side) {
  36022. if (mesh === void 0) { mesh = null; }
  36023. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36024. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36025. _this.segments = segments;
  36026. _this.diameter = diameter;
  36027. _this.side = side;
  36028. return _this;
  36029. }
  36030. SphereGeometry.prototype._regenerateVertexData = function () {
  36031. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36032. };
  36033. SphereGeometry.prototype.copy = function (id) {
  36034. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36035. };
  36036. SphereGeometry.prototype.serialize = function () {
  36037. var serializationObject = _super.prototype.serialize.call(this);
  36038. serializationObject.segments = this.segments;
  36039. serializationObject.diameter = this.diameter;
  36040. return serializationObject;
  36041. };
  36042. SphereGeometry.Parse = function (parsedSphere, scene) {
  36043. if (scene.getGeometryByID(parsedSphere.id)) {
  36044. return null; // null since geometry could be something else than a sphere...
  36045. }
  36046. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36047. if (BABYLON.Tags) {
  36048. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36049. }
  36050. scene.pushGeometry(sphere, true);
  36051. return sphere;
  36052. };
  36053. return SphereGeometry;
  36054. }(_PrimitiveGeometry));
  36055. BABYLON.SphereGeometry = SphereGeometry;
  36056. /**
  36057. * Creates a disc geometry
  36058. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36059. */
  36060. var DiscGeometry = /** @class */ (function (_super) {
  36061. __extends(DiscGeometry, _super);
  36062. /**
  36063. * Creates a new disc geometry
  36064. * @param id defines the unique ID of the geometry
  36065. * @param scene defines the hosting scene
  36066. * @param radius defines the radius of the disc
  36067. * @param tessellation defines the tesselation factor to apply to the disc
  36068. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36069. * @param mesh defines the hosting mesh (can be null)
  36070. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36071. */
  36072. function DiscGeometry(id, scene,
  36073. /**
  36074. * Defines the radius of the disc
  36075. */
  36076. radius,
  36077. /**
  36078. * Defines the tesselation factor to apply to the disc
  36079. */
  36080. tessellation, canBeRegenerated, mesh,
  36081. /**
  36082. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36083. */
  36084. side) {
  36085. if (mesh === void 0) { mesh = null; }
  36086. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36087. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36088. _this.radius = radius;
  36089. _this.tessellation = tessellation;
  36090. _this.side = side;
  36091. return _this;
  36092. }
  36093. DiscGeometry.prototype._regenerateVertexData = function () {
  36094. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36095. };
  36096. DiscGeometry.prototype.copy = function (id) {
  36097. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36098. };
  36099. return DiscGeometry;
  36100. }(_PrimitiveGeometry));
  36101. BABYLON.DiscGeometry = DiscGeometry;
  36102. /**
  36103. * Creates a new cylinder geometry
  36104. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36105. */
  36106. var CylinderGeometry = /** @class */ (function (_super) {
  36107. __extends(CylinderGeometry, _super);
  36108. /**
  36109. * Creates a new cylinder geometry
  36110. * @param id defines the unique ID of the geometry
  36111. * @param scene defines the hosting scene
  36112. * @param height defines the height of the cylinder
  36113. * @param diameterTop defines the diameter of the cylinder's top cap
  36114. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36115. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36116. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36117. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36118. * @param mesh defines the hosting mesh (can be null)
  36119. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36120. */
  36121. function CylinderGeometry(id, scene,
  36122. /**
  36123. * Defines the height of the cylinder
  36124. */
  36125. height,
  36126. /**
  36127. * Defines the diameter of the cylinder's top cap
  36128. */
  36129. diameterTop,
  36130. /**
  36131. * Defines the diameter of the cylinder's bottom cap
  36132. */
  36133. diameterBottom,
  36134. /**
  36135. * Defines the tessellation factor to apply to the cylinder
  36136. */
  36137. tessellation,
  36138. /**
  36139. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36140. */
  36141. subdivisions, canBeRegenerated, mesh,
  36142. /**
  36143. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36144. */
  36145. side) {
  36146. if (subdivisions === void 0) { subdivisions = 1; }
  36147. if (mesh === void 0) { mesh = null; }
  36148. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36149. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36150. _this.height = height;
  36151. _this.diameterTop = diameterTop;
  36152. _this.diameterBottom = diameterBottom;
  36153. _this.tessellation = tessellation;
  36154. _this.subdivisions = subdivisions;
  36155. _this.side = side;
  36156. return _this;
  36157. }
  36158. CylinderGeometry.prototype._regenerateVertexData = function () {
  36159. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36160. };
  36161. CylinderGeometry.prototype.copy = function (id) {
  36162. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36163. };
  36164. CylinderGeometry.prototype.serialize = function () {
  36165. var serializationObject = _super.prototype.serialize.call(this);
  36166. serializationObject.height = this.height;
  36167. serializationObject.diameterTop = this.diameterTop;
  36168. serializationObject.diameterBottom = this.diameterBottom;
  36169. serializationObject.tessellation = this.tessellation;
  36170. return serializationObject;
  36171. };
  36172. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36173. if (scene.getGeometryByID(parsedCylinder.id)) {
  36174. return null; // null since geometry could be something else than a cylinder...
  36175. }
  36176. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36177. if (BABYLON.Tags) {
  36178. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36179. }
  36180. scene.pushGeometry(cylinder, true);
  36181. return cylinder;
  36182. };
  36183. return CylinderGeometry;
  36184. }(_PrimitiveGeometry));
  36185. BABYLON.CylinderGeometry = CylinderGeometry;
  36186. /**
  36187. * Creates a new torus geometry
  36188. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36189. */
  36190. var TorusGeometry = /** @class */ (function (_super) {
  36191. __extends(TorusGeometry, _super);
  36192. /**
  36193. * Creates a new torus geometry
  36194. * @param id defines the unique ID of the geometry
  36195. * @param scene defines the hosting scene
  36196. * @param diameter defines the diameter of the torus
  36197. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36198. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36199. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36200. * @param mesh defines the hosting mesh (can be null)
  36201. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36202. */
  36203. function TorusGeometry(id, scene,
  36204. /**
  36205. * Defines the diameter of the torus
  36206. */
  36207. diameter,
  36208. /**
  36209. * Defines the thickness of the torus (ie. internal diameter)
  36210. */
  36211. thickness,
  36212. /**
  36213. * Defines the tesselation factor to apply to the torus
  36214. */
  36215. tessellation, canBeRegenerated, mesh,
  36216. /**
  36217. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36218. */
  36219. side) {
  36220. if (mesh === void 0) { mesh = null; }
  36221. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36222. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36223. _this.diameter = diameter;
  36224. _this.thickness = thickness;
  36225. _this.tessellation = tessellation;
  36226. _this.side = side;
  36227. return _this;
  36228. }
  36229. TorusGeometry.prototype._regenerateVertexData = function () {
  36230. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36231. };
  36232. TorusGeometry.prototype.copy = function (id) {
  36233. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36234. };
  36235. TorusGeometry.prototype.serialize = function () {
  36236. var serializationObject = _super.prototype.serialize.call(this);
  36237. serializationObject.diameter = this.diameter;
  36238. serializationObject.thickness = this.thickness;
  36239. serializationObject.tessellation = this.tessellation;
  36240. return serializationObject;
  36241. };
  36242. TorusGeometry.Parse = function (parsedTorus, scene) {
  36243. if (scene.getGeometryByID(parsedTorus.id)) {
  36244. return null; // null since geometry could be something else than a torus...
  36245. }
  36246. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36247. if (BABYLON.Tags) {
  36248. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36249. }
  36250. scene.pushGeometry(torus, true);
  36251. return torus;
  36252. };
  36253. return TorusGeometry;
  36254. }(_PrimitiveGeometry));
  36255. BABYLON.TorusGeometry = TorusGeometry;
  36256. /**
  36257. * Creates a new ground geometry
  36258. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36259. */
  36260. var GroundGeometry = /** @class */ (function (_super) {
  36261. __extends(GroundGeometry, _super);
  36262. /**
  36263. * Creates a new ground geometry
  36264. * @param id defines the unique ID of the geometry
  36265. * @param scene defines the hosting scene
  36266. * @param width defines the width of the ground
  36267. * @param height defines the height of the ground
  36268. * @param subdivisions defines the subdivisions to apply to the ground
  36269. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36270. * @param mesh defines the hosting mesh (can be null)
  36271. */
  36272. function GroundGeometry(id, scene,
  36273. /**
  36274. * Defines the width of the ground
  36275. */
  36276. width,
  36277. /**
  36278. * Defines the height of the ground
  36279. */
  36280. height,
  36281. /**
  36282. * Defines the subdivisions to apply to the ground
  36283. */
  36284. subdivisions, canBeRegenerated, mesh) {
  36285. if (mesh === void 0) { mesh = null; }
  36286. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36287. _this.width = width;
  36288. _this.height = height;
  36289. _this.subdivisions = subdivisions;
  36290. return _this;
  36291. }
  36292. GroundGeometry.prototype._regenerateVertexData = function () {
  36293. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36294. };
  36295. GroundGeometry.prototype.copy = function (id) {
  36296. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36297. };
  36298. GroundGeometry.prototype.serialize = function () {
  36299. var serializationObject = _super.prototype.serialize.call(this);
  36300. serializationObject.width = this.width;
  36301. serializationObject.height = this.height;
  36302. serializationObject.subdivisions = this.subdivisions;
  36303. return serializationObject;
  36304. };
  36305. GroundGeometry.Parse = function (parsedGround, scene) {
  36306. if (scene.getGeometryByID(parsedGround.id)) {
  36307. return null; // null since geometry could be something else than a ground...
  36308. }
  36309. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36310. if (BABYLON.Tags) {
  36311. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36312. }
  36313. scene.pushGeometry(ground, true);
  36314. return ground;
  36315. };
  36316. return GroundGeometry;
  36317. }(_PrimitiveGeometry));
  36318. BABYLON.GroundGeometry = GroundGeometry;
  36319. /**
  36320. * Creates a tiled ground geometry
  36321. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36322. */
  36323. var TiledGroundGeometry = /** @class */ (function (_super) {
  36324. __extends(TiledGroundGeometry, _super);
  36325. /**
  36326. * Creates a tiled ground geometry
  36327. * @param id defines the unique ID of the geometry
  36328. * @param scene defines the hosting scene
  36329. * @param xmin defines the minimum value on X axis
  36330. * @param zmin defines the minimum value on Z axis
  36331. * @param xmax defines the maximum value on X axis
  36332. * @param zmax defines the maximum value on Z axis
  36333. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36334. * @param precision defines the precision to use when computing the tiles
  36335. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36336. * @param mesh defines the hosting mesh (can be null)
  36337. */
  36338. function TiledGroundGeometry(id, scene,
  36339. /**
  36340. * Defines the minimum value on X axis
  36341. */
  36342. xmin,
  36343. /**
  36344. * Defines the minimum value on Z axis
  36345. */
  36346. zmin,
  36347. /**
  36348. * Defines the maximum value on X axis
  36349. */
  36350. xmax,
  36351. /**
  36352. * Defines the maximum value on Z axis
  36353. */
  36354. zmax,
  36355. /**
  36356. * Defines the subdivisions to apply to the ground
  36357. */
  36358. subdivisions,
  36359. /**
  36360. * Defines the precision to use when computing the tiles
  36361. */
  36362. precision, canBeRegenerated, mesh) {
  36363. if (mesh === void 0) { mesh = null; }
  36364. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36365. _this.xmin = xmin;
  36366. _this.zmin = zmin;
  36367. _this.xmax = xmax;
  36368. _this.zmax = zmax;
  36369. _this.subdivisions = subdivisions;
  36370. _this.precision = precision;
  36371. return _this;
  36372. }
  36373. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36374. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36375. };
  36376. TiledGroundGeometry.prototype.copy = function (id) {
  36377. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36378. };
  36379. return TiledGroundGeometry;
  36380. }(_PrimitiveGeometry));
  36381. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36382. /**
  36383. * Creates a plane geometry
  36384. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36385. */
  36386. var PlaneGeometry = /** @class */ (function (_super) {
  36387. __extends(PlaneGeometry, _super);
  36388. /**
  36389. * Creates a plane geometry
  36390. * @param id defines the unique ID of the geometry
  36391. * @param scene defines the hosting scene
  36392. * @param size defines the size of the plane (width === height)
  36393. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36394. * @param mesh defines the hosting mesh (can be null)
  36395. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36396. */
  36397. function PlaneGeometry(id, scene,
  36398. /**
  36399. * Defines the size of the plane (width === height)
  36400. */
  36401. size, canBeRegenerated, mesh,
  36402. /**
  36403. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36404. */
  36405. side) {
  36406. if (mesh === void 0) { mesh = null; }
  36407. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36408. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36409. _this.size = size;
  36410. _this.side = side;
  36411. return _this;
  36412. }
  36413. PlaneGeometry.prototype._regenerateVertexData = function () {
  36414. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36415. };
  36416. PlaneGeometry.prototype.copy = function (id) {
  36417. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36418. };
  36419. PlaneGeometry.prototype.serialize = function () {
  36420. var serializationObject = _super.prototype.serialize.call(this);
  36421. serializationObject.size = this.size;
  36422. return serializationObject;
  36423. };
  36424. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36425. if (scene.getGeometryByID(parsedPlane.id)) {
  36426. return null; // null since geometry could be something else than a ground...
  36427. }
  36428. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36429. if (BABYLON.Tags) {
  36430. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36431. }
  36432. scene.pushGeometry(plane, true);
  36433. return plane;
  36434. };
  36435. return PlaneGeometry;
  36436. }(_PrimitiveGeometry));
  36437. BABYLON.PlaneGeometry = PlaneGeometry;
  36438. /**
  36439. * Creates a torus knot geometry
  36440. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36441. */
  36442. var TorusKnotGeometry = /** @class */ (function (_super) {
  36443. __extends(TorusKnotGeometry, _super);
  36444. /**
  36445. * Creates a torus knot geometry
  36446. * @param id defines the unique ID of the geometry
  36447. * @param scene defines the hosting scene
  36448. * @param radius defines the radius of the torus knot
  36449. * @param tube defines the thickness of the torus knot tube
  36450. * @param radialSegments defines the number of radial segments
  36451. * @param tubularSegments defines the number of tubular segments
  36452. * @param p defines the first number of windings
  36453. * @param q defines the second number of windings
  36454. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36455. * @param mesh defines the hosting mesh (can be null)
  36456. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36457. */
  36458. function TorusKnotGeometry(id, scene,
  36459. /**
  36460. * Defines the radius of the torus knot
  36461. */
  36462. radius,
  36463. /**
  36464. * Defines the thickness of the torus knot tube
  36465. */
  36466. tube,
  36467. /**
  36468. * Defines the number of radial segments
  36469. */
  36470. radialSegments,
  36471. /**
  36472. * Defines the number of tubular segments
  36473. */
  36474. tubularSegments,
  36475. /**
  36476. * Defines the first number of windings
  36477. */
  36478. p,
  36479. /**
  36480. * Defines the second number of windings
  36481. */
  36482. q, canBeRegenerated, mesh,
  36483. /**
  36484. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36485. */
  36486. side) {
  36487. if (mesh === void 0) { mesh = null; }
  36488. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36489. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36490. _this.radius = radius;
  36491. _this.tube = tube;
  36492. _this.radialSegments = radialSegments;
  36493. _this.tubularSegments = tubularSegments;
  36494. _this.p = p;
  36495. _this.q = q;
  36496. _this.side = side;
  36497. return _this;
  36498. }
  36499. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36500. 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 });
  36501. };
  36502. TorusKnotGeometry.prototype.copy = function (id) {
  36503. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36504. };
  36505. TorusKnotGeometry.prototype.serialize = function () {
  36506. var serializationObject = _super.prototype.serialize.call(this);
  36507. serializationObject.radius = this.radius;
  36508. serializationObject.tube = this.tube;
  36509. serializationObject.radialSegments = this.radialSegments;
  36510. serializationObject.tubularSegments = this.tubularSegments;
  36511. serializationObject.p = this.p;
  36512. serializationObject.q = this.q;
  36513. return serializationObject;
  36514. };
  36515. ;
  36516. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36517. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36518. return null; // null since geometry could be something else than a ground...
  36519. }
  36520. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36521. if (BABYLON.Tags) {
  36522. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36523. }
  36524. scene.pushGeometry(torusKnot, true);
  36525. return torusKnot;
  36526. };
  36527. return TorusKnotGeometry;
  36528. }(_PrimitiveGeometry));
  36529. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36530. //}
  36531. })(BABYLON || (BABYLON = {}));
  36532. //# sourceMappingURL=babylon.geometry.js.map
  36533. var BABYLON;
  36534. (function (BABYLON) {
  36535. /**
  36536. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36537. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36538. */
  36539. var PostProcessManager = /** @class */ (function () {
  36540. /**
  36541. * Creates a new instance of @see PostProcess
  36542. * @param scene The scene that the post process is associated with.
  36543. */
  36544. function PostProcessManager(scene) {
  36545. this._vertexBuffers = {};
  36546. this._scene = scene;
  36547. }
  36548. PostProcessManager.prototype._prepareBuffers = function () {
  36549. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36550. return;
  36551. }
  36552. // VBO
  36553. var vertices = [];
  36554. vertices.push(1, 1);
  36555. vertices.push(-1, 1);
  36556. vertices.push(-1, -1);
  36557. vertices.push(1, -1);
  36558. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36559. this._buildIndexBuffer();
  36560. };
  36561. PostProcessManager.prototype._buildIndexBuffer = function () {
  36562. // Indices
  36563. var indices = [];
  36564. indices.push(0);
  36565. indices.push(1);
  36566. indices.push(2);
  36567. indices.push(0);
  36568. indices.push(2);
  36569. indices.push(3);
  36570. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36571. };
  36572. /**
  36573. * Rebuilds the vertex buffers of the manager.
  36574. */
  36575. PostProcessManager.prototype._rebuild = function () {
  36576. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36577. if (!vb) {
  36578. return;
  36579. }
  36580. vb._rebuild();
  36581. this._buildIndexBuffer();
  36582. };
  36583. // Methods
  36584. /**
  36585. * Prepares a frame to be run through a post process.
  36586. * @param sourceTexture The input texture to the post procesess. (default: null)
  36587. * @param postProcesses An array of post processes to be run. (default: null)
  36588. * @returns True if the post processes were able to be run.
  36589. */
  36590. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36591. if (sourceTexture === void 0) { sourceTexture = null; }
  36592. if (postProcesses === void 0) { postProcesses = null; }
  36593. var camera = this._scene.activeCamera;
  36594. if (!camera) {
  36595. return false;
  36596. }
  36597. var postProcesses = postProcesses || camera._postProcesses;
  36598. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36599. return false;
  36600. }
  36601. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36602. return true;
  36603. };
  36604. /**
  36605. * Manually render a set of post processes to a texture.
  36606. * @param postProcesses An array of post processes to be run.
  36607. * @param targetTexture The target texture to render to.
  36608. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36609. */
  36610. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36611. if (targetTexture === void 0) { targetTexture = null; }
  36612. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36613. var engine = this._scene.getEngine();
  36614. for (var index = 0; index < postProcesses.length; index++) {
  36615. if (index < postProcesses.length - 1) {
  36616. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36617. }
  36618. else {
  36619. if (targetTexture) {
  36620. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36621. }
  36622. else {
  36623. engine.restoreDefaultFramebuffer();
  36624. }
  36625. }
  36626. var pp = postProcesses[index];
  36627. var effect = pp.apply();
  36628. if (effect) {
  36629. pp.onBeforeRenderObservable.notifyObservers(effect);
  36630. // VBOs
  36631. this._prepareBuffers();
  36632. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36633. // Draw order
  36634. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36635. pp.onAfterRenderObservable.notifyObservers(effect);
  36636. }
  36637. }
  36638. // Restore depth buffer
  36639. engine.setDepthBuffer(true);
  36640. engine.setDepthWrite(true);
  36641. };
  36642. /**
  36643. * Finalize the result of the output of the postprocesses.
  36644. * @param doNotPresent If true the result will not be displayed to the screen.
  36645. * @param targetTexture The target texture to render to.
  36646. * @param faceIndex The index of the face to bind the target texture to.
  36647. * @param postProcesses The array of post processes to render.
  36648. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36649. */
  36650. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36651. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36652. var camera = this._scene.activeCamera;
  36653. if (!camera) {
  36654. return;
  36655. }
  36656. postProcesses = postProcesses || camera._postProcesses;
  36657. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36658. return;
  36659. }
  36660. var engine = this._scene.getEngine();
  36661. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36662. if (index < len - 1) {
  36663. postProcesses[index + 1].activate(camera, targetTexture);
  36664. }
  36665. else {
  36666. if (targetTexture) {
  36667. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36668. }
  36669. else {
  36670. engine.restoreDefaultFramebuffer();
  36671. }
  36672. }
  36673. if (doNotPresent) {
  36674. break;
  36675. }
  36676. var pp = postProcesses[index];
  36677. var effect = pp.apply();
  36678. if (effect) {
  36679. pp.onBeforeRenderObservable.notifyObservers(effect);
  36680. // VBOs
  36681. this._prepareBuffers();
  36682. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36683. // Draw order
  36684. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36685. pp.onAfterRenderObservable.notifyObservers(effect);
  36686. }
  36687. }
  36688. // Restore states
  36689. engine.setDepthBuffer(true);
  36690. engine.setDepthWrite(true);
  36691. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36692. };
  36693. /**
  36694. * Disposes of the post process manager.
  36695. */
  36696. PostProcessManager.prototype.dispose = function () {
  36697. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36698. if (buffer) {
  36699. buffer.dispose();
  36700. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36701. }
  36702. if (this._indexBuffer) {
  36703. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36704. this._indexBuffer = null;
  36705. }
  36706. };
  36707. return PostProcessManager;
  36708. }());
  36709. BABYLON.PostProcessManager = PostProcessManager;
  36710. })(BABYLON || (BABYLON = {}));
  36711. //# sourceMappingURL=babylon.postProcessManager.js.map
  36712. var BABYLON;
  36713. (function (BABYLON) {
  36714. /**
  36715. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36716. */
  36717. var PerformanceMonitor = /** @class */ (function () {
  36718. /**
  36719. * constructor
  36720. * @param frameSampleSize The number of samples required to saturate the sliding window
  36721. */
  36722. function PerformanceMonitor(frameSampleSize) {
  36723. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36724. this._enabled = true;
  36725. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36726. }
  36727. /**
  36728. * Samples current frame
  36729. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36730. */
  36731. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36732. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36733. if (!this._enabled)
  36734. return;
  36735. if (this._lastFrameTimeMs != null) {
  36736. var dt = timeMs - this._lastFrameTimeMs;
  36737. this._rollingFrameTime.add(dt);
  36738. }
  36739. this._lastFrameTimeMs = timeMs;
  36740. };
  36741. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36742. /**
  36743. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36744. * @return Average frame time in milliseconds
  36745. */
  36746. get: function () {
  36747. return this._rollingFrameTime.average;
  36748. },
  36749. enumerable: true,
  36750. configurable: true
  36751. });
  36752. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36753. /**
  36754. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36755. * @return Frame time variance in milliseconds squared
  36756. */
  36757. get: function () {
  36758. return this._rollingFrameTime.variance;
  36759. },
  36760. enumerable: true,
  36761. configurable: true
  36762. });
  36763. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36764. /**
  36765. * Returns the frame time of the most recent frame
  36766. * @return Frame time in milliseconds
  36767. */
  36768. get: function () {
  36769. return this._rollingFrameTime.history(0);
  36770. },
  36771. enumerable: true,
  36772. configurable: true
  36773. });
  36774. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36775. /**
  36776. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36777. * @return Framerate in frames per second
  36778. */
  36779. get: function () {
  36780. return 1000.0 / this._rollingFrameTime.average;
  36781. },
  36782. enumerable: true,
  36783. configurable: true
  36784. });
  36785. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36786. /**
  36787. * Returns the average framerate in frames per second using the most recent frame time
  36788. * @return Framerate in frames per second
  36789. */
  36790. get: function () {
  36791. var history = this._rollingFrameTime.history(0);
  36792. if (history === 0) {
  36793. return 0;
  36794. }
  36795. return 1000.0 / history;
  36796. },
  36797. enumerable: true,
  36798. configurable: true
  36799. });
  36800. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36801. /**
  36802. * Returns true if enough samples have been taken to completely fill the sliding window
  36803. * @return true if saturated
  36804. */
  36805. get: function () {
  36806. return this._rollingFrameTime.isSaturated();
  36807. },
  36808. enumerable: true,
  36809. configurable: true
  36810. });
  36811. /**
  36812. * Enables contributions to the sliding window sample set
  36813. */
  36814. PerformanceMonitor.prototype.enable = function () {
  36815. this._enabled = true;
  36816. };
  36817. /**
  36818. * Disables contributions to the sliding window sample set
  36819. * Samples will not be interpolated over the disabled period
  36820. */
  36821. PerformanceMonitor.prototype.disable = function () {
  36822. this._enabled = false;
  36823. //clear last sample to avoid interpolating over the disabled period when next enabled
  36824. this._lastFrameTimeMs = null;
  36825. };
  36826. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36827. /**
  36828. * Returns true if sampling is enabled
  36829. * @return true if enabled
  36830. */
  36831. get: function () {
  36832. return this._enabled;
  36833. },
  36834. enumerable: true,
  36835. configurable: true
  36836. });
  36837. /**
  36838. * Resets performance monitor
  36839. */
  36840. PerformanceMonitor.prototype.reset = function () {
  36841. //clear last sample to avoid interpolating over the disabled period when next enabled
  36842. this._lastFrameTimeMs = null;
  36843. //wipe record
  36844. this._rollingFrameTime.reset();
  36845. };
  36846. return PerformanceMonitor;
  36847. }());
  36848. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36849. /**
  36850. * RollingAverage
  36851. *
  36852. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36853. */
  36854. var RollingAverage = /** @class */ (function () {
  36855. /**
  36856. * constructor
  36857. * @param length The number of samples required to saturate the sliding window
  36858. */
  36859. function RollingAverage(length) {
  36860. this._samples = new Array(length);
  36861. this.reset();
  36862. }
  36863. /**
  36864. * Adds a sample to the sample set
  36865. * @param v The sample value
  36866. */
  36867. RollingAverage.prototype.add = function (v) {
  36868. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36869. var delta;
  36870. //we need to check if we've already wrapped round
  36871. if (this.isSaturated()) {
  36872. //remove bottom of stack from mean
  36873. var bottomValue = this._samples[this._pos];
  36874. delta = bottomValue - this.average;
  36875. this.average -= delta / (this._sampleCount - 1);
  36876. this._m2 -= delta * (bottomValue - this.average);
  36877. }
  36878. else {
  36879. this._sampleCount++;
  36880. }
  36881. //add new value to mean
  36882. delta = v - this.average;
  36883. this.average += delta / (this._sampleCount);
  36884. this._m2 += delta * (v - this.average);
  36885. //set the new variance
  36886. this.variance = this._m2 / (this._sampleCount - 1);
  36887. this._samples[this._pos] = v;
  36888. this._pos++;
  36889. this._pos %= this._samples.length; //positive wrap around
  36890. };
  36891. /**
  36892. * Returns previously added values or null if outside of history or outside the sliding window domain
  36893. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36894. * @return Value previously recorded with add() or null if outside of range
  36895. */
  36896. RollingAverage.prototype.history = function (i) {
  36897. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36898. return 0;
  36899. }
  36900. var i0 = this._wrapPosition(this._pos - 1.0);
  36901. return this._samples[this._wrapPosition(i0 - i)];
  36902. };
  36903. /**
  36904. * Returns true if enough samples have been taken to completely fill the sliding window
  36905. * @return true if sample-set saturated
  36906. */
  36907. RollingAverage.prototype.isSaturated = function () {
  36908. return this._sampleCount >= this._samples.length;
  36909. };
  36910. /**
  36911. * Resets the rolling average (equivalent to 0 samples taken so far)
  36912. */
  36913. RollingAverage.prototype.reset = function () {
  36914. this.average = 0;
  36915. this.variance = 0;
  36916. this._sampleCount = 0;
  36917. this._pos = 0;
  36918. this._m2 = 0;
  36919. };
  36920. /**
  36921. * Wraps a value around the sample range boundaries
  36922. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36923. * @return Wrapped position in sample range
  36924. */
  36925. RollingAverage.prototype._wrapPosition = function (i) {
  36926. var max = this._samples.length;
  36927. return ((i % max) + max) % max;
  36928. };
  36929. return RollingAverage;
  36930. }());
  36931. BABYLON.RollingAverage = RollingAverage;
  36932. })(BABYLON || (BABYLON = {}));
  36933. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36934. var BABYLON;
  36935. (function (BABYLON) {
  36936. /**
  36937. * This groups together the common properties used for image processing either in direct forward pass
  36938. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36939. * or not.
  36940. */
  36941. var ImageProcessingConfiguration = /** @class */ (function () {
  36942. function ImageProcessingConfiguration() {
  36943. /**
  36944. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36945. */
  36946. this.colorCurves = new BABYLON.ColorCurves();
  36947. this._colorCurvesEnabled = false;
  36948. this._colorGradingEnabled = false;
  36949. this._colorGradingWithGreenDepth = true;
  36950. this._colorGradingBGR = true;
  36951. this._exposure = 1.0;
  36952. this._toneMappingEnabled = false;
  36953. this._contrast = 1.0;
  36954. /**
  36955. * Vignette stretch size.
  36956. */
  36957. this.vignetteStretch = 0;
  36958. /**
  36959. * Vignette centre X Offset.
  36960. */
  36961. this.vignetteCentreX = 0;
  36962. /**
  36963. * Vignette centre Y Offset.
  36964. */
  36965. this.vignetteCentreY = 0;
  36966. /**
  36967. * Vignette weight or intensity of the vignette effect.
  36968. */
  36969. this.vignetteWeight = 1.5;
  36970. /**
  36971. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36972. * if vignetteEnabled is set to true.
  36973. */
  36974. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36975. /**
  36976. * Camera field of view used by the Vignette effect.
  36977. */
  36978. this.vignetteCameraFov = 0.5;
  36979. this._grainEnabled = false;
  36980. this._grainIntensity = 30;
  36981. this._grainAnimated = false;
  36982. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36983. this._vignetteEnabled = false;
  36984. this._applyByPostProcess = false;
  36985. this._isEnabled = true;
  36986. /**
  36987. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36988. * @type {BABYLON.Observable}
  36989. */
  36990. this.onUpdateParameters = new BABYLON.Observable();
  36991. }
  36992. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36993. /**
  36994. * Gets wether the color curves effect is enabled.
  36995. */
  36996. get: function () {
  36997. return this._colorCurvesEnabled;
  36998. },
  36999. /**
  37000. * Sets wether the color curves effect is enabled.
  37001. */
  37002. set: function (value) {
  37003. if (this._colorCurvesEnabled === value) {
  37004. return;
  37005. }
  37006. this._colorCurvesEnabled = value;
  37007. this._updateParameters();
  37008. },
  37009. enumerable: true,
  37010. configurable: true
  37011. });
  37012. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37013. /**
  37014. * Gets wether the color grading effect is enabled.
  37015. */
  37016. get: function () {
  37017. return this._colorGradingEnabled;
  37018. },
  37019. /**
  37020. * Sets wether the color grading effect is enabled.
  37021. */
  37022. set: function (value) {
  37023. if (this._colorGradingEnabled === value) {
  37024. return;
  37025. }
  37026. this._colorGradingEnabled = value;
  37027. this._updateParameters();
  37028. },
  37029. enumerable: true,
  37030. configurable: true
  37031. });
  37032. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37033. /**
  37034. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37035. */
  37036. get: function () {
  37037. return this._colorGradingWithGreenDepth;
  37038. },
  37039. /**
  37040. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37041. */
  37042. set: function (value) {
  37043. if (this._colorGradingWithGreenDepth === value) {
  37044. return;
  37045. }
  37046. this._colorGradingWithGreenDepth = value;
  37047. this._updateParameters();
  37048. },
  37049. enumerable: true,
  37050. configurable: true
  37051. });
  37052. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37053. /**
  37054. * Gets wether the color grading texture contains BGR values.
  37055. */
  37056. get: function () {
  37057. return this._colorGradingBGR;
  37058. },
  37059. /**
  37060. * Sets wether the color grading texture contains BGR values.
  37061. */
  37062. set: function (value) {
  37063. if (this._colorGradingBGR === value) {
  37064. return;
  37065. }
  37066. this._colorGradingBGR = value;
  37067. this._updateParameters();
  37068. },
  37069. enumerable: true,
  37070. configurable: true
  37071. });
  37072. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37073. /**
  37074. * Gets the Exposure used in the effect.
  37075. */
  37076. get: function () {
  37077. return this._exposure;
  37078. },
  37079. /**
  37080. * Sets the Exposure used in the effect.
  37081. */
  37082. set: function (value) {
  37083. if (this._exposure === value) {
  37084. return;
  37085. }
  37086. this._exposure = value;
  37087. this._updateParameters();
  37088. },
  37089. enumerable: true,
  37090. configurable: true
  37091. });
  37092. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37093. /**
  37094. * Gets wether the tone mapping effect is enabled.
  37095. */
  37096. get: function () {
  37097. return this._toneMappingEnabled;
  37098. },
  37099. /**
  37100. * Sets wether the tone mapping effect is enabled.
  37101. */
  37102. set: function (value) {
  37103. if (this._toneMappingEnabled === value) {
  37104. return;
  37105. }
  37106. this._toneMappingEnabled = value;
  37107. this._updateParameters();
  37108. },
  37109. enumerable: true,
  37110. configurable: true
  37111. });
  37112. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37113. /**
  37114. * Gets the contrast used in the effect.
  37115. */
  37116. get: function () {
  37117. return this._contrast;
  37118. },
  37119. /**
  37120. * Sets the contrast used in the effect.
  37121. */
  37122. set: function (value) {
  37123. if (this._contrast === value) {
  37124. return;
  37125. }
  37126. this._contrast = value;
  37127. this._updateParameters();
  37128. },
  37129. enumerable: true,
  37130. configurable: true
  37131. });
  37132. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37133. /**
  37134. * If the grain effect should be enabled.
  37135. */
  37136. get: function () {
  37137. return this._grainEnabled;
  37138. },
  37139. set: function (value) {
  37140. if (this._grainEnabled === value) {
  37141. return;
  37142. }
  37143. this._grainEnabled = value;
  37144. this._updateParameters();
  37145. },
  37146. enumerable: true,
  37147. configurable: true
  37148. });
  37149. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37150. /**
  37151. * Amount of grain to be applied by the grain effect.
  37152. */
  37153. get: function () {
  37154. return this._grainIntensity;
  37155. },
  37156. set: function (value) {
  37157. if (this._grainIntensity === value) {
  37158. return;
  37159. }
  37160. this._grainIntensity = value;
  37161. },
  37162. enumerable: true,
  37163. configurable: true
  37164. });
  37165. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37166. /**
  37167. * If the grain effect should be animated.
  37168. */
  37169. get: function () {
  37170. return this._grainAnimated;
  37171. },
  37172. set: function (value) {
  37173. if (this._grainAnimated === value) {
  37174. return;
  37175. }
  37176. this._grainAnimated = value;
  37177. this._updateParameters();
  37178. },
  37179. enumerable: true,
  37180. configurable: true
  37181. });
  37182. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37183. /**
  37184. * Gets the vignette blend mode allowing different kind of effect.
  37185. */
  37186. get: function () {
  37187. return this._vignetteBlendMode;
  37188. },
  37189. /**
  37190. * Sets the vignette blend mode allowing different kind of effect.
  37191. */
  37192. set: function (value) {
  37193. if (this._vignetteBlendMode === value) {
  37194. return;
  37195. }
  37196. this._vignetteBlendMode = value;
  37197. this._updateParameters();
  37198. },
  37199. enumerable: true,
  37200. configurable: true
  37201. });
  37202. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37203. /**
  37204. * Gets wether the vignette effect is enabled.
  37205. */
  37206. get: function () {
  37207. return this._vignetteEnabled;
  37208. },
  37209. /**
  37210. * Sets wether the vignette effect is enabled.
  37211. */
  37212. set: function (value) {
  37213. if (this._vignetteEnabled === value) {
  37214. return;
  37215. }
  37216. this._vignetteEnabled = value;
  37217. this._updateParameters();
  37218. },
  37219. enumerable: true,
  37220. configurable: true
  37221. });
  37222. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37223. /**
  37224. * Gets wether the image processing is applied through a post process or not.
  37225. */
  37226. get: function () {
  37227. return this._applyByPostProcess;
  37228. },
  37229. /**
  37230. * Sets wether the image processing is applied through a post process or not.
  37231. */
  37232. set: function (value) {
  37233. if (this._applyByPostProcess === value) {
  37234. return;
  37235. }
  37236. this._applyByPostProcess = value;
  37237. this._updateParameters();
  37238. },
  37239. enumerable: true,
  37240. configurable: true
  37241. });
  37242. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37243. /**
  37244. * Gets wether the image processing is enabled or not.
  37245. */
  37246. get: function () {
  37247. return this._isEnabled;
  37248. },
  37249. /**
  37250. * Sets wether the image processing is enabled or not.
  37251. */
  37252. set: function (value) {
  37253. if (this._isEnabled === value) {
  37254. return;
  37255. }
  37256. this._isEnabled = value;
  37257. this._updateParameters();
  37258. },
  37259. enumerable: true,
  37260. configurable: true
  37261. });
  37262. /**
  37263. * Method called each time the image processing information changes requires to recompile the effect.
  37264. */
  37265. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37266. this.onUpdateParameters.notifyObservers(this);
  37267. };
  37268. ImageProcessingConfiguration.prototype.getClassName = function () {
  37269. return "ImageProcessingConfiguration";
  37270. };
  37271. /**
  37272. * Prepare the list of uniforms associated with the Image Processing effects.
  37273. * @param uniformsList The list of uniforms used in the effect
  37274. * @param defines the list of defines currently in use
  37275. */
  37276. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37277. if (defines.EXPOSURE) {
  37278. uniforms.push("exposureLinear");
  37279. }
  37280. if (defines.CONTRAST) {
  37281. uniforms.push("contrast");
  37282. }
  37283. if (defines.COLORGRADING) {
  37284. uniforms.push("colorTransformSettings");
  37285. }
  37286. if (defines.VIGNETTE) {
  37287. uniforms.push("vInverseScreenSize");
  37288. uniforms.push("vignetteSettings1");
  37289. uniforms.push("vignetteSettings2");
  37290. }
  37291. if (defines.COLORCURVES) {
  37292. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37293. }
  37294. if (defines.GRAIN) {
  37295. uniforms.push("grainVarianceAmount");
  37296. uniforms.push("grainAnimatedSeed");
  37297. }
  37298. };
  37299. /**
  37300. * Prepare the list of samplers associated with the Image Processing effects.
  37301. * @param uniformsList The list of uniforms used in the effect
  37302. * @param defines the list of defines currently in use
  37303. */
  37304. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37305. if (defines.COLORGRADING) {
  37306. samplersList.push("txColorTransform");
  37307. }
  37308. };
  37309. /**
  37310. * Prepare the list of defines associated to the shader.
  37311. * @param defines the list of defines to complete
  37312. */
  37313. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37314. if (forPostProcess === void 0) { forPostProcess = false; }
  37315. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37316. defines.VIGNETTE = false;
  37317. defines.TONEMAPPING = false;
  37318. defines.CONTRAST = false;
  37319. defines.EXPOSURE = false;
  37320. defines.COLORCURVES = false;
  37321. defines.COLORGRADING = false;
  37322. defines.COLORGRADING3D = false;
  37323. defines.IMAGEPROCESSING = false;
  37324. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37325. return;
  37326. }
  37327. defines.VIGNETTE = this.vignetteEnabled;
  37328. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37329. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37330. defines.TONEMAPPING = this.toneMappingEnabled;
  37331. defines.CONTRAST = (this.contrast !== 1.0);
  37332. defines.EXPOSURE = (this.exposure !== 1.0);
  37333. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37334. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37335. if (defines.COLORGRADING) {
  37336. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37337. }
  37338. else {
  37339. defines.COLORGRADING3D = false;
  37340. }
  37341. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37342. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37343. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37344. defines.GRAIN = this.grainEnabled;
  37345. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37346. };
  37347. /**
  37348. * Returns true if all the image processing information are ready.
  37349. */
  37350. ImageProcessingConfiguration.prototype.isReady = function () {
  37351. // Color Grading texure can not be none blocking.
  37352. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37353. };
  37354. /**
  37355. * Binds the image processing to the shader.
  37356. * @param effect The effect to bind to
  37357. */
  37358. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37359. if (aspectRatio === void 0) { aspectRatio = 1; }
  37360. // Color Curves
  37361. if (this._colorCurvesEnabled && this.colorCurves) {
  37362. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37363. }
  37364. // Vignette
  37365. if (this._vignetteEnabled) {
  37366. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37367. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37368. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37369. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37370. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37371. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37372. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37373. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37374. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37375. var vignettePower = -2.0 * this.vignetteWeight;
  37376. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37377. }
  37378. // Exposure
  37379. effect.setFloat("exposureLinear", this.exposure);
  37380. // Contrast
  37381. effect.setFloat("contrast", this.contrast);
  37382. // Color transform settings
  37383. if (this.colorGradingTexture) {
  37384. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37385. var textureSize = this.colorGradingTexture.getSize().height;
  37386. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37387. 0.5 / textureSize, // textureOffset
  37388. textureSize, // textureSize
  37389. this.colorGradingTexture.level // weight
  37390. );
  37391. }
  37392. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37393. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37394. };
  37395. /**
  37396. * Clones the current image processing instance.
  37397. * @return The cloned image processing
  37398. */
  37399. ImageProcessingConfiguration.prototype.clone = function () {
  37400. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37401. };
  37402. /**
  37403. * Serializes the current image processing instance to a json representation.
  37404. * @return a JSON representation
  37405. */
  37406. ImageProcessingConfiguration.prototype.serialize = function () {
  37407. return BABYLON.SerializationHelper.Serialize(this);
  37408. };
  37409. /**
  37410. * Parses the image processing from a json representation.
  37411. * @param source the JSON source to parse
  37412. * @return The parsed image processing
  37413. */
  37414. ImageProcessingConfiguration.Parse = function (source) {
  37415. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37416. };
  37417. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37418. /**
  37419. * Used to apply the vignette as a mix with the pixel color.
  37420. */
  37421. get: function () {
  37422. return this._VIGNETTEMODE_MULTIPLY;
  37423. },
  37424. enumerable: true,
  37425. configurable: true
  37426. });
  37427. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37428. /**
  37429. * Used to apply the vignette as a replacement of the pixel color.
  37430. */
  37431. get: function () {
  37432. return this._VIGNETTEMODE_OPAQUE;
  37433. },
  37434. enumerable: true,
  37435. configurable: true
  37436. });
  37437. // Static constants associated to the image processing.
  37438. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37439. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37440. __decorate([
  37441. BABYLON.serializeAsColorCurves()
  37442. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37443. __decorate([
  37444. BABYLON.serialize()
  37445. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37446. __decorate([
  37447. BABYLON.serializeAsTexture()
  37448. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37449. __decorate([
  37450. BABYLON.serialize()
  37451. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37452. __decorate([
  37453. BABYLON.serialize()
  37454. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37455. __decorate([
  37456. BABYLON.serialize()
  37457. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37458. __decorate([
  37459. BABYLON.serialize()
  37460. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37461. __decorate([
  37462. BABYLON.serialize()
  37463. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37464. __decorate([
  37465. BABYLON.serialize()
  37466. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37467. __decorate([
  37468. BABYLON.serialize()
  37469. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37470. __decorate([
  37471. BABYLON.serialize()
  37472. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37473. __decorate([
  37474. BABYLON.serialize()
  37475. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37476. __decorate([
  37477. BABYLON.serialize()
  37478. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37479. __decorate([
  37480. BABYLON.serializeAsColor4()
  37481. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37482. __decorate([
  37483. BABYLON.serialize()
  37484. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37485. __decorate([
  37486. BABYLON.serialize()
  37487. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37488. __decorate([
  37489. BABYLON.serialize()
  37490. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37491. __decorate([
  37492. BABYLON.serialize()
  37493. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37494. __decorate([
  37495. BABYLON.serialize()
  37496. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37497. __decorate([
  37498. BABYLON.serialize()
  37499. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37500. __decorate([
  37501. BABYLON.serialize()
  37502. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37503. __decorate([
  37504. BABYLON.serialize()
  37505. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37506. return ImageProcessingConfiguration;
  37507. }());
  37508. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37509. })(BABYLON || (BABYLON = {}));
  37510. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37511. var BABYLON;
  37512. (function (BABYLON) {
  37513. /**
  37514. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37515. * It can help converting any input color in a desired output one. This can then be used to create effects
  37516. * from sepia, black and white to sixties or futuristic rendering...
  37517. *
  37518. * The only supported format is currently 3dl.
  37519. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37520. */
  37521. var ColorGradingTexture = /** @class */ (function (_super) {
  37522. __extends(ColorGradingTexture, _super);
  37523. /**
  37524. * Instantiates a ColorGradingTexture from the following parameters.
  37525. *
  37526. * @param url The location of the color gradind data (currently only supporting 3dl)
  37527. * @param scene The scene the texture will be used in
  37528. */
  37529. function ColorGradingTexture(url, scene) {
  37530. var _this = _super.call(this, scene) || this;
  37531. if (!url) {
  37532. return _this;
  37533. }
  37534. _this._engine = scene.getEngine();
  37535. _this._textureMatrix = BABYLON.Matrix.Identity();
  37536. _this.name = url;
  37537. _this.url = url;
  37538. _this.hasAlpha = false;
  37539. _this.isCube = false;
  37540. _this.is3D = _this._engine.webGLVersion > 1;
  37541. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37542. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37543. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37544. _this.anisotropicFilteringLevel = 1;
  37545. _this._texture = _this._getFromCache(url, true);
  37546. if (!_this._texture) {
  37547. if (!scene.useDelayedTextureLoading) {
  37548. _this.loadTexture();
  37549. }
  37550. else {
  37551. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37552. }
  37553. }
  37554. return _this;
  37555. }
  37556. /**
  37557. * Returns the texture matrix used in most of the material.
  37558. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37559. */
  37560. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37561. return this._textureMatrix;
  37562. };
  37563. /**
  37564. * Occurs when the file being loaded is a .3dl LUT file.
  37565. */
  37566. ColorGradingTexture.prototype.load3dlTexture = function () {
  37567. var engine = this._engine;
  37568. var texture;
  37569. if (engine.webGLVersion === 1) {
  37570. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37571. }
  37572. else {
  37573. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37574. }
  37575. this._texture = texture;
  37576. var callback = function (text) {
  37577. if (typeof text !== "string") {
  37578. return;
  37579. }
  37580. var data = null;
  37581. var tempData = null;
  37582. var line;
  37583. var lines = text.split('\n');
  37584. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37585. var maxColor = 0;
  37586. for (var i = 0; i < lines.length; i++) {
  37587. line = lines[i];
  37588. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37589. continue;
  37590. if (line.indexOf('#') === 0)
  37591. continue;
  37592. var words = line.split(" ");
  37593. if (size === 0) {
  37594. // Number of space + one
  37595. size = words.length;
  37596. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37597. tempData = new Float32Array(size * size * size * 4);
  37598. continue;
  37599. }
  37600. if (size != 0) {
  37601. var r = Math.max(parseInt(words[0]), 0);
  37602. var g = Math.max(parseInt(words[1]), 0);
  37603. var b = Math.max(parseInt(words[2]), 0);
  37604. maxColor = Math.max(r, maxColor);
  37605. maxColor = Math.max(g, maxColor);
  37606. maxColor = Math.max(b, maxColor);
  37607. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37608. if (tempData) {
  37609. tempData[pixelStorageIndex + 0] = r;
  37610. tempData[pixelStorageIndex + 1] = g;
  37611. tempData[pixelStorageIndex + 2] = b;
  37612. }
  37613. pixelIndexSlice++;
  37614. if (pixelIndexSlice % size == 0) {
  37615. pixelIndexH++;
  37616. pixelIndexSlice = 0;
  37617. if (pixelIndexH % size == 0) {
  37618. pixelIndexW++;
  37619. pixelIndexH = 0;
  37620. }
  37621. }
  37622. }
  37623. }
  37624. if (tempData && data) {
  37625. for (var i = 0; i < tempData.length; i++) {
  37626. if (i > 0 && (i + 1) % 4 === 0) {
  37627. data[i] = 255;
  37628. }
  37629. else {
  37630. var value = tempData[i];
  37631. data[i] = (value / maxColor * 255);
  37632. }
  37633. }
  37634. }
  37635. if (texture.is3D) {
  37636. texture.updateSize(size, size, size);
  37637. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37638. }
  37639. else {
  37640. texture.updateSize(size * size, size);
  37641. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37642. }
  37643. };
  37644. var scene = this.getScene();
  37645. if (scene) {
  37646. scene._loadFile(this.url, callback);
  37647. }
  37648. else {
  37649. this._engine._loadFile(this.url, callback);
  37650. }
  37651. return this._texture;
  37652. };
  37653. /**
  37654. * Starts the loading process of the texture.
  37655. */
  37656. ColorGradingTexture.prototype.loadTexture = function () {
  37657. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37658. this.load3dlTexture();
  37659. }
  37660. };
  37661. /**
  37662. * Clones the color gradind texture.
  37663. */
  37664. ColorGradingTexture.prototype.clone = function () {
  37665. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37666. // Base texture
  37667. newTexture.level = this.level;
  37668. return newTexture;
  37669. };
  37670. /**
  37671. * Called during delayed load for textures.
  37672. */
  37673. ColorGradingTexture.prototype.delayLoad = function () {
  37674. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37675. return;
  37676. }
  37677. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37678. this._texture = this._getFromCache(this.url, true);
  37679. if (!this._texture) {
  37680. this.loadTexture();
  37681. }
  37682. };
  37683. /**
  37684. * Parses a color grading texture serialized by Babylon.
  37685. * @param parsedTexture The texture information being parsedTexture
  37686. * @param scene The scene to load the texture in
  37687. * @param rootUrl The root url of the data assets to load
  37688. * @return A color gradind texture
  37689. */
  37690. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37691. var texture = null;
  37692. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37693. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37694. texture.name = parsedTexture.name;
  37695. texture.level = parsedTexture.level;
  37696. }
  37697. return texture;
  37698. };
  37699. /**
  37700. * Serializes the LUT texture to json format.
  37701. */
  37702. ColorGradingTexture.prototype.serialize = function () {
  37703. if (!this.name) {
  37704. return null;
  37705. }
  37706. var serializationObject = {};
  37707. serializationObject.name = this.name;
  37708. serializationObject.level = this.level;
  37709. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37710. return serializationObject;
  37711. };
  37712. /**
  37713. * Empty line regex stored for GC.
  37714. */
  37715. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37716. return ColorGradingTexture;
  37717. }(BABYLON.BaseTexture));
  37718. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37719. })(BABYLON || (BABYLON = {}));
  37720. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37721. var BABYLON;
  37722. (function (BABYLON) {
  37723. /**
  37724. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37725. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37726. * 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;
  37727. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37728. */
  37729. var ColorCurves = /** @class */ (function () {
  37730. function ColorCurves() {
  37731. this._dirty = true;
  37732. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37733. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37734. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37735. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37736. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37737. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37738. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37739. this._globalHue = 30;
  37740. this._globalDensity = 0;
  37741. this._globalSaturation = 0;
  37742. this._globalExposure = 0;
  37743. this._highlightsHue = 30;
  37744. this._highlightsDensity = 0;
  37745. this._highlightsSaturation = 0;
  37746. this._highlightsExposure = 0;
  37747. this._midtonesHue = 30;
  37748. this._midtonesDensity = 0;
  37749. this._midtonesSaturation = 0;
  37750. this._midtonesExposure = 0;
  37751. this._shadowsHue = 30;
  37752. this._shadowsDensity = 0;
  37753. this._shadowsSaturation = 0;
  37754. this._shadowsExposure = 0;
  37755. }
  37756. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37757. /**
  37758. * Gets the global Hue value.
  37759. * 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).
  37760. */
  37761. get: function () {
  37762. return this._globalHue;
  37763. },
  37764. /**
  37765. * Sets the global Hue value.
  37766. * 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).
  37767. */
  37768. set: function (value) {
  37769. this._globalHue = value;
  37770. this._dirty = true;
  37771. },
  37772. enumerable: true,
  37773. configurable: true
  37774. });
  37775. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37776. /**
  37777. * Gets the global Density value.
  37778. * 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.
  37779. * Values less than zero provide a filter of opposite hue.
  37780. */
  37781. get: function () {
  37782. return this._globalDensity;
  37783. },
  37784. /**
  37785. * Sets the global Density value.
  37786. * 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.
  37787. * Values less than zero provide a filter of opposite hue.
  37788. */
  37789. set: function (value) {
  37790. this._globalDensity = value;
  37791. this._dirty = true;
  37792. },
  37793. enumerable: true,
  37794. configurable: true
  37795. });
  37796. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37797. /**
  37798. * Gets the global Saturation value.
  37799. * 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.
  37800. */
  37801. get: function () {
  37802. return this._globalSaturation;
  37803. },
  37804. /**
  37805. * Sets the global Saturation value.
  37806. * 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.
  37807. */
  37808. set: function (value) {
  37809. this._globalSaturation = value;
  37810. this._dirty = true;
  37811. },
  37812. enumerable: true,
  37813. configurable: true
  37814. });
  37815. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37816. /**
  37817. * Gets the highlights Hue value.
  37818. * 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).
  37819. */
  37820. get: function () {
  37821. return this._highlightsHue;
  37822. },
  37823. /**
  37824. * Sets the highlights Hue value.
  37825. * 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).
  37826. */
  37827. set: function (value) {
  37828. this._highlightsHue = value;
  37829. this._dirty = true;
  37830. },
  37831. enumerable: true,
  37832. configurable: true
  37833. });
  37834. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37835. /**
  37836. * Gets the highlights Density value.
  37837. * 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.
  37838. * Values less than zero provide a filter of opposite hue.
  37839. */
  37840. get: function () {
  37841. return this._highlightsDensity;
  37842. },
  37843. /**
  37844. * Sets the highlights Density value.
  37845. * 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.
  37846. * Values less than zero provide a filter of opposite hue.
  37847. */
  37848. set: function (value) {
  37849. this._highlightsDensity = value;
  37850. this._dirty = true;
  37851. },
  37852. enumerable: true,
  37853. configurable: true
  37854. });
  37855. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37856. /**
  37857. * Gets the highlights Saturation value.
  37858. * 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.
  37859. */
  37860. get: function () {
  37861. return this._highlightsSaturation;
  37862. },
  37863. /**
  37864. * Sets the highlights Saturation value.
  37865. * 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.
  37866. */
  37867. set: function (value) {
  37868. this._highlightsSaturation = value;
  37869. this._dirty = true;
  37870. },
  37871. enumerable: true,
  37872. configurable: true
  37873. });
  37874. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37875. /**
  37876. * Gets the highlights Exposure value.
  37877. * 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.
  37878. */
  37879. get: function () {
  37880. return this._highlightsExposure;
  37881. },
  37882. /**
  37883. * Sets the highlights Exposure value.
  37884. * 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.
  37885. */
  37886. set: function (value) {
  37887. this._highlightsExposure = value;
  37888. this._dirty = true;
  37889. },
  37890. enumerable: true,
  37891. configurable: true
  37892. });
  37893. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37894. /**
  37895. * Gets the midtones Hue value.
  37896. * 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).
  37897. */
  37898. get: function () {
  37899. return this._midtonesHue;
  37900. },
  37901. /**
  37902. * Sets the midtones Hue value.
  37903. * 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).
  37904. */
  37905. set: function (value) {
  37906. this._midtonesHue = value;
  37907. this._dirty = true;
  37908. },
  37909. enumerable: true,
  37910. configurable: true
  37911. });
  37912. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37913. /**
  37914. * Gets the midtones Density value.
  37915. * 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.
  37916. * Values less than zero provide a filter of opposite hue.
  37917. */
  37918. get: function () {
  37919. return this._midtonesDensity;
  37920. },
  37921. /**
  37922. * Sets the midtones Density value.
  37923. * 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.
  37924. * Values less than zero provide a filter of opposite hue.
  37925. */
  37926. set: function (value) {
  37927. this._midtonesDensity = value;
  37928. this._dirty = true;
  37929. },
  37930. enumerable: true,
  37931. configurable: true
  37932. });
  37933. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37934. /**
  37935. * Gets the midtones Saturation value.
  37936. * 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.
  37937. */
  37938. get: function () {
  37939. return this._midtonesSaturation;
  37940. },
  37941. /**
  37942. * Sets the midtones Saturation value.
  37943. * 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.
  37944. */
  37945. set: function (value) {
  37946. this._midtonesSaturation = value;
  37947. this._dirty = true;
  37948. },
  37949. enumerable: true,
  37950. configurable: true
  37951. });
  37952. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37953. /**
  37954. * Gets the midtones Exposure value.
  37955. * 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.
  37956. */
  37957. get: function () {
  37958. return this._midtonesExposure;
  37959. },
  37960. /**
  37961. * Sets the midtones Exposure value.
  37962. * 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.
  37963. */
  37964. set: function (value) {
  37965. this._midtonesExposure = value;
  37966. this._dirty = true;
  37967. },
  37968. enumerable: true,
  37969. configurable: true
  37970. });
  37971. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37972. /**
  37973. * Gets the shadows Hue value.
  37974. * 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).
  37975. */
  37976. get: function () {
  37977. return this._shadowsHue;
  37978. },
  37979. /**
  37980. * Sets the shadows Hue value.
  37981. * 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).
  37982. */
  37983. set: function (value) {
  37984. this._shadowsHue = value;
  37985. this._dirty = true;
  37986. },
  37987. enumerable: true,
  37988. configurable: true
  37989. });
  37990. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37991. /**
  37992. * Gets the shadows Density value.
  37993. * 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.
  37994. * Values less than zero provide a filter of opposite hue.
  37995. */
  37996. get: function () {
  37997. return this._shadowsDensity;
  37998. },
  37999. /**
  38000. * Sets the shadows Density value.
  38001. * 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.
  38002. * Values less than zero provide a filter of opposite hue.
  38003. */
  38004. set: function (value) {
  38005. this._shadowsDensity = value;
  38006. this._dirty = true;
  38007. },
  38008. enumerable: true,
  38009. configurable: true
  38010. });
  38011. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38012. /**
  38013. * Gets the shadows Saturation value.
  38014. * 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.
  38015. */
  38016. get: function () {
  38017. return this._shadowsSaturation;
  38018. },
  38019. /**
  38020. * Sets the shadows Saturation value.
  38021. * 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.
  38022. */
  38023. set: function (value) {
  38024. this._shadowsSaturation = value;
  38025. this._dirty = true;
  38026. },
  38027. enumerable: true,
  38028. configurable: true
  38029. });
  38030. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38031. /**
  38032. * Gets the shadows Exposure value.
  38033. * 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.
  38034. */
  38035. get: function () {
  38036. return this._shadowsExposure;
  38037. },
  38038. /**
  38039. * Sets the shadows Exposure value.
  38040. * 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.
  38041. */
  38042. set: function (value) {
  38043. this._shadowsExposure = value;
  38044. this._dirty = true;
  38045. },
  38046. enumerable: true,
  38047. configurable: true
  38048. });
  38049. ColorCurves.prototype.getClassName = function () {
  38050. return "ColorCurves";
  38051. };
  38052. /**
  38053. * Binds the color curves to the shader.
  38054. * @param colorCurves The color curve to bind
  38055. * @param effect The effect to bind to
  38056. */
  38057. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38058. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38059. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38060. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38061. if (colorCurves._dirty) {
  38062. colorCurves._dirty = false;
  38063. // Fill in global info.
  38064. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38065. // Compute highlights info.
  38066. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38067. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38068. // Compute midtones info.
  38069. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38070. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38071. // Compute shadows info.
  38072. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38073. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38074. // Compute deltas (neutral is midtones).
  38075. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38076. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38077. }
  38078. if (effect) {
  38079. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38080. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38081. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38082. }
  38083. };
  38084. /**
  38085. * Prepare the list of uniforms associated with the ColorCurves effects.
  38086. * @param uniformsList The list of uniforms used in the effect
  38087. */
  38088. ColorCurves.PrepareUniforms = function (uniformsList) {
  38089. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38090. };
  38091. /**
  38092. * Returns color grading data based on a hue, density, saturation and exposure value.
  38093. * @param filterHue The hue of the color filter.
  38094. * @param filterDensity The density of the color filter.
  38095. * @param saturation The saturation.
  38096. * @param exposure The exposure.
  38097. * @param result The result data container.
  38098. */
  38099. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38100. if (hue == null) {
  38101. return;
  38102. }
  38103. hue = ColorCurves.clamp(hue, 0, 360);
  38104. density = ColorCurves.clamp(density, -100, 100);
  38105. saturation = ColorCurves.clamp(saturation, -100, 100);
  38106. exposure = ColorCurves.clamp(exposure, -100, 100);
  38107. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38108. // so that the maximum filter density is only 50% control. This provides fine control
  38109. // for small values and reasonable range.
  38110. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38111. density *= 0.5;
  38112. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38113. if (density < 0) {
  38114. density *= -1;
  38115. hue = (hue + 180) % 360;
  38116. }
  38117. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38118. result.scaleToRef(2, result);
  38119. result.a = 1 + 0.01 * saturation;
  38120. };
  38121. /**
  38122. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38123. * @param value The input slider value in range [-100,100].
  38124. * @returns Adjusted value.
  38125. */
  38126. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38127. value /= 100;
  38128. var x = Math.abs(value);
  38129. x = Math.pow(x, 2);
  38130. if (value < 0) {
  38131. x *= -1;
  38132. }
  38133. x *= 100;
  38134. return x;
  38135. };
  38136. /**
  38137. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38138. * @param hue The hue (H) input.
  38139. * @param saturation The saturation (S) input.
  38140. * @param brightness The brightness (B) input.
  38141. * @result An RGBA color represented as Vector4.
  38142. */
  38143. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38144. var h = ColorCurves.clamp(hue, 0, 360);
  38145. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38146. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38147. if (s === 0) {
  38148. result.r = v;
  38149. result.g = v;
  38150. result.b = v;
  38151. }
  38152. else {
  38153. // sector 0 to 5
  38154. h /= 60;
  38155. var i = Math.floor(h);
  38156. // fractional part of h
  38157. var f = h - i;
  38158. var p = v * (1 - s);
  38159. var q = v * (1 - s * f);
  38160. var t = v * (1 - s * (1 - f));
  38161. switch (i) {
  38162. case 0:
  38163. result.r = v;
  38164. result.g = t;
  38165. result.b = p;
  38166. break;
  38167. case 1:
  38168. result.r = q;
  38169. result.g = v;
  38170. result.b = p;
  38171. break;
  38172. case 2:
  38173. result.r = p;
  38174. result.g = v;
  38175. result.b = t;
  38176. break;
  38177. case 3:
  38178. result.r = p;
  38179. result.g = q;
  38180. result.b = v;
  38181. break;
  38182. case 4:
  38183. result.r = t;
  38184. result.g = p;
  38185. result.b = v;
  38186. break;
  38187. default:// case 5:
  38188. result.r = v;
  38189. result.g = p;
  38190. result.b = q;
  38191. break;
  38192. }
  38193. }
  38194. result.a = 1;
  38195. };
  38196. /**
  38197. * Returns a value clamped between min and max
  38198. * @param value The value to clamp
  38199. * @param min The minimum of value
  38200. * @param max The maximum of value
  38201. * @returns The clamped value.
  38202. */
  38203. ColorCurves.clamp = function (value, min, max) {
  38204. return Math.min(Math.max(value, min), max);
  38205. };
  38206. /**
  38207. * Clones the current color curve instance.
  38208. * @return The cloned curves
  38209. */
  38210. ColorCurves.prototype.clone = function () {
  38211. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38212. };
  38213. /**
  38214. * Serializes the current color curve instance to a json representation.
  38215. * @return a JSON representation
  38216. */
  38217. ColorCurves.prototype.serialize = function () {
  38218. return BABYLON.SerializationHelper.Serialize(this);
  38219. };
  38220. /**
  38221. * Parses the color curve from a json representation.
  38222. * @param source the JSON source to parse
  38223. * @return The parsed curves
  38224. */
  38225. ColorCurves.Parse = function (source) {
  38226. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38227. };
  38228. __decorate([
  38229. BABYLON.serialize()
  38230. ], ColorCurves.prototype, "_globalHue", void 0);
  38231. __decorate([
  38232. BABYLON.serialize()
  38233. ], ColorCurves.prototype, "_globalDensity", void 0);
  38234. __decorate([
  38235. BABYLON.serialize()
  38236. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38237. __decorate([
  38238. BABYLON.serialize()
  38239. ], ColorCurves.prototype, "_globalExposure", void 0);
  38240. __decorate([
  38241. BABYLON.serialize()
  38242. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38243. __decorate([
  38244. BABYLON.serialize()
  38245. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38246. __decorate([
  38247. BABYLON.serialize()
  38248. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38249. __decorate([
  38250. BABYLON.serialize()
  38251. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38252. __decorate([
  38253. BABYLON.serialize()
  38254. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38255. __decorate([
  38256. BABYLON.serialize()
  38257. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38258. __decorate([
  38259. BABYLON.serialize()
  38260. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38261. __decorate([
  38262. BABYLON.serialize()
  38263. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38264. return ColorCurves;
  38265. }());
  38266. BABYLON.ColorCurves = ColorCurves;
  38267. })(BABYLON || (BABYLON = {}));
  38268. //# sourceMappingURL=babylon.colorCurves.js.map
  38269. //# sourceMappingURL=babylon.behavior.js.map
  38270. var BABYLON;
  38271. (function (BABYLON) {
  38272. /**
  38273. * "Static Class" containing the most commonly used helper while dealing with material for
  38274. * rendering purpose.
  38275. *
  38276. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38277. *
  38278. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38279. */
  38280. var MaterialHelper = /** @class */ (function () {
  38281. function MaterialHelper() {
  38282. }
  38283. /**
  38284. * Bind the current view position to an effect.
  38285. * @param effect The effect to be bound
  38286. * @param scene The scene the eyes position is used from
  38287. */
  38288. MaterialHelper.BindEyePosition = function (effect, scene) {
  38289. if (scene._forcedViewPosition) {
  38290. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38291. return;
  38292. }
  38293. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38294. };
  38295. /**
  38296. * Helps preparing the defines values about the UVs in used in the effect.
  38297. * UVs are shared as much as we can accross chanels in the shaders.
  38298. * @param texture The texture we are preparing the UVs for
  38299. * @param defines The defines to update
  38300. * @param key The chanel key "diffuse", "specular"... used in the shader
  38301. */
  38302. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38303. defines._needUVs = true;
  38304. defines[key] = true;
  38305. if (texture.getTextureMatrix().isIdentity(true)) {
  38306. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38307. if (texture.coordinatesIndex === 0) {
  38308. defines["MAINUV1"] = true;
  38309. }
  38310. else {
  38311. defines["MAINUV2"] = true;
  38312. }
  38313. }
  38314. else {
  38315. defines[key + "DIRECTUV"] = 0;
  38316. }
  38317. };
  38318. /**
  38319. * Binds a texture matrix value to its corrsponding uniform
  38320. * @param texture The texture to bind the matrix for
  38321. * @param uniformBuffer The uniform buffer receivin the data
  38322. * @param key The chanel key "diffuse", "specular"... used in the shader
  38323. */
  38324. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38325. var matrix = texture.getTextureMatrix();
  38326. if (!matrix.isIdentity(true)) {
  38327. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38328. }
  38329. };
  38330. /**
  38331. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38332. * @param mesh defines the current mesh
  38333. * @param scene defines the current scene
  38334. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38335. * @param pointsCloud defines if point cloud rendering has to be turned on
  38336. * @param fogEnabled defines if fog has to be turned on
  38337. * @param alphaTest defines if alpha testing has to be turned on
  38338. * @param defines defines the current list of defines
  38339. */
  38340. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38341. if (defines._areMiscDirty) {
  38342. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38343. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38344. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38345. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38346. defines["ALPHATEST"] = alphaTest;
  38347. }
  38348. };
  38349. /**
  38350. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38351. * @param scene defines the current scene
  38352. * @param engine defines the current engine
  38353. * @param defines specifies the list of active defines
  38354. * @param useInstances defines if instances have to be turned on
  38355. * @param useClipPlane defines if clip plane have to be turned on
  38356. */
  38357. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38358. if (useClipPlane === void 0) { useClipPlane = null; }
  38359. var changed = false;
  38360. if (useClipPlane == null) {
  38361. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38362. }
  38363. if (defines["CLIPPLANE"] !== useClipPlane) {
  38364. defines["CLIPPLANE"] = useClipPlane;
  38365. changed = true;
  38366. }
  38367. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38368. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38369. changed = true;
  38370. }
  38371. if (defines["INSTANCES"] !== useInstances) {
  38372. defines["INSTANCES"] = useInstances;
  38373. changed = true;
  38374. }
  38375. if (changed) {
  38376. defines.markAsUnprocessed();
  38377. }
  38378. };
  38379. /**
  38380. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38381. * @param mesh The mesh containing the geometry data we will draw
  38382. * @param defines The defines to update
  38383. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38384. * @param useBones Precise whether bones should be used or not (override mesh info)
  38385. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38386. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38387. * @returns false if defines are considered not dirty and have not been checked
  38388. */
  38389. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38390. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38391. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38392. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38393. return false;
  38394. }
  38395. defines._normals = defines._needNormals;
  38396. defines._uvs = defines._needUVs;
  38397. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38398. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38399. defines["TANGENT"] = true;
  38400. }
  38401. if (defines._needUVs) {
  38402. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38403. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38404. }
  38405. else {
  38406. defines["UV1"] = false;
  38407. defines["UV2"] = false;
  38408. }
  38409. if (useVertexColor) {
  38410. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38411. defines["VERTEXCOLOR"] = hasVertexColors;
  38412. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38413. }
  38414. if (useBones) {
  38415. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38416. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38417. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38418. }
  38419. else {
  38420. defines["NUM_BONE_INFLUENCERS"] = 0;
  38421. defines["BonesPerMesh"] = 0;
  38422. }
  38423. }
  38424. if (useMorphTargets) {
  38425. var manager = mesh.morphTargetManager;
  38426. if (manager) {
  38427. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38428. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38429. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38430. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38431. }
  38432. else {
  38433. defines["MORPHTARGETS_TANGENT"] = false;
  38434. defines["MORPHTARGETS_NORMAL"] = false;
  38435. defines["MORPHTARGETS"] = false;
  38436. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38437. }
  38438. }
  38439. return true;
  38440. };
  38441. /**
  38442. * Prepares the defines related to the light information passed in parameter
  38443. * @param scene The scene we are intending to draw
  38444. * @param mesh The mesh the effect is compiling for
  38445. * @param defines The defines to update
  38446. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38447. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38448. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38449. * @returns true if normals will be required for the rest of the effect
  38450. */
  38451. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38452. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38453. if (disableLighting === void 0) { disableLighting = false; }
  38454. if (!defines._areLightsDirty) {
  38455. return defines._needNormals;
  38456. }
  38457. var lightIndex = 0;
  38458. var needNormals = false;
  38459. var needRebuild = false;
  38460. var lightmapMode = false;
  38461. var shadowEnabled = false;
  38462. var specularEnabled = false;
  38463. if (scene.lightsEnabled && !disableLighting) {
  38464. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38465. var light = _a[_i];
  38466. needNormals = true;
  38467. if (defines["LIGHT" + lightIndex] === undefined) {
  38468. needRebuild = true;
  38469. }
  38470. defines["LIGHT" + lightIndex] = true;
  38471. defines["SPOTLIGHT" + lightIndex] = false;
  38472. defines["HEMILIGHT" + lightIndex] = false;
  38473. defines["POINTLIGHT" + lightIndex] = false;
  38474. defines["DIRLIGHT" + lightIndex] = false;
  38475. var type;
  38476. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38477. type = "SPOTLIGHT" + lightIndex;
  38478. var spotLight = light;
  38479. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38480. }
  38481. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38482. type = "HEMILIGHT" + lightIndex;
  38483. }
  38484. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38485. type = "POINTLIGHT" + lightIndex;
  38486. }
  38487. else {
  38488. type = "DIRLIGHT" + lightIndex;
  38489. }
  38490. defines[type] = true;
  38491. // Specular
  38492. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38493. specularEnabled = true;
  38494. }
  38495. // Shadows
  38496. defines["SHADOW" + lightIndex] = false;
  38497. defines["SHADOWPCF" + lightIndex] = false;
  38498. defines["SHADOWESM" + lightIndex] = false;
  38499. defines["SHADOWCUBE" + lightIndex] = false;
  38500. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38501. var shadowGenerator = light.getShadowGenerator();
  38502. if (shadowGenerator) {
  38503. shadowEnabled = true;
  38504. shadowGenerator.prepareDefines(defines, lightIndex);
  38505. }
  38506. }
  38507. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38508. lightmapMode = true;
  38509. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38510. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38511. }
  38512. else {
  38513. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38514. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38515. }
  38516. lightIndex++;
  38517. if (lightIndex === maxSimultaneousLights)
  38518. break;
  38519. }
  38520. }
  38521. defines["SPECULARTERM"] = specularEnabled;
  38522. defines["SHADOWS"] = shadowEnabled;
  38523. // Resetting all other lights if any
  38524. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38525. if (defines["LIGHT" + index] !== undefined) {
  38526. defines["LIGHT" + index] = false;
  38527. defines["HEMILIGHT" + lightIndex] = false;
  38528. defines["POINTLIGHT" + lightIndex] = false;
  38529. defines["DIRLIGHT" + lightIndex] = false;
  38530. defines["SPOTLIGHT" + lightIndex] = false;
  38531. defines["SHADOW" + lightIndex] = false;
  38532. }
  38533. }
  38534. var caps = scene.getEngine().getCaps();
  38535. if (defines["SHADOWFLOAT"] === undefined) {
  38536. needRebuild = true;
  38537. }
  38538. defines["SHADOWFLOAT"] = shadowEnabled &&
  38539. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38540. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38541. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38542. if (needRebuild) {
  38543. defines.rebuild();
  38544. }
  38545. return needNormals;
  38546. };
  38547. /**
  38548. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38549. * that won t be acctive due to defines being turned off.
  38550. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38551. * @param samplersList The samplers list
  38552. * @param defines The defines helping in the list generation
  38553. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38554. */
  38555. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38556. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38557. var uniformsList;
  38558. var uniformBuffersList = null;
  38559. if (uniformsListOrOptions.uniformsNames) {
  38560. var options = uniformsListOrOptions;
  38561. uniformsList = options.uniformsNames;
  38562. uniformBuffersList = options.uniformBuffersNames;
  38563. samplersList = options.samplers;
  38564. defines = options.defines;
  38565. maxSimultaneousLights = options.maxSimultaneousLights;
  38566. }
  38567. else {
  38568. uniformsList = uniformsListOrOptions;
  38569. if (!samplersList) {
  38570. samplersList = [];
  38571. }
  38572. }
  38573. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38574. if (!defines["LIGHT" + lightIndex]) {
  38575. break;
  38576. }
  38577. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38578. if (uniformBuffersList) {
  38579. uniformBuffersList.push("Light" + lightIndex);
  38580. }
  38581. samplersList.push("shadowSampler" + lightIndex);
  38582. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38583. samplersList.push("projectionLightSampler" + lightIndex);
  38584. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38585. }
  38586. }
  38587. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38588. uniformsList.push("morphTargetInfluences");
  38589. }
  38590. };
  38591. /**
  38592. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38593. * @param defines The defines to update while falling back
  38594. * @param fallbacks The authorized effect fallbacks
  38595. * @param maxSimultaneousLights The maximum number of lights allowed
  38596. * @param rank the current rank of the Effect
  38597. * @returns The newly affected rank
  38598. */
  38599. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38600. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38601. if (rank === void 0) { rank = 0; }
  38602. var lightFallbackRank = 0;
  38603. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38604. if (!defines["LIGHT" + lightIndex]) {
  38605. break;
  38606. }
  38607. if (lightIndex > 0) {
  38608. lightFallbackRank = rank + lightIndex;
  38609. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38610. }
  38611. if (!defines["SHADOWS"]) {
  38612. if (defines["SHADOW" + lightIndex]) {
  38613. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38614. }
  38615. if (defines["SHADOWPCF" + lightIndex]) {
  38616. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38617. }
  38618. if (defines["SHADOWESM" + lightIndex]) {
  38619. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38620. }
  38621. }
  38622. }
  38623. return lightFallbackRank++;
  38624. };
  38625. /**
  38626. * Prepares the list of attributes required for morph targets according to the effect defines.
  38627. * @param attribs The current list of supported attribs
  38628. * @param mesh The mesh to prepare the morph targets attributes for
  38629. * @param defines The current Defines of the effect
  38630. */
  38631. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38632. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38633. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38634. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38635. var manager = mesh.morphTargetManager;
  38636. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38637. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38638. for (var index = 0; index < influencers; index++) {
  38639. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38640. if (normal) {
  38641. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38642. }
  38643. if (tangent) {
  38644. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38645. }
  38646. if (attribs.length > maxAttributesCount) {
  38647. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38648. }
  38649. }
  38650. }
  38651. };
  38652. /**
  38653. * Prepares the list of attributes required for bones according to the effect defines.
  38654. * @param attribs The current list of supported attribs
  38655. * @param mesh The mesh to prepare the bones attributes for
  38656. * @param defines The current Defines of the effect
  38657. * @param fallbacks The current efffect fallback strategy
  38658. */
  38659. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38660. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38661. fallbacks.addCPUSkinningFallback(0, mesh);
  38662. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38663. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38664. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38665. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38666. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38667. }
  38668. }
  38669. };
  38670. /**
  38671. * Prepares the list of attributes required for instances according to the effect defines.
  38672. * @param attribs The current list of supported attribs
  38673. * @param defines The current Defines of the effect
  38674. */
  38675. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38676. if (defines["INSTANCES"]) {
  38677. attribs.push("world0");
  38678. attribs.push("world1");
  38679. attribs.push("world2");
  38680. attribs.push("world3");
  38681. }
  38682. };
  38683. /**
  38684. * Binds the light shadow information to the effect for the given mesh.
  38685. * @param light The light containing the generator
  38686. * @param scene The scene the lights belongs to
  38687. * @param mesh The mesh we are binding the information to render
  38688. * @param lightIndex The light index in the effect used to render the mesh
  38689. * @param effect The effect we are binding the data to
  38690. */
  38691. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38692. if (light.shadowEnabled && mesh.receiveShadows) {
  38693. var shadowGenerator = light.getShadowGenerator();
  38694. if (shadowGenerator) {
  38695. shadowGenerator.bindShadowLight(lightIndex, effect);
  38696. }
  38697. }
  38698. };
  38699. /**
  38700. * Binds the light information to the effect.
  38701. * @param light The light containing the generator
  38702. * @param effect The effect we are binding the data to
  38703. * @param lightIndex The light index in the effect used to render
  38704. */
  38705. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38706. light.transferToEffect(effect, lightIndex + "");
  38707. };
  38708. /**
  38709. * Binds the lights information from the scene to the effect for the given mesh.
  38710. * @param scene The scene the lights belongs to
  38711. * @param mesh The mesh we are binding the information to render
  38712. * @param effect The effect we are binding the data to
  38713. * @param defines The generated defines for the effect
  38714. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38715. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38716. */
  38717. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38718. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38719. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38720. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38721. for (var i = 0; i < len; i++) {
  38722. var light = mesh._lightSources[i];
  38723. var iAsString = i.toString();
  38724. var scaledIntensity = light.getScaledIntensity();
  38725. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38726. MaterialHelper.BindLightProperties(light, effect, i);
  38727. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38728. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38729. if (defines["SPECULARTERM"]) {
  38730. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38731. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38732. }
  38733. // Shadows
  38734. if (scene.shadowsEnabled) {
  38735. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38736. }
  38737. light._uniformBuffer.update();
  38738. }
  38739. };
  38740. /**
  38741. * Binds the fog information from the scene to the effect for the given mesh.
  38742. * @param scene The scene the lights belongs to
  38743. * @param mesh The mesh we are binding the information to render
  38744. * @param effect The effect we are binding the data to
  38745. */
  38746. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38747. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38748. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38749. effect.setColor3("vFogColor", scene.fogColor);
  38750. }
  38751. };
  38752. /**
  38753. * Binds the bones information from the mesh to the effect.
  38754. * @param mesh The mesh we are binding the information to render
  38755. * @param effect The effect we are binding the data to
  38756. */
  38757. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38758. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38759. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38760. if (matrices && effect) {
  38761. effect.setMatrices("mBones", matrices);
  38762. }
  38763. }
  38764. };
  38765. /**
  38766. * Binds the morph targets information from the mesh to the effect.
  38767. * @param abstractMesh The mesh we are binding the information to render
  38768. * @param effect The effect we are binding the data to
  38769. */
  38770. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38771. var manager = abstractMesh.morphTargetManager;
  38772. if (!abstractMesh || !manager) {
  38773. return;
  38774. }
  38775. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38776. };
  38777. /**
  38778. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38779. * @param defines The generated defines used in the effect
  38780. * @param effect The effect we are binding the data to
  38781. * @param scene The scene we are willing to render with logarithmic scale for
  38782. */
  38783. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38784. if (defines["LOGARITHMICDEPTH"]) {
  38785. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38786. }
  38787. };
  38788. /**
  38789. * Binds the clip plane information from the scene to the effect.
  38790. * @param scene The scene the clip plane information are extracted from
  38791. * @param effect The effect we are binding the data to
  38792. */
  38793. MaterialHelper.BindClipPlane = function (effect, scene) {
  38794. if (scene.clipPlane) {
  38795. var clipPlane = scene.clipPlane;
  38796. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38797. }
  38798. };
  38799. return MaterialHelper;
  38800. }());
  38801. BABYLON.MaterialHelper = MaterialHelper;
  38802. })(BABYLON || (BABYLON = {}));
  38803. //# sourceMappingURL=babylon.materialHelper.js.map
  38804. var BABYLON;
  38805. (function (BABYLON) {
  38806. var PushMaterial = /** @class */ (function (_super) {
  38807. __extends(PushMaterial, _super);
  38808. function PushMaterial(name, scene) {
  38809. var _this = _super.call(this, name, scene) || this;
  38810. _this._normalMatrix = new BABYLON.Matrix();
  38811. _this.storeEffectOnSubMeshes = true;
  38812. return _this;
  38813. }
  38814. PushMaterial.prototype.getEffect = function () {
  38815. return this._activeEffect;
  38816. };
  38817. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38818. if (!mesh) {
  38819. return false;
  38820. }
  38821. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38822. return true;
  38823. }
  38824. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38825. };
  38826. /**
  38827. * Binds the given world matrix to the active effect
  38828. *
  38829. * @param world the matrix to bind
  38830. */
  38831. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38832. this._activeEffect.setMatrix("world", world);
  38833. };
  38834. /**
  38835. * Binds the given normal matrix to the active effect
  38836. *
  38837. * @param normalMatrix the matrix to bind
  38838. */
  38839. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38840. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38841. };
  38842. PushMaterial.prototype.bind = function (world, mesh) {
  38843. if (!mesh) {
  38844. return;
  38845. }
  38846. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38847. };
  38848. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38849. if (effect === void 0) { effect = null; }
  38850. _super.prototype._afterBind.call(this, mesh);
  38851. this.getScene()._cachedEffect = effect;
  38852. };
  38853. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38854. if (visibility === void 0) { visibility = 1; }
  38855. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38856. };
  38857. return PushMaterial;
  38858. }(BABYLON.Material));
  38859. BABYLON.PushMaterial = PushMaterial;
  38860. })(BABYLON || (BABYLON = {}));
  38861. //# sourceMappingURL=babylon.pushMaterial.js.map
  38862. var BABYLON;
  38863. (function (BABYLON) {
  38864. /** @ignore */
  38865. var StandardMaterialDefines = /** @class */ (function (_super) {
  38866. __extends(StandardMaterialDefines, _super);
  38867. function StandardMaterialDefines() {
  38868. var _this = _super.call(this) || this;
  38869. _this.MAINUV1 = false;
  38870. _this.MAINUV2 = false;
  38871. _this.DIFFUSE = false;
  38872. _this.DIFFUSEDIRECTUV = 0;
  38873. _this.AMBIENT = false;
  38874. _this.AMBIENTDIRECTUV = 0;
  38875. _this.OPACITY = false;
  38876. _this.OPACITYDIRECTUV = 0;
  38877. _this.OPACITYRGB = false;
  38878. _this.REFLECTION = false;
  38879. _this.EMISSIVE = false;
  38880. _this.EMISSIVEDIRECTUV = 0;
  38881. _this.SPECULAR = false;
  38882. _this.SPECULARDIRECTUV = 0;
  38883. _this.BUMP = false;
  38884. _this.BUMPDIRECTUV = 0;
  38885. _this.PARALLAX = false;
  38886. _this.PARALLAXOCCLUSION = false;
  38887. _this.SPECULAROVERALPHA = false;
  38888. _this.CLIPPLANE = false;
  38889. _this.ALPHATEST = false;
  38890. _this.DEPTHPREPASS = false;
  38891. _this.ALPHAFROMDIFFUSE = false;
  38892. _this.POINTSIZE = false;
  38893. _this.FOG = false;
  38894. _this.SPECULARTERM = false;
  38895. _this.DIFFUSEFRESNEL = false;
  38896. _this.OPACITYFRESNEL = false;
  38897. _this.REFLECTIONFRESNEL = false;
  38898. _this.REFRACTIONFRESNEL = false;
  38899. _this.EMISSIVEFRESNEL = false;
  38900. _this.FRESNEL = false;
  38901. _this.NORMAL = false;
  38902. _this.UV1 = false;
  38903. _this.UV2 = false;
  38904. _this.VERTEXCOLOR = false;
  38905. _this.VERTEXALPHA = false;
  38906. _this.NUM_BONE_INFLUENCERS = 0;
  38907. _this.BonesPerMesh = 0;
  38908. _this.INSTANCES = false;
  38909. _this.GLOSSINESS = false;
  38910. _this.ROUGHNESS = false;
  38911. _this.EMISSIVEASILLUMINATION = false;
  38912. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38913. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38914. _this.LIGHTMAP = false;
  38915. _this.LIGHTMAPDIRECTUV = 0;
  38916. _this.OBJECTSPACE_NORMALMAP = false;
  38917. _this.USELIGHTMAPASSHADOWMAP = false;
  38918. _this.REFLECTIONMAP_3D = false;
  38919. _this.REFLECTIONMAP_SPHERICAL = false;
  38920. _this.REFLECTIONMAP_PLANAR = false;
  38921. _this.REFLECTIONMAP_CUBIC = false;
  38922. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38923. _this.REFLECTIONMAP_PROJECTION = false;
  38924. _this.REFLECTIONMAP_SKYBOX = false;
  38925. _this.REFLECTIONMAP_EXPLICIT = false;
  38926. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38927. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38928. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38929. _this.INVERTCUBICMAP = false;
  38930. _this.LOGARITHMICDEPTH = false;
  38931. _this.REFRACTION = false;
  38932. _this.REFRACTIONMAP_3D = false;
  38933. _this.REFLECTIONOVERALPHA = false;
  38934. _this.TWOSIDEDLIGHTING = false;
  38935. _this.SHADOWFLOAT = false;
  38936. _this.MORPHTARGETS = false;
  38937. _this.MORPHTARGETS_NORMAL = false;
  38938. _this.MORPHTARGETS_TANGENT = false;
  38939. _this.NUM_MORPH_INFLUENCERS = 0;
  38940. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38941. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38942. _this.IMAGEPROCESSING = false;
  38943. _this.VIGNETTE = false;
  38944. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38945. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38946. _this.TONEMAPPING = false;
  38947. _this.CONTRAST = false;
  38948. _this.COLORCURVES = false;
  38949. _this.COLORGRADING = false;
  38950. _this.COLORGRADING3D = false;
  38951. _this.SAMPLER3DGREENDEPTH = false;
  38952. _this.SAMPLER3DBGRMAP = false;
  38953. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38954. _this.EXPOSURE = false;
  38955. _this.GRAIN = false;
  38956. _this.rebuild();
  38957. return _this;
  38958. }
  38959. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38960. var modes = [
  38961. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38962. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38963. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38964. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38965. ];
  38966. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38967. var mode = modes_1[_i];
  38968. this[mode] = (mode === modeToEnable);
  38969. }
  38970. };
  38971. return StandardMaterialDefines;
  38972. }(BABYLON.MaterialDefines));
  38973. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38974. var StandardMaterial = /** @class */ (function (_super) {
  38975. __extends(StandardMaterial, _super);
  38976. function StandardMaterial(name, scene) {
  38977. var _this = _super.call(this, name, scene) || this;
  38978. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38979. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38980. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38981. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38982. _this.specularPower = 64;
  38983. _this._useAlphaFromDiffuseTexture = false;
  38984. _this._useEmissiveAsIllumination = false;
  38985. _this._linkEmissiveWithDiffuse = false;
  38986. _this._useSpecularOverAlpha = false;
  38987. _this._useReflectionOverAlpha = false;
  38988. _this._disableLighting = false;
  38989. _this._useObjectSpaceNormalMap = false;
  38990. _this._useParallax = false;
  38991. _this._useParallaxOcclusion = false;
  38992. _this.parallaxScaleBias = 0.05;
  38993. _this._roughness = 0;
  38994. _this.indexOfRefraction = 0.98;
  38995. _this.invertRefractionY = true;
  38996. _this._useLightmapAsShadowmap = false;
  38997. _this._useReflectionFresnelFromSpecular = false;
  38998. _this._useGlossinessFromSpecularMapAlpha = false;
  38999. _this._maxSimultaneousLights = 4;
  39000. /**
  39001. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39002. */
  39003. _this._invertNormalMapX = false;
  39004. /**
  39005. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39006. */
  39007. _this._invertNormalMapY = false;
  39008. /**
  39009. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39010. */
  39011. _this._twoSidedLighting = false;
  39012. _this._renderTargets = new BABYLON.SmartArray(16);
  39013. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39014. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39015. // Setup the default processing configuration to the scene.
  39016. _this._attachImageProcessingConfiguration(null);
  39017. _this.getRenderTargetTextures = function () {
  39018. _this._renderTargets.reset();
  39019. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39020. _this._renderTargets.push(_this._reflectionTexture);
  39021. }
  39022. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39023. _this._renderTargets.push(_this._refractionTexture);
  39024. }
  39025. return _this._renderTargets;
  39026. };
  39027. return _this;
  39028. }
  39029. ;
  39030. ;
  39031. ;
  39032. ;
  39033. ;
  39034. ;
  39035. ;
  39036. ;
  39037. ;
  39038. ;
  39039. ;
  39040. ;
  39041. ;
  39042. ;
  39043. ;
  39044. ;
  39045. ;
  39046. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39047. /**
  39048. * Gets the image processing configuration used either in this material.
  39049. */
  39050. get: function () {
  39051. return this._imageProcessingConfiguration;
  39052. },
  39053. /**
  39054. * Sets the Default image processing configuration used either in the this material.
  39055. *
  39056. * If sets to null, the scene one is in use.
  39057. */
  39058. set: function (value) {
  39059. this._attachImageProcessingConfiguration(value);
  39060. // Ensure the effect will be rebuilt.
  39061. this._markAllSubMeshesAsTexturesDirty();
  39062. },
  39063. enumerable: true,
  39064. configurable: true
  39065. });
  39066. /**
  39067. * Attaches a new image processing configuration to the Standard Material.
  39068. * @param configuration
  39069. */
  39070. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39071. var _this = this;
  39072. if (configuration === this._imageProcessingConfiguration) {
  39073. return;
  39074. }
  39075. // Detaches observer.
  39076. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39077. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39078. }
  39079. // Pick the scene configuration if needed.
  39080. if (!configuration) {
  39081. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39082. }
  39083. else {
  39084. this._imageProcessingConfiguration = configuration;
  39085. }
  39086. // Attaches observer.
  39087. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39088. _this._markAllSubMeshesAsImageProcessingDirty();
  39089. });
  39090. };
  39091. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39092. /**
  39093. * Gets wether the color curves effect is enabled.
  39094. */
  39095. get: function () {
  39096. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39097. },
  39098. /**
  39099. * Sets wether the color curves effect is enabled.
  39100. */
  39101. set: function (value) {
  39102. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39103. },
  39104. enumerable: true,
  39105. configurable: true
  39106. });
  39107. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39108. /**
  39109. * Gets wether the color grading effect is enabled.
  39110. */
  39111. get: function () {
  39112. return this.imageProcessingConfiguration.colorGradingEnabled;
  39113. },
  39114. /**
  39115. * Gets wether the color grading effect is enabled.
  39116. */
  39117. set: function (value) {
  39118. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39119. },
  39120. enumerable: true,
  39121. configurable: true
  39122. });
  39123. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39124. /**
  39125. * Gets wether tonemapping is enabled or not.
  39126. */
  39127. get: function () {
  39128. return this._imageProcessingConfiguration.toneMappingEnabled;
  39129. },
  39130. /**
  39131. * Sets wether tonemapping is enabled or not
  39132. */
  39133. set: function (value) {
  39134. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39135. },
  39136. enumerable: true,
  39137. configurable: true
  39138. });
  39139. ;
  39140. ;
  39141. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39142. /**
  39143. * The camera exposure used on this material.
  39144. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39145. * This corresponds to a photographic exposure.
  39146. */
  39147. get: function () {
  39148. return this._imageProcessingConfiguration.exposure;
  39149. },
  39150. /**
  39151. * The camera exposure used on this material.
  39152. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39153. * This corresponds to a photographic exposure.
  39154. */
  39155. set: function (value) {
  39156. this._imageProcessingConfiguration.exposure = value;
  39157. },
  39158. enumerable: true,
  39159. configurable: true
  39160. });
  39161. ;
  39162. ;
  39163. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39164. /**
  39165. * Gets The camera contrast used on this material.
  39166. */
  39167. get: function () {
  39168. return this._imageProcessingConfiguration.contrast;
  39169. },
  39170. /**
  39171. * Sets The camera contrast used on this material.
  39172. */
  39173. set: function (value) {
  39174. this._imageProcessingConfiguration.contrast = value;
  39175. },
  39176. enumerable: true,
  39177. configurable: true
  39178. });
  39179. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39180. /**
  39181. * Gets the Color Grading 2D Lookup Texture.
  39182. */
  39183. get: function () {
  39184. return this._imageProcessingConfiguration.colorGradingTexture;
  39185. },
  39186. /**
  39187. * Sets the Color Grading 2D Lookup Texture.
  39188. */
  39189. set: function (value) {
  39190. this._imageProcessingConfiguration.colorGradingTexture = value;
  39191. },
  39192. enumerable: true,
  39193. configurable: true
  39194. });
  39195. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39196. /**
  39197. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39198. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39199. * 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;
  39200. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39201. */
  39202. get: function () {
  39203. return this._imageProcessingConfiguration.colorCurves;
  39204. },
  39205. /**
  39206. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39207. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39208. * 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;
  39209. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39210. */
  39211. set: function (value) {
  39212. this._imageProcessingConfiguration.colorCurves = value;
  39213. },
  39214. enumerable: true,
  39215. configurable: true
  39216. });
  39217. StandardMaterial.prototype.getClassName = function () {
  39218. return "StandardMaterial";
  39219. };
  39220. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39221. get: function () {
  39222. return this._useLogarithmicDepth;
  39223. },
  39224. set: function (value) {
  39225. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39226. this._markAllSubMeshesAsMiscDirty();
  39227. },
  39228. enumerable: true,
  39229. configurable: true
  39230. });
  39231. StandardMaterial.prototype.needAlphaBlending = function () {
  39232. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39233. };
  39234. StandardMaterial.prototype.needAlphaTesting = function () {
  39235. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39236. };
  39237. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39238. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39239. };
  39240. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39241. return this._diffuseTexture;
  39242. };
  39243. /**
  39244. * Child classes can use it to update shaders
  39245. */
  39246. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39247. if (useInstances === void 0) { useInstances = false; }
  39248. if (subMesh.effect && this.isFrozen) {
  39249. if (this._wasPreviouslyReady && subMesh.effect) {
  39250. return true;
  39251. }
  39252. }
  39253. if (!subMesh._materialDefines) {
  39254. subMesh._materialDefines = new StandardMaterialDefines();
  39255. }
  39256. var scene = this.getScene();
  39257. var defines = subMesh._materialDefines;
  39258. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39259. if (defines._renderId === scene.getRenderId()) {
  39260. return true;
  39261. }
  39262. }
  39263. var engine = scene.getEngine();
  39264. // Lights
  39265. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39266. // Textures
  39267. if (defines._areTexturesDirty) {
  39268. defines._needUVs = false;
  39269. defines.MAINUV1 = false;
  39270. defines.MAINUV2 = false;
  39271. if (scene.texturesEnabled) {
  39272. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39273. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39274. return false;
  39275. }
  39276. else {
  39277. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39278. }
  39279. }
  39280. else {
  39281. defines.DIFFUSE = false;
  39282. }
  39283. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39284. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39285. return false;
  39286. }
  39287. else {
  39288. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39289. }
  39290. }
  39291. else {
  39292. defines.AMBIENT = false;
  39293. }
  39294. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39295. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39296. return false;
  39297. }
  39298. else {
  39299. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39300. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39301. }
  39302. }
  39303. else {
  39304. defines.OPACITY = false;
  39305. }
  39306. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39307. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39308. return false;
  39309. }
  39310. else {
  39311. defines._needNormals = true;
  39312. defines.REFLECTION = true;
  39313. defines.ROUGHNESS = (this._roughness > 0);
  39314. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39315. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39316. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39317. switch (this._reflectionTexture.coordinatesMode) {
  39318. case BABYLON.Texture.CUBIC_MODE:
  39319. case BABYLON.Texture.INVCUBIC_MODE:
  39320. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39321. break;
  39322. case BABYLON.Texture.EXPLICIT_MODE:
  39323. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39324. break;
  39325. case BABYLON.Texture.PLANAR_MODE:
  39326. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39327. break;
  39328. case BABYLON.Texture.PROJECTION_MODE:
  39329. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39330. break;
  39331. case BABYLON.Texture.SKYBOX_MODE:
  39332. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39333. break;
  39334. case BABYLON.Texture.SPHERICAL_MODE:
  39335. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39336. break;
  39337. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39338. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39339. break;
  39340. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39341. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39342. break;
  39343. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39344. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39345. break;
  39346. }
  39347. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39348. }
  39349. }
  39350. else {
  39351. defines.REFLECTION = false;
  39352. }
  39353. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39354. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39355. return false;
  39356. }
  39357. else {
  39358. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39359. }
  39360. }
  39361. else {
  39362. defines.EMISSIVE = false;
  39363. }
  39364. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39365. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39366. return false;
  39367. }
  39368. else {
  39369. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39370. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39371. }
  39372. }
  39373. else {
  39374. defines.LIGHTMAP = false;
  39375. }
  39376. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39377. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39378. return false;
  39379. }
  39380. else {
  39381. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39382. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39383. }
  39384. }
  39385. else {
  39386. defines.SPECULAR = false;
  39387. }
  39388. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39389. // Bump texure can not be not blocking.
  39390. if (!this._bumpTexture.isReady()) {
  39391. return false;
  39392. }
  39393. else {
  39394. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39395. defines.PARALLAX = this._useParallax;
  39396. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39397. }
  39398. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39399. }
  39400. else {
  39401. defines.BUMP = false;
  39402. }
  39403. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39404. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39405. return false;
  39406. }
  39407. else {
  39408. defines._needUVs = true;
  39409. defines.REFRACTION = true;
  39410. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39411. }
  39412. }
  39413. else {
  39414. defines.REFRACTION = false;
  39415. }
  39416. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39417. }
  39418. else {
  39419. defines.DIFFUSE = false;
  39420. defines.AMBIENT = false;
  39421. defines.OPACITY = false;
  39422. defines.REFLECTION = false;
  39423. defines.EMISSIVE = false;
  39424. defines.LIGHTMAP = false;
  39425. defines.BUMP = false;
  39426. defines.REFRACTION = false;
  39427. }
  39428. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39429. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39430. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39431. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39432. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39433. }
  39434. if (defines._areImageProcessingDirty) {
  39435. if (!this._imageProcessingConfiguration.isReady()) {
  39436. return false;
  39437. }
  39438. this._imageProcessingConfiguration.prepareDefines(defines);
  39439. }
  39440. if (defines._areFresnelDirty) {
  39441. if (StandardMaterial.FresnelEnabled) {
  39442. // Fresnel
  39443. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39444. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39445. this._reflectionFresnelParameters) {
  39446. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39447. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39448. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39449. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39450. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39451. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39452. defines._needNormals = true;
  39453. defines.FRESNEL = true;
  39454. }
  39455. }
  39456. else {
  39457. defines.FRESNEL = false;
  39458. }
  39459. }
  39460. // Misc.
  39461. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39462. // Attribs
  39463. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39464. // Values that need to be evaluated on every frame
  39465. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39466. // Get correct effect
  39467. if (defines.isDirty) {
  39468. defines.markAsProcessed();
  39469. scene.resetCachedMaterial();
  39470. // Fallbacks
  39471. var fallbacks = new BABYLON.EffectFallbacks();
  39472. if (defines.REFLECTION) {
  39473. fallbacks.addFallback(0, "REFLECTION");
  39474. }
  39475. if (defines.SPECULAR) {
  39476. fallbacks.addFallback(0, "SPECULAR");
  39477. }
  39478. if (defines.BUMP) {
  39479. fallbacks.addFallback(0, "BUMP");
  39480. }
  39481. if (defines.PARALLAX) {
  39482. fallbacks.addFallback(1, "PARALLAX");
  39483. }
  39484. if (defines.PARALLAXOCCLUSION) {
  39485. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39486. }
  39487. if (defines.SPECULAROVERALPHA) {
  39488. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39489. }
  39490. if (defines.FOG) {
  39491. fallbacks.addFallback(1, "FOG");
  39492. }
  39493. if (defines.POINTSIZE) {
  39494. fallbacks.addFallback(0, "POINTSIZE");
  39495. }
  39496. if (defines.LOGARITHMICDEPTH) {
  39497. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39498. }
  39499. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39500. if (defines.SPECULARTERM) {
  39501. fallbacks.addFallback(0, "SPECULARTERM");
  39502. }
  39503. if (defines.DIFFUSEFRESNEL) {
  39504. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39505. }
  39506. if (defines.OPACITYFRESNEL) {
  39507. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39508. }
  39509. if (defines.REFLECTIONFRESNEL) {
  39510. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39511. }
  39512. if (defines.EMISSIVEFRESNEL) {
  39513. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39514. }
  39515. if (defines.FRESNEL) {
  39516. fallbacks.addFallback(4, "FRESNEL");
  39517. }
  39518. //Attributes
  39519. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39520. if (defines.NORMAL) {
  39521. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39522. }
  39523. if (defines.UV1) {
  39524. attribs.push(BABYLON.VertexBuffer.UVKind);
  39525. }
  39526. if (defines.UV2) {
  39527. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39528. }
  39529. if (defines.VERTEXCOLOR) {
  39530. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39531. }
  39532. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39533. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39534. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39535. var shaderName = "default";
  39536. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39537. "vFogInfos", "vFogColor", "pointSize",
  39538. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39539. "mBones",
  39540. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39541. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39542. "vReflectionPosition", "vReflectionSize",
  39543. "logarithmicDepthConstant", "vTangentSpaceParams"
  39544. ];
  39545. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39546. var uniformBuffers = ["Material", "Scene"];
  39547. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39548. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39549. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39550. uniformsNames: uniforms,
  39551. uniformBuffersNames: uniformBuffers,
  39552. samplers: samplers,
  39553. defines: defines,
  39554. maxSimultaneousLights: this._maxSimultaneousLights
  39555. });
  39556. if (this.customShaderNameResolve) {
  39557. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39558. }
  39559. var join = defines.toString();
  39560. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39561. attributes: attribs,
  39562. uniformsNames: uniforms,
  39563. uniformBuffersNames: uniformBuffers,
  39564. samplers: samplers,
  39565. defines: join,
  39566. fallbacks: fallbacks,
  39567. onCompiled: this.onCompiled,
  39568. onError: this.onError,
  39569. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39570. }, engine), defines);
  39571. this.buildUniformLayout();
  39572. }
  39573. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39574. return false;
  39575. }
  39576. defines._renderId = scene.getRenderId();
  39577. this._wasPreviouslyReady = true;
  39578. return true;
  39579. };
  39580. StandardMaterial.prototype.buildUniformLayout = function () {
  39581. // Order is important !
  39582. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39583. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39584. this._uniformBuffer.addUniform("opacityParts", 4);
  39585. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39586. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39587. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39588. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39589. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39590. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39591. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39592. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39593. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39594. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39595. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39596. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39597. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39598. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39599. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39600. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39601. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39602. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39603. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39604. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39605. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39606. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39607. this._uniformBuffer.addUniform("specularMatrix", 16);
  39608. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39609. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39610. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39611. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39612. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39613. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39614. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39615. this._uniformBuffer.addUniform("pointSize", 1);
  39616. this._uniformBuffer.create();
  39617. };
  39618. StandardMaterial.prototype.unbind = function () {
  39619. if (this._activeEffect) {
  39620. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39621. this._activeEffect.setTexture("reflection2DSampler", null);
  39622. }
  39623. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39624. this._activeEffect.setTexture("refraction2DSampler", null);
  39625. }
  39626. }
  39627. _super.prototype.unbind.call(this);
  39628. };
  39629. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39630. var scene = this.getScene();
  39631. var defines = subMesh._materialDefines;
  39632. if (!defines) {
  39633. return;
  39634. }
  39635. var effect = subMesh.effect;
  39636. if (!effect) {
  39637. return;
  39638. }
  39639. this._activeEffect = effect;
  39640. // Matrices
  39641. this.bindOnlyWorldMatrix(world);
  39642. // Normal Matrix
  39643. if (defines.OBJECTSPACE_NORMALMAP) {
  39644. world.toNormalMatrix(this._normalMatrix);
  39645. this.bindOnlyNormalMatrix(this._normalMatrix);
  39646. }
  39647. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39648. // Bones
  39649. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39650. if (mustRebind) {
  39651. this._uniformBuffer.bindToEffect(effect, "Material");
  39652. this.bindViewProjection(effect);
  39653. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39654. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39655. // Fresnel
  39656. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39657. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39658. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39659. }
  39660. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39661. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39662. }
  39663. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39664. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39665. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39666. }
  39667. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39668. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39669. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39670. }
  39671. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39672. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39673. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39674. }
  39675. }
  39676. // Textures
  39677. if (scene.texturesEnabled) {
  39678. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39679. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39680. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39681. }
  39682. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39683. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39684. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39685. }
  39686. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39687. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39688. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39689. }
  39690. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39691. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39692. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39693. if (this._reflectionTexture.boundingBoxSize) {
  39694. var cubeTexture = this._reflectionTexture;
  39695. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39696. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39697. }
  39698. }
  39699. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39700. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39701. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39702. }
  39703. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39704. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39705. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39706. }
  39707. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39708. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39709. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39710. }
  39711. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39712. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39713. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39714. if (scene._mirroredCameraPosition) {
  39715. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39716. }
  39717. else {
  39718. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39719. }
  39720. }
  39721. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39722. var depth = 1.0;
  39723. if (!this._refractionTexture.isCube) {
  39724. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39725. if (this._refractionTexture.depth) {
  39726. depth = this._refractionTexture.depth;
  39727. }
  39728. }
  39729. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39730. }
  39731. }
  39732. // Point size
  39733. if (this.pointsCloud) {
  39734. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39735. }
  39736. if (defines.SPECULARTERM) {
  39737. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39738. }
  39739. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39740. // Diffuse
  39741. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39742. }
  39743. // Textures
  39744. if (scene.texturesEnabled) {
  39745. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39746. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39747. }
  39748. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39749. effect.setTexture("ambientSampler", this._ambientTexture);
  39750. }
  39751. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39752. effect.setTexture("opacitySampler", this._opacityTexture);
  39753. }
  39754. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39755. if (this._reflectionTexture.isCube) {
  39756. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39757. }
  39758. else {
  39759. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39760. }
  39761. }
  39762. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39763. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39764. }
  39765. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39766. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39767. }
  39768. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39769. effect.setTexture("specularSampler", this._specularTexture);
  39770. }
  39771. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39772. effect.setTexture("bumpSampler", this._bumpTexture);
  39773. }
  39774. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39775. var depth = 1.0;
  39776. if (this._refractionTexture.isCube) {
  39777. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39778. }
  39779. else {
  39780. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39781. }
  39782. }
  39783. }
  39784. // Clip plane
  39785. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39786. // Colors
  39787. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39788. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39789. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39790. }
  39791. if (mustRebind || !this.isFrozen) {
  39792. // Lights
  39793. if (scene.lightsEnabled && !this._disableLighting) {
  39794. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39795. }
  39796. // View
  39797. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39798. this.bindView(effect);
  39799. }
  39800. // Fog
  39801. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39802. // Morph targets
  39803. if (defines.NUM_MORPH_INFLUENCERS) {
  39804. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39805. }
  39806. // Log. depth
  39807. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39808. // image processing
  39809. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39810. this._imageProcessingConfiguration.bind(this._activeEffect);
  39811. }
  39812. }
  39813. this._uniformBuffer.update();
  39814. this._afterBind(mesh, this._activeEffect);
  39815. };
  39816. StandardMaterial.prototype.getAnimatables = function () {
  39817. var results = [];
  39818. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39819. results.push(this._diffuseTexture);
  39820. }
  39821. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39822. results.push(this._ambientTexture);
  39823. }
  39824. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39825. results.push(this._opacityTexture);
  39826. }
  39827. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39828. results.push(this._reflectionTexture);
  39829. }
  39830. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39831. results.push(this._emissiveTexture);
  39832. }
  39833. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39834. results.push(this._specularTexture);
  39835. }
  39836. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39837. results.push(this._bumpTexture);
  39838. }
  39839. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39840. results.push(this._lightmapTexture);
  39841. }
  39842. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39843. results.push(this._refractionTexture);
  39844. }
  39845. return results;
  39846. };
  39847. StandardMaterial.prototype.getActiveTextures = function () {
  39848. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39849. if (this._diffuseTexture) {
  39850. activeTextures.push(this._diffuseTexture);
  39851. }
  39852. if (this._ambientTexture) {
  39853. activeTextures.push(this._ambientTexture);
  39854. }
  39855. if (this._opacityTexture) {
  39856. activeTextures.push(this._opacityTexture);
  39857. }
  39858. if (this._reflectionTexture) {
  39859. activeTextures.push(this._reflectionTexture);
  39860. }
  39861. if (this._emissiveTexture) {
  39862. activeTextures.push(this._emissiveTexture);
  39863. }
  39864. if (this._specularTexture) {
  39865. activeTextures.push(this._specularTexture);
  39866. }
  39867. if (this._bumpTexture) {
  39868. activeTextures.push(this._bumpTexture);
  39869. }
  39870. if (this._lightmapTexture) {
  39871. activeTextures.push(this._lightmapTexture);
  39872. }
  39873. if (this._refractionTexture) {
  39874. activeTextures.push(this._refractionTexture);
  39875. }
  39876. return activeTextures;
  39877. };
  39878. StandardMaterial.prototype.hasTexture = function (texture) {
  39879. if (_super.prototype.hasTexture.call(this, texture)) {
  39880. return true;
  39881. }
  39882. if (this._diffuseTexture === texture) {
  39883. return true;
  39884. }
  39885. if (this._ambientTexture === texture) {
  39886. return true;
  39887. }
  39888. if (this._opacityTexture === texture) {
  39889. return true;
  39890. }
  39891. if (this._reflectionTexture === texture) {
  39892. return true;
  39893. }
  39894. if (this._emissiveTexture === texture) {
  39895. return true;
  39896. }
  39897. if (this._specularTexture === texture) {
  39898. return true;
  39899. }
  39900. if (this._bumpTexture === texture) {
  39901. return true;
  39902. }
  39903. if (this._lightmapTexture === texture) {
  39904. return true;
  39905. }
  39906. if (this._refractionTexture === texture) {
  39907. return true;
  39908. }
  39909. return false;
  39910. };
  39911. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39912. if (forceDisposeTextures) {
  39913. if (this._diffuseTexture) {
  39914. this._diffuseTexture.dispose();
  39915. }
  39916. if (this._ambientTexture) {
  39917. this._ambientTexture.dispose();
  39918. }
  39919. if (this._opacityTexture) {
  39920. this._opacityTexture.dispose();
  39921. }
  39922. if (this._reflectionTexture) {
  39923. this._reflectionTexture.dispose();
  39924. }
  39925. if (this._emissiveTexture) {
  39926. this._emissiveTexture.dispose();
  39927. }
  39928. if (this._specularTexture) {
  39929. this._specularTexture.dispose();
  39930. }
  39931. if (this._bumpTexture) {
  39932. this._bumpTexture.dispose();
  39933. }
  39934. if (this._lightmapTexture) {
  39935. this._lightmapTexture.dispose();
  39936. }
  39937. if (this._refractionTexture) {
  39938. this._refractionTexture.dispose();
  39939. }
  39940. }
  39941. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39942. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39943. }
  39944. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39945. };
  39946. StandardMaterial.prototype.clone = function (name) {
  39947. var _this = this;
  39948. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39949. result.name = name;
  39950. result.id = name;
  39951. return result;
  39952. };
  39953. StandardMaterial.prototype.serialize = function () {
  39954. return BABYLON.SerializationHelper.Serialize(this);
  39955. };
  39956. // Statics
  39957. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39958. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39959. };
  39960. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39961. get: function () {
  39962. return StandardMaterial._DiffuseTextureEnabled;
  39963. },
  39964. set: function (value) {
  39965. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39966. return;
  39967. }
  39968. StandardMaterial._DiffuseTextureEnabled = value;
  39969. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39970. },
  39971. enumerable: true,
  39972. configurable: true
  39973. });
  39974. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39975. get: function () {
  39976. return StandardMaterial._AmbientTextureEnabled;
  39977. },
  39978. set: function (value) {
  39979. if (StandardMaterial._AmbientTextureEnabled === value) {
  39980. return;
  39981. }
  39982. StandardMaterial._AmbientTextureEnabled = value;
  39983. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39984. },
  39985. enumerable: true,
  39986. configurable: true
  39987. });
  39988. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39989. get: function () {
  39990. return StandardMaterial._OpacityTextureEnabled;
  39991. },
  39992. set: function (value) {
  39993. if (StandardMaterial._OpacityTextureEnabled === value) {
  39994. return;
  39995. }
  39996. StandardMaterial._OpacityTextureEnabled = value;
  39997. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39998. },
  39999. enumerable: true,
  40000. configurable: true
  40001. });
  40002. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40003. get: function () {
  40004. return StandardMaterial._ReflectionTextureEnabled;
  40005. },
  40006. set: function (value) {
  40007. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40008. return;
  40009. }
  40010. StandardMaterial._ReflectionTextureEnabled = value;
  40011. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40012. },
  40013. enumerable: true,
  40014. configurable: true
  40015. });
  40016. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40017. get: function () {
  40018. return StandardMaterial._EmissiveTextureEnabled;
  40019. },
  40020. set: function (value) {
  40021. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40022. return;
  40023. }
  40024. StandardMaterial._EmissiveTextureEnabled = value;
  40025. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40026. },
  40027. enumerable: true,
  40028. configurable: true
  40029. });
  40030. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40031. get: function () {
  40032. return StandardMaterial._SpecularTextureEnabled;
  40033. },
  40034. set: function (value) {
  40035. if (StandardMaterial._SpecularTextureEnabled === value) {
  40036. return;
  40037. }
  40038. StandardMaterial._SpecularTextureEnabled = value;
  40039. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40040. },
  40041. enumerable: true,
  40042. configurable: true
  40043. });
  40044. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40045. get: function () {
  40046. return StandardMaterial._BumpTextureEnabled;
  40047. },
  40048. set: function (value) {
  40049. if (StandardMaterial._BumpTextureEnabled === value) {
  40050. return;
  40051. }
  40052. StandardMaterial._BumpTextureEnabled = value;
  40053. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40054. },
  40055. enumerable: true,
  40056. configurable: true
  40057. });
  40058. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40059. get: function () {
  40060. return StandardMaterial._LightmapTextureEnabled;
  40061. },
  40062. set: function (value) {
  40063. if (StandardMaterial._LightmapTextureEnabled === value) {
  40064. return;
  40065. }
  40066. StandardMaterial._LightmapTextureEnabled = value;
  40067. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40068. },
  40069. enumerable: true,
  40070. configurable: true
  40071. });
  40072. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40073. get: function () {
  40074. return StandardMaterial._RefractionTextureEnabled;
  40075. },
  40076. set: function (value) {
  40077. if (StandardMaterial._RefractionTextureEnabled === value) {
  40078. return;
  40079. }
  40080. StandardMaterial._RefractionTextureEnabled = value;
  40081. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40082. },
  40083. enumerable: true,
  40084. configurable: true
  40085. });
  40086. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40087. get: function () {
  40088. return StandardMaterial._ColorGradingTextureEnabled;
  40089. },
  40090. set: function (value) {
  40091. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40092. return;
  40093. }
  40094. StandardMaterial._ColorGradingTextureEnabled = value;
  40095. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40096. },
  40097. enumerable: true,
  40098. configurable: true
  40099. });
  40100. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40101. get: function () {
  40102. return StandardMaterial._FresnelEnabled;
  40103. },
  40104. set: function (value) {
  40105. if (StandardMaterial._FresnelEnabled === value) {
  40106. return;
  40107. }
  40108. StandardMaterial._FresnelEnabled = value;
  40109. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40110. },
  40111. enumerable: true,
  40112. configurable: true
  40113. });
  40114. // Flags used to enable or disable a type of texture for all Standard Materials
  40115. StandardMaterial._DiffuseTextureEnabled = true;
  40116. StandardMaterial._AmbientTextureEnabled = true;
  40117. StandardMaterial._OpacityTextureEnabled = true;
  40118. StandardMaterial._ReflectionTextureEnabled = true;
  40119. StandardMaterial._EmissiveTextureEnabled = true;
  40120. StandardMaterial._SpecularTextureEnabled = true;
  40121. StandardMaterial._BumpTextureEnabled = true;
  40122. StandardMaterial._LightmapTextureEnabled = true;
  40123. StandardMaterial._RefractionTextureEnabled = true;
  40124. StandardMaterial._ColorGradingTextureEnabled = true;
  40125. StandardMaterial._FresnelEnabled = true;
  40126. __decorate([
  40127. BABYLON.serializeAsTexture("diffuseTexture")
  40128. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40129. __decorate([
  40130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40131. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40132. __decorate([
  40133. BABYLON.serializeAsTexture("ambientTexture")
  40134. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40135. __decorate([
  40136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40137. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40138. __decorate([
  40139. BABYLON.serializeAsTexture("opacityTexture")
  40140. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40141. __decorate([
  40142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40143. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40144. __decorate([
  40145. BABYLON.serializeAsTexture("reflectionTexture")
  40146. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40147. __decorate([
  40148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40149. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40150. __decorate([
  40151. BABYLON.serializeAsTexture("emissiveTexture")
  40152. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40153. __decorate([
  40154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40155. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40156. __decorate([
  40157. BABYLON.serializeAsTexture("specularTexture")
  40158. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40159. __decorate([
  40160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40161. ], StandardMaterial.prototype, "specularTexture", void 0);
  40162. __decorate([
  40163. BABYLON.serializeAsTexture("bumpTexture")
  40164. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40165. __decorate([
  40166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40167. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40168. __decorate([
  40169. BABYLON.serializeAsTexture("lightmapTexture")
  40170. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40171. __decorate([
  40172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40173. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40174. __decorate([
  40175. BABYLON.serializeAsTexture("refractionTexture")
  40176. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40177. __decorate([
  40178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40179. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40180. __decorate([
  40181. BABYLON.serializeAsColor3("ambient")
  40182. ], StandardMaterial.prototype, "ambientColor", void 0);
  40183. __decorate([
  40184. BABYLON.serializeAsColor3("diffuse")
  40185. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40186. __decorate([
  40187. BABYLON.serializeAsColor3("specular")
  40188. ], StandardMaterial.prototype, "specularColor", void 0);
  40189. __decorate([
  40190. BABYLON.serializeAsColor3("emissive")
  40191. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40192. __decorate([
  40193. BABYLON.serialize()
  40194. ], StandardMaterial.prototype, "specularPower", void 0);
  40195. __decorate([
  40196. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40197. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40198. __decorate([
  40199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40200. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40201. __decorate([
  40202. BABYLON.serialize("useEmissiveAsIllumination")
  40203. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40204. __decorate([
  40205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40206. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40207. __decorate([
  40208. BABYLON.serialize("linkEmissiveWithDiffuse")
  40209. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40210. __decorate([
  40211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40212. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40213. __decorate([
  40214. BABYLON.serialize("useSpecularOverAlpha")
  40215. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40216. __decorate([
  40217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40218. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40219. __decorate([
  40220. BABYLON.serialize("useReflectionOverAlpha")
  40221. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40222. __decorate([
  40223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40224. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40225. __decorate([
  40226. BABYLON.serialize("disableLighting")
  40227. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40228. __decorate([
  40229. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40230. ], StandardMaterial.prototype, "disableLighting", void 0);
  40231. __decorate([
  40232. BABYLON.serialize("useObjectSpaceNormalMap")
  40233. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40234. __decorate([
  40235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40236. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40237. __decorate([
  40238. BABYLON.serialize("useParallax")
  40239. ], StandardMaterial.prototype, "_useParallax", void 0);
  40240. __decorate([
  40241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40242. ], StandardMaterial.prototype, "useParallax", void 0);
  40243. __decorate([
  40244. BABYLON.serialize("useParallaxOcclusion")
  40245. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40246. __decorate([
  40247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40248. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40249. __decorate([
  40250. BABYLON.serialize()
  40251. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40252. __decorate([
  40253. BABYLON.serialize("roughness")
  40254. ], StandardMaterial.prototype, "_roughness", void 0);
  40255. __decorate([
  40256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40257. ], StandardMaterial.prototype, "roughness", void 0);
  40258. __decorate([
  40259. BABYLON.serialize()
  40260. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40261. __decorate([
  40262. BABYLON.serialize()
  40263. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40264. __decorate([
  40265. BABYLON.serialize("useLightmapAsShadowmap")
  40266. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40267. __decorate([
  40268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40269. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40270. __decorate([
  40271. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40272. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40273. __decorate([
  40274. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40275. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40276. __decorate([
  40277. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40278. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40279. __decorate([
  40280. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40281. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40282. __decorate([
  40283. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40284. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40285. __decorate([
  40286. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40287. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40288. __decorate([
  40289. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40290. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40291. __decorate([
  40292. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40293. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40294. __decorate([
  40295. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40296. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40297. __decorate([
  40298. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40299. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40300. __decorate([
  40301. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40302. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40303. __decorate([
  40304. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40305. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40306. __decorate([
  40307. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40308. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40309. __decorate([
  40310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40311. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40312. __decorate([
  40313. BABYLON.serialize("maxSimultaneousLights")
  40314. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40315. __decorate([
  40316. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40317. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40318. __decorate([
  40319. BABYLON.serialize("invertNormalMapX")
  40320. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40321. __decorate([
  40322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40323. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40324. __decorate([
  40325. BABYLON.serialize("invertNormalMapY")
  40326. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40327. __decorate([
  40328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40329. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40330. __decorate([
  40331. BABYLON.serialize("twoSidedLighting")
  40332. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40333. __decorate([
  40334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40335. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40336. __decorate([
  40337. BABYLON.serialize()
  40338. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40339. return StandardMaterial;
  40340. }(BABYLON.PushMaterial));
  40341. BABYLON.StandardMaterial = StandardMaterial;
  40342. })(BABYLON || (BABYLON = {}));
  40343. //# sourceMappingURL=babylon.standardMaterial.js.map
  40344. var BABYLON;
  40345. (function (BABYLON) {
  40346. /**
  40347. * Manages the defines for the PBR Material.
  40348. */
  40349. var PBRMaterialDefines = /** @class */ (function (_super) {
  40350. __extends(PBRMaterialDefines, _super);
  40351. /**
  40352. * Initializes the PBR Material defines.
  40353. */
  40354. function PBRMaterialDefines() {
  40355. var _this = _super.call(this) || this;
  40356. _this.PBR = true;
  40357. _this.MAINUV1 = false;
  40358. _this.MAINUV2 = false;
  40359. _this.UV1 = false;
  40360. _this.UV2 = false;
  40361. _this.ALBEDO = false;
  40362. _this.ALBEDODIRECTUV = 0;
  40363. _this.VERTEXCOLOR = false;
  40364. _this.AMBIENT = false;
  40365. _this.AMBIENTDIRECTUV = 0;
  40366. _this.AMBIENTINGRAYSCALE = false;
  40367. _this.OPACITY = false;
  40368. _this.VERTEXALPHA = false;
  40369. _this.OPACITYDIRECTUV = 0;
  40370. _this.OPACITYRGB = false;
  40371. _this.ALPHATEST = false;
  40372. _this.DEPTHPREPASS = false;
  40373. _this.ALPHABLEND = false;
  40374. _this.ALPHAFROMALBEDO = false;
  40375. _this.ALPHATESTVALUE = 0.5;
  40376. _this.SPECULAROVERALPHA = false;
  40377. _this.RADIANCEOVERALPHA = false;
  40378. _this.ALPHAFRESNEL = false;
  40379. _this.LINEARALPHAFRESNEL = false;
  40380. _this.PREMULTIPLYALPHA = false;
  40381. _this.EMISSIVE = false;
  40382. _this.EMISSIVEDIRECTUV = 0;
  40383. _this.REFLECTIVITY = false;
  40384. _this.REFLECTIVITYDIRECTUV = 0;
  40385. _this.SPECULARTERM = false;
  40386. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40387. _this.MICROSURFACEAUTOMATIC = false;
  40388. _this.LODBASEDMICROSFURACE = false;
  40389. _this.MICROSURFACEMAP = false;
  40390. _this.MICROSURFACEMAPDIRECTUV = 0;
  40391. _this.METALLICWORKFLOW = false;
  40392. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40393. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40394. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40395. _this.AOSTOREINMETALMAPRED = false;
  40396. _this.ENVIRONMENTBRDF = false;
  40397. _this.NORMAL = false;
  40398. _this.TANGENT = false;
  40399. _this.BUMP = false;
  40400. _this.BUMPDIRECTUV = 0;
  40401. _this.OBJECTSPACE_NORMALMAP = false;
  40402. _this.PARALLAX = false;
  40403. _this.PARALLAXOCCLUSION = false;
  40404. _this.NORMALXYSCALE = true;
  40405. _this.LIGHTMAP = false;
  40406. _this.LIGHTMAPDIRECTUV = 0;
  40407. _this.USELIGHTMAPASSHADOWMAP = false;
  40408. _this.REFLECTION = false;
  40409. _this.REFLECTIONMAP_3D = false;
  40410. _this.REFLECTIONMAP_SPHERICAL = false;
  40411. _this.REFLECTIONMAP_PLANAR = false;
  40412. _this.REFLECTIONMAP_CUBIC = false;
  40413. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40414. _this.REFLECTIONMAP_PROJECTION = false;
  40415. _this.REFLECTIONMAP_SKYBOX = false;
  40416. _this.REFLECTIONMAP_EXPLICIT = false;
  40417. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40418. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40419. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40420. _this.INVERTCUBICMAP = false;
  40421. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40422. _this.USESPHERICALINVERTEX = false;
  40423. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40424. _this.LODINREFLECTIONALPHA = false;
  40425. _this.GAMMAREFLECTION = false;
  40426. _this.RADIANCEOCCLUSION = false;
  40427. _this.HORIZONOCCLUSION = false;
  40428. _this.REFRACTION = false;
  40429. _this.REFRACTIONMAP_3D = false;
  40430. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40431. _this.LODINREFRACTIONALPHA = false;
  40432. _this.GAMMAREFRACTION = false;
  40433. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40434. _this.INSTANCES = false;
  40435. _this.NUM_BONE_INFLUENCERS = 0;
  40436. _this.BonesPerMesh = 0;
  40437. _this.NONUNIFORMSCALING = false;
  40438. _this.MORPHTARGETS = false;
  40439. _this.MORPHTARGETS_NORMAL = false;
  40440. _this.MORPHTARGETS_TANGENT = false;
  40441. _this.NUM_MORPH_INFLUENCERS = 0;
  40442. _this.IMAGEPROCESSING = false;
  40443. _this.VIGNETTE = false;
  40444. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40445. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40446. _this.TONEMAPPING = false;
  40447. _this.CONTRAST = false;
  40448. _this.COLORCURVES = false;
  40449. _this.COLORGRADING = false;
  40450. _this.COLORGRADING3D = false;
  40451. _this.SAMPLER3DGREENDEPTH = false;
  40452. _this.SAMPLER3DBGRMAP = false;
  40453. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40454. _this.EXPOSURE = false;
  40455. _this.GRAIN = false;
  40456. _this.USEPHYSICALLIGHTFALLOFF = false;
  40457. _this.TWOSIDEDLIGHTING = false;
  40458. _this.SHADOWFLOAT = false;
  40459. _this.CLIPPLANE = false;
  40460. _this.POINTSIZE = false;
  40461. _this.FOG = false;
  40462. _this.LOGARITHMICDEPTH = false;
  40463. _this.FORCENORMALFORWARD = false;
  40464. _this.rebuild();
  40465. return _this;
  40466. }
  40467. /**
  40468. * Resets the PBR Material defines.
  40469. */
  40470. PBRMaterialDefines.prototype.reset = function () {
  40471. _super.prototype.reset.call(this);
  40472. this.ALPHATESTVALUE = 0.5;
  40473. this.PBR = true;
  40474. };
  40475. return PBRMaterialDefines;
  40476. }(BABYLON.MaterialDefines));
  40477. /**
  40478. * The Physically based material base class of BJS.
  40479. *
  40480. * This offers the main features of a standard PBR material.
  40481. * For more information, please refer to the documentation :
  40482. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40483. */
  40484. var PBRBaseMaterial = /** @class */ (function (_super) {
  40485. __extends(PBRBaseMaterial, _super);
  40486. /**
  40487. * Instantiates a new PBRMaterial instance.
  40488. *
  40489. * @param name The material name
  40490. * @param scene The scene the material will be use in.
  40491. */
  40492. function PBRBaseMaterial(name, scene) {
  40493. var _this = _super.call(this, name, scene) || this;
  40494. /**
  40495. * Intensity of the direct lights e.g. the four lights available in your scene.
  40496. * This impacts both the direct diffuse and specular highlights.
  40497. */
  40498. _this._directIntensity = 1.0;
  40499. /**
  40500. * Intensity of the emissive part of the material.
  40501. * This helps controlling the emissive effect without modifying the emissive color.
  40502. */
  40503. _this._emissiveIntensity = 1.0;
  40504. /**
  40505. * Intensity of the environment e.g. how much the environment will light the object
  40506. * either through harmonics for rough material or through the refelction for shiny ones.
  40507. */
  40508. _this._environmentIntensity = 1.0;
  40509. /**
  40510. * This is a special control allowing the reduction of the specular highlights coming from the
  40511. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40512. */
  40513. _this._specularIntensity = 1.0;
  40514. /**
  40515. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40516. */
  40517. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40518. /**
  40519. * Debug Control allowing disabling the bump map on this material.
  40520. */
  40521. _this._disableBumpMap = false;
  40522. /**
  40523. * AKA Occlusion Texture Intensity in other nomenclature.
  40524. */
  40525. _this._ambientTextureStrength = 1.0;
  40526. /**
  40527. * The color of a material in ambient lighting.
  40528. */
  40529. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40530. /**
  40531. * AKA Diffuse Color in other nomenclature.
  40532. */
  40533. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40534. /**
  40535. * AKA Specular Color in other nomenclature.
  40536. */
  40537. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40538. /**
  40539. * The color applied when light is reflected from a material.
  40540. */
  40541. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40542. /**
  40543. * The color applied when light is emitted from a material.
  40544. */
  40545. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40546. /**
  40547. * AKA Glossiness in other nomenclature.
  40548. */
  40549. _this._microSurface = 0.9;
  40550. /**
  40551. * source material index of refraction (IOR)' / 'destination material IOR.
  40552. */
  40553. _this._indexOfRefraction = 0.66;
  40554. /**
  40555. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40556. */
  40557. _this._invertRefractionY = false;
  40558. /**
  40559. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40560. * Materials half opaque for instance using refraction could benefit from this control.
  40561. */
  40562. _this._linkRefractionWithTransparency = false;
  40563. /**
  40564. * Specifies that the material will use the light map as a show map.
  40565. */
  40566. _this._useLightmapAsShadowmap = false;
  40567. /**
  40568. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40569. * makes the reflect vector face the model (under horizon).
  40570. */
  40571. _this._useHorizonOcclusion = true;
  40572. /**
  40573. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40574. * too much the area relying on ambient texture to define their ambient occlusion.
  40575. */
  40576. _this._useRadianceOcclusion = true;
  40577. /**
  40578. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40579. */
  40580. _this._useAlphaFromAlbedoTexture = false;
  40581. /**
  40582. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40583. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40584. */
  40585. _this._useSpecularOverAlpha = true;
  40586. /**
  40587. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40588. */
  40589. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40590. /**
  40591. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40592. */
  40593. _this._useRoughnessFromMetallicTextureAlpha = true;
  40594. /**
  40595. * Specifies if the metallic texture contains the roughness information in its green channel.
  40596. */
  40597. _this._useRoughnessFromMetallicTextureGreen = false;
  40598. /**
  40599. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40600. */
  40601. _this._useMetallnessFromMetallicTextureBlue = false;
  40602. /**
  40603. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40604. */
  40605. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40606. /**
  40607. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40608. */
  40609. _this._useAmbientInGrayScale = false;
  40610. /**
  40611. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40612. * The material will try to infer what glossiness each pixel should be.
  40613. */
  40614. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40615. /**
  40616. * BJS is using an harcoded light falloff based on a manually sets up range.
  40617. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40618. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40619. */
  40620. _this._usePhysicalLightFalloff = true;
  40621. /**
  40622. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40623. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40624. */
  40625. _this._useRadianceOverAlpha = true;
  40626. /**
  40627. * Allows using an object space normal map (instead of tangent space).
  40628. */
  40629. _this._useObjectSpaceNormalMap = false;
  40630. /**
  40631. * Allows using the bump map in parallax mode.
  40632. */
  40633. _this._useParallax = false;
  40634. /**
  40635. * Allows using the bump map in parallax occlusion mode.
  40636. */
  40637. _this._useParallaxOcclusion = false;
  40638. /**
  40639. * Controls the scale bias of the parallax mode.
  40640. */
  40641. _this._parallaxScaleBias = 0.05;
  40642. /**
  40643. * If sets to true, disables all the lights affecting the material.
  40644. */
  40645. _this._disableLighting = false;
  40646. /**
  40647. * Number of Simultaneous lights allowed on the material.
  40648. */
  40649. _this._maxSimultaneousLights = 4;
  40650. /**
  40651. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40652. */
  40653. _this._invertNormalMapX = false;
  40654. /**
  40655. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40656. */
  40657. _this._invertNormalMapY = false;
  40658. /**
  40659. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40660. */
  40661. _this._twoSidedLighting = false;
  40662. /**
  40663. * Defines the alpha limits in alpha test mode.
  40664. */
  40665. _this._alphaCutOff = 0.4;
  40666. /**
  40667. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40668. */
  40669. _this._forceAlphaTest = false;
  40670. /**
  40671. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40672. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40673. */
  40674. _this._useAlphaFresnel = false;
  40675. /**
  40676. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40677. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40678. */
  40679. _this._useLinearAlphaFresnel = false;
  40680. /**
  40681. * The transparency mode of the material.
  40682. */
  40683. _this._transparencyMode = null;
  40684. /**
  40685. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40686. * from cos thetav and roughness:
  40687. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40688. */
  40689. _this._environmentBRDFTexture = null;
  40690. /**
  40691. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40692. */
  40693. _this._forceIrradianceInFragment = false;
  40694. /**
  40695. * Force normal to face away from face.
  40696. */
  40697. _this._forceNormalForward = false;
  40698. /**
  40699. * Stores the available render targets.
  40700. */
  40701. _this._renderTargets = new BABYLON.SmartArray(16);
  40702. /**
  40703. * Sets the global ambient color for the material used in lighting calculations.
  40704. */
  40705. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40706. // Setup the default processing configuration to the scene.
  40707. _this._attachImageProcessingConfiguration(null);
  40708. _this.getRenderTargetTextures = function () {
  40709. _this._renderTargets.reset();
  40710. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40711. _this._renderTargets.push(_this._reflectionTexture);
  40712. }
  40713. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40714. _this._renderTargets.push(_this._refractionTexture);
  40715. }
  40716. return _this._renderTargets;
  40717. };
  40718. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40719. return _this;
  40720. }
  40721. /**
  40722. * Attaches a new image processing configuration to the PBR Material.
  40723. * @param configuration
  40724. */
  40725. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40726. var _this = this;
  40727. if (configuration === this._imageProcessingConfiguration) {
  40728. return;
  40729. }
  40730. // Detaches observer.
  40731. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40732. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40733. }
  40734. // Pick the scene configuration if needed.
  40735. if (!configuration) {
  40736. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40737. }
  40738. else {
  40739. this._imageProcessingConfiguration = configuration;
  40740. }
  40741. // Attaches observer.
  40742. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40743. _this._markAllSubMeshesAsImageProcessingDirty();
  40744. });
  40745. };
  40746. /**
  40747. * Gets the name of the material class.
  40748. */
  40749. PBRBaseMaterial.prototype.getClassName = function () {
  40750. return "PBRBaseMaterial";
  40751. };
  40752. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40753. /**
  40754. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40755. */
  40756. get: function () {
  40757. return this._useLogarithmicDepth;
  40758. },
  40759. /**
  40760. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40761. */
  40762. set: function (value) {
  40763. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40764. },
  40765. enumerable: true,
  40766. configurable: true
  40767. });
  40768. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40769. /**
  40770. * Gets the current transparency mode.
  40771. */
  40772. get: function () {
  40773. return this._transparencyMode;
  40774. },
  40775. /**
  40776. * Sets the transparency mode of the material.
  40777. */
  40778. set: function (value) {
  40779. if (this._transparencyMode === value) {
  40780. return;
  40781. }
  40782. this._transparencyMode = value;
  40783. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40784. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40785. },
  40786. enumerable: true,
  40787. configurable: true
  40788. });
  40789. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40790. /**
  40791. * Returns true if alpha blending should be disabled.
  40792. */
  40793. get: function () {
  40794. return (this._linkRefractionWithTransparency ||
  40795. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40796. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40797. },
  40798. enumerable: true,
  40799. configurable: true
  40800. });
  40801. /**
  40802. * Specifies whether or not this material should be rendered in alpha blend mode.
  40803. */
  40804. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40805. if (this._disableAlphaBlending) {
  40806. return false;
  40807. }
  40808. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40809. };
  40810. /**
  40811. * Specifies if the mesh will require alpha blending.
  40812. * @param mesh - BJS mesh.
  40813. */
  40814. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40815. if (this._disableAlphaBlending) {
  40816. return false;
  40817. }
  40818. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40819. };
  40820. /**
  40821. * Specifies whether or not this material should be rendered in alpha test mode.
  40822. */
  40823. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40824. if (this._forceAlphaTest) {
  40825. return true;
  40826. }
  40827. if (this._linkRefractionWithTransparency) {
  40828. return false;
  40829. }
  40830. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40831. };
  40832. /**
  40833. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40834. */
  40835. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40836. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40837. };
  40838. /**
  40839. * Gets the texture used for the alpha test.
  40840. */
  40841. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40842. return this._albedoTexture;
  40843. };
  40844. /**
  40845. * Specifies that the submesh is ready to be used.
  40846. * @param mesh - BJS mesh.
  40847. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40848. * @param useInstances - Specifies that instances should be used.
  40849. * @returns - boolean indicating that the submesh is ready or not.
  40850. */
  40851. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40852. if (subMesh.effect && this.isFrozen) {
  40853. if (this._wasPreviouslyReady) {
  40854. return true;
  40855. }
  40856. }
  40857. if (!subMesh._materialDefines) {
  40858. subMesh._materialDefines = new PBRMaterialDefines();
  40859. }
  40860. var defines = subMesh._materialDefines;
  40861. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40862. if (defines._renderId === this.getScene().getRenderId()) {
  40863. return true;
  40864. }
  40865. }
  40866. var scene = this.getScene();
  40867. var engine = scene.getEngine();
  40868. if (defines._areTexturesDirty) {
  40869. if (scene.texturesEnabled) {
  40870. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40871. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40872. return false;
  40873. }
  40874. }
  40875. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40876. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40877. return false;
  40878. }
  40879. }
  40880. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40881. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40882. return false;
  40883. }
  40884. }
  40885. var reflectionTexture = this._getReflectionTexture();
  40886. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40887. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40888. return false;
  40889. }
  40890. }
  40891. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40892. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40893. return false;
  40894. }
  40895. }
  40896. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40897. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40898. return false;
  40899. }
  40900. }
  40901. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40902. if (this._metallicTexture) {
  40903. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40904. return false;
  40905. }
  40906. }
  40907. else if (this._reflectivityTexture) {
  40908. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40909. return false;
  40910. }
  40911. }
  40912. if (this._microSurfaceTexture) {
  40913. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40914. return false;
  40915. }
  40916. }
  40917. }
  40918. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40919. // Bump texture cannot be not blocking.
  40920. if (!this._bumpTexture.isReady()) {
  40921. return false;
  40922. }
  40923. }
  40924. var refractionTexture = this._getRefractionTexture();
  40925. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40926. if (!refractionTexture.isReadyOrNotBlocking()) {
  40927. return false;
  40928. }
  40929. }
  40930. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40931. // This is blocking.
  40932. if (!this._environmentBRDFTexture.isReady()) {
  40933. return false;
  40934. }
  40935. }
  40936. }
  40937. }
  40938. if (defines._areImageProcessingDirty) {
  40939. if (!this._imageProcessingConfiguration.isReady()) {
  40940. return false;
  40941. }
  40942. }
  40943. if (!engine.getCaps().standardDerivatives) {
  40944. var bufferMesh = null;
  40945. if (mesh.getClassName() === "InstancedMesh") {
  40946. bufferMesh = mesh.sourceMesh;
  40947. }
  40948. else if (mesh.getClassName() === "Mesh") {
  40949. bufferMesh = mesh;
  40950. }
  40951. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40952. bufferMesh.createNormals(true);
  40953. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40954. }
  40955. }
  40956. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40957. if (effect) {
  40958. scene.resetCachedMaterial();
  40959. subMesh.setEffect(effect, defines);
  40960. this.buildUniformLayout();
  40961. }
  40962. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40963. return false;
  40964. }
  40965. defines._renderId = scene.getRenderId();
  40966. this._wasPreviouslyReady = true;
  40967. return true;
  40968. };
  40969. /**
  40970. * Specifies if the material uses metallic roughness workflow.
  40971. * @returns boolean specifiying if the material uses metallic roughness workflow.
  40972. */
  40973. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  40974. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  40975. return true;
  40976. }
  40977. return false;
  40978. };
  40979. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40980. if (onCompiled === void 0) { onCompiled = null; }
  40981. if (onError === void 0) { onError = null; }
  40982. if (useInstances === void 0) { useInstances = null; }
  40983. if (useClipPlane === void 0) { useClipPlane = null; }
  40984. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40985. if (!defines.isDirty) {
  40986. return null;
  40987. }
  40988. defines.markAsProcessed();
  40989. var scene = this.getScene();
  40990. var engine = scene.getEngine();
  40991. // Fallbacks
  40992. var fallbacks = new BABYLON.EffectFallbacks();
  40993. var fallbackRank = 0;
  40994. if (defines.USESPHERICALINVERTEX) {
  40995. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40996. }
  40997. if (defines.FOG) {
  40998. fallbacks.addFallback(fallbackRank, "FOG");
  40999. }
  41000. if (defines.POINTSIZE) {
  41001. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41002. }
  41003. if (defines.LOGARITHMICDEPTH) {
  41004. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41005. }
  41006. if (defines.PARALLAX) {
  41007. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41008. }
  41009. if (defines.PARALLAXOCCLUSION) {
  41010. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41011. }
  41012. if (defines.ENVIRONMENTBRDF) {
  41013. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41014. }
  41015. if (defines.TANGENT) {
  41016. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41017. }
  41018. if (defines.BUMP) {
  41019. fallbacks.addFallback(fallbackRank++, "BUMP");
  41020. }
  41021. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41022. if (defines.SPECULARTERM) {
  41023. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41024. }
  41025. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41026. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41027. }
  41028. if (defines.LIGHTMAP) {
  41029. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41030. }
  41031. if (defines.NORMAL) {
  41032. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41033. }
  41034. if (defines.AMBIENT) {
  41035. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41036. }
  41037. if (defines.EMISSIVE) {
  41038. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41039. }
  41040. if (defines.VERTEXCOLOR) {
  41041. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41042. }
  41043. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41044. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41045. }
  41046. if (defines.MORPHTARGETS) {
  41047. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41048. }
  41049. //Attributes
  41050. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41051. if (defines.NORMAL) {
  41052. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41053. }
  41054. if (defines.TANGENT) {
  41055. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41056. }
  41057. if (defines.UV1) {
  41058. attribs.push(BABYLON.VertexBuffer.UVKind);
  41059. }
  41060. if (defines.UV2) {
  41061. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41062. }
  41063. if (defines.VERTEXCOLOR) {
  41064. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41065. }
  41066. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41067. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41068. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41069. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41070. "vFogInfos", "vFogColor", "pointSize",
  41071. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41072. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41073. "mBones",
  41074. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41075. "vLightingIntensity",
  41076. "logarithmicDepthConstant",
  41077. "vSphericalX", "vSphericalY", "vSphericalZ",
  41078. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41079. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41080. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41081. "vTangentSpaceParams"
  41082. ];
  41083. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41084. "bumpSampler", "lightmapSampler", "opacitySampler",
  41085. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41086. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41087. "microSurfaceSampler", "environmentBrdfSampler"];
  41088. var uniformBuffers = ["Material", "Scene"];
  41089. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41090. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41091. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41092. uniformsNames: uniforms,
  41093. uniformBuffersNames: uniformBuffers,
  41094. samplers: samplers,
  41095. defines: defines,
  41096. maxSimultaneousLights: this._maxSimultaneousLights
  41097. });
  41098. var join = defines.toString();
  41099. return engine.createEffect("pbr", {
  41100. attributes: attribs,
  41101. uniformsNames: uniforms,
  41102. uniformBuffersNames: uniformBuffers,
  41103. samplers: samplers,
  41104. defines: join,
  41105. fallbacks: fallbacks,
  41106. onCompiled: onCompiled,
  41107. onError: onError,
  41108. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41109. }, engine);
  41110. };
  41111. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41112. if (useInstances === void 0) { useInstances = null; }
  41113. if (useClipPlane === void 0) { useClipPlane = null; }
  41114. var scene = this.getScene();
  41115. var engine = scene.getEngine();
  41116. // Lights
  41117. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41118. defines._needNormals = true;
  41119. // Textures
  41120. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41121. if (defines._areTexturesDirty) {
  41122. defines._needUVs = false;
  41123. if (scene.texturesEnabled) {
  41124. if (scene.getEngine().getCaps().textureLOD) {
  41125. defines.LODBASEDMICROSFURACE = true;
  41126. }
  41127. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41128. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41129. }
  41130. else {
  41131. defines.ALBEDO = false;
  41132. }
  41133. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41134. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41135. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41136. }
  41137. else {
  41138. defines.AMBIENT = false;
  41139. }
  41140. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41141. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41142. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41143. }
  41144. else {
  41145. defines.OPACITY = false;
  41146. }
  41147. var reflectionTexture = this._getReflectionTexture();
  41148. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41149. defines.REFLECTION = true;
  41150. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41151. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41152. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41153. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41154. defines.INVERTCUBICMAP = true;
  41155. }
  41156. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41157. switch (reflectionTexture.coordinatesMode) {
  41158. case BABYLON.Texture.CUBIC_MODE:
  41159. case BABYLON.Texture.INVCUBIC_MODE:
  41160. defines.REFLECTIONMAP_CUBIC = true;
  41161. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41162. break;
  41163. case BABYLON.Texture.EXPLICIT_MODE:
  41164. defines.REFLECTIONMAP_EXPLICIT = true;
  41165. break;
  41166. case BABYLON.Texture.PLANAR_MODE:
  41167. defines.REFLECTIONMAP_PLANAR = true;
  41168. break;
  41169. case BABYLON.Texture.PROJECTION_MODE:
  41170. defines.REFLECTIONMAP_PROJECTION = true;
  41171. break;
  41172. case BABYLON.Texture.SKYBOX_MODE:
  41173. defines.REFLECTIONMAP_SKYBOX = true;
  41174. break;
  41175. case BABYLON.Texture.SPHERICAL_MODE:
  41176. defines.REFLECTIONMAP_SPHERICAL = true;
  41177. break;
  41178. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41179. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41180. break;
  41181. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41182. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41183. break;
  41184. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41185. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41186. break;
  41187. }
  41188. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41189. if (reflectionTexture.sphericalPolynomial) {
  41190. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41191. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41192. defines.USESPHERICALINVERTEX = false;
  41193. }
  41194. else {
  41195. defines.USESPHERICALINVERTEX = true;
  41196. }
  41197. }
  41198. }
  41199. }
  41200. else {
  41201. defines.REFLECTION = false;
  41202. defines.REFLECTIONMAP_3D = false;
  41203. defines.REFLECTIONMAP_SPHERICAL = false;
  41204. defines.REFLECTIONMAP_PLANAR = false;
  41205. defines.REFLECTIONMAP_CUBIC = false;
  41206. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41207. defines.REFLECTIONMAP_PROJECTION = false;
  41208. defines.REFLECTIONMAP_SKYBOX = false;
  41209. defines.REFLECTIONMAP_EXPLICIT = false;
  41210. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41211. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41212. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41213. defines.INVERTCUBICMAP = false;
  41214. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41215. defines.USESPHERICALINVERTEX = false;
  41216. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41217. defines.LODINREFLECTIONALPHA = false;
  41218. defines.GAMMAREFLECTION = false;
  41219. }
  41220. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41221. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41222. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41223. }
  41224. else {
  41225. defines.LIGHTMAP = false;
  41226. }
  41227. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41228. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41229. }
  41230. else {
  41231. defines.EMISSIVE = false;
  41232. }
  41233. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41234. if (this._metallicTexture) {
  41235. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41236. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41237. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41238. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41239. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41240. }
  41241. else if (this._reflectivityTexture) {
  41242. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41243. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41244. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41245. }
  41246. else {
  41247. defines.REFLECTIVITY = false;
  41248. }
  41249. if (this._microSurfaceTexture) {
  41250. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41251. }
  41252. else {
  41253. defines.MICROSURFACEMAP = false;
  41254. }
  41255. }
  41256. else {
  41257. defines.REFLECTIVITY = false;
  41258. defines.MICROSURFACEMAP = false;
  41259. }
  41260. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41261. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41262. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41263. defines.PARALLAX = true;
  41264. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41265. }
  41266. else {
  41267. defines.PARALLAX = false;
  41268. }
  41269. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41270. }
  41271. else {
  41272. defines.BUMP = false;
  41273. }
  41274. var refractionTexture = this._getRefractionTexture();
  41275. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41276. defines.REFRACTION = true;
  41277. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41278. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41279. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41280. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41281. if (this._linkRefractionWithTransparency) {
  41282. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41283. }
  41284. }
  41285. else {
  41286. defines.REFRACTION = false;
  41287. }
  41288. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41289. defines.ENVIRONMENTBRDF = true;
  41290. }
  41291. else {
  41292. defines.ENVIRONMENTBRDF = false;
  41293. }
  41294. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41295. defines.ALPHAFROMALBEDO = true;
  41296. }
  41297. else {
  41298. defines.ALPHAFROMALBEDO = false;
  41299. }
  41300. }
  41301. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41302. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41303. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41304. if (!this.backFaceCulling && this._twoSidedLighting) {
  41305. defines.TWOSIDEDLIGHTING = true;
  41306. }
  41307. else {
  41308. defines.TWOSIDEDLIGHTING = false;
  41309. }
  41310. defines.ALPHATESTVALUE = this._alphaCutOff;
  41311. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41312. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41313. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41314. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41315. }
  41316. if (defines._areImageProcessingDirty) {
  41317. this._imageProcessingConfiguration.prepareDefines(defines);
  41318. }
  41319. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41320. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41321. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41322. // Misc.
  41323. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41324. // Values that need to be evaluated on every frame
  41325. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41326. // Attribs
  41327. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41328. };
  41329. /**
  41330. * Force shader compilation
  41331. */
  41332. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41333. var _this = this;
  41334. var localOptions = __assign({ clipPlane: false }, options);
  41335. var defines = new PBRMaterialDefines();
  41336. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41337. if (effect.isReady()) {
  41338. if (onCompiled) {
  41339. onCompiled(this);
  41340. }
  41341. }
  41342. else {
  41343. effect.onCompileObservable.add(function () {
  41344. if (onCompiled) {
  41345. onCompiled(_this);
  41346. }
  41347. });
  41348. }
  41349. };
  41350. /**
  41351. * Initializes the uniform buffer layout for the shader.
  41352. */
  41353. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41354. // Order is important !
  41355. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41356. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41357. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41358. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41359. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41360. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41361. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41362. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41363. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41364. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41365. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41366. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41367. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41368. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41369. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41370. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41371. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41372. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41373. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41374. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41375. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41376. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41377. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41378. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41379. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41380. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41381. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41382. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41383. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41384. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41385. this._uniformBuffer.addUniform("pointSize", 1);
  41386. this._uniformBuffer.create();
  41387. };
  41388. /**
  41389. * Unbinds the textures.
  41390. */
  41391. PBRBaseMaterial.prototype.unbind = function () {
  41392. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41393. this._uniformBuffer.setTexture("reflectionSampler", null);
  41394. }
  41395. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41396. this._uniformBuffer.setTexture("refractionSampler", null);
  41397. }
  41398. _super.prototype.unbind.call(this);
  41399. };
  41400. /**
  41401. * Binds the submesh data.
  41402. * @param world - The world matrix.
  41403. * @param mesh - The BJS mesh.
  41404. * @param subMesh - A submesh of the BJS mesh.
  41405. */
  41406. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41407. var scene = this.getScene();
  41408. var defines = subMesh._materialDefines;
  41409. if (!defines) {
  41410. return;
  41411. }
  41412. var effect = subMesh.effect;
  41413. if (!effect) {
  41414. return;
  41415. }
  41416. this._activeEffect = effect;
  41417. // Matrices
  41418. this.bindOnlyWorldMatrix(world);
  41419. // Normal Matrix
  41420. if (defines.OBJECTSPACE_NORMALMAP) {
  41421. world.toNormalMatrix(this._normalMatrix);
  41422. this.bindOnlyNormalMatrix(this._normalMatrix);
  41423. }
  41424. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41425. // Bones
  41426. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41427. var reflectionTexture = null;
  41428. if (mustRebind) {
  41429. this._uniformBuffer.bindToEffect(effect, "Material");
  41430. this.bindViewProjection(effect);
  41431. reflectionTexture = this._getReflectionTexture();
  41432. var refractionTexture = this._getRefractionTexture();
  41433. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41434. // Texture uniforms
  41435. if (scene.texturesEnabled) {
  41436. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41437. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41438. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41439. }
  41440. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41441. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41442. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41443. }
  41444. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41445. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41446. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41447. }
  41448. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41449. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41450. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41451. if (reflectionTexture.boundingBoxSize) {
  41452. var cubeTexture = reflectionTexture;
  41453. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41454. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41455. }
  41456. var polynomials = reflectionTexture.sphericalPolynomial;
  41457. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41458. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41459. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41460. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41461. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41462. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41463. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41464. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41465. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41466. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41467. }
  41468. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41469. }
  41470. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41471. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41472. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41473. }
  41474. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41475. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41476. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41477. }
  41478. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41479. if (this._metallicTexture) {
  41480. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41481. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41482. }
  41483. else if (this._reflectivityTexture) {
  41484. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41485. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41486. }
  41487. if (this._microSurfaceTexture) {
  41488. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41489. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41490. }
  41491. }
  41492. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41493. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41494. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41495. if (scene._mirroredCameraPosition) {
  41496. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41497. }
  41498. else {
  41499. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41500. }
  41501. }
  41502. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41503. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41504. var depth = 1.0;
  41505. if (!refractionTexture.isCube) {
  41506. if (refractionTexture.depth) {
  41507. depth = refractionTexture.depth;
  41508. }
  41509. }
  41510. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41511. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41512. }
  41513. }
  41514. // Point size
  41515. if (this.pointsCloud) {
  41516. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41517. }
  41518. // Colors
  41519. if (defines.METALLICWORKFLOW) {
  41520. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41521. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41522. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41523. }
  41524. else {
  41525. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41526. }
  41527. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41528. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41529. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41530. // Misc
  41531. this._lightingInfos.x = this._directIntensity;
  41532. this._lightingInfos.y = this._emissiveIntensity;
  41533. this._lightingInfos.z = this._environmentIntensity;
  41534. this._lightingInfos.w = this._specularIntensity;
  41535. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41536. }
  41537. // Textures
  41538. if (scene.texturesEnabled) {
  41539. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41540. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41541. }
  41542. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41543. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41544. }
  41545. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41546. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41547. }
  41548. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41549. if (defines.LODBASEDMICROSFURACE) {
  41550. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41551. }
  41552. else {
  41553. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41554. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41555. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41556. }
  41557. }
  41558. if (defines.ENVIRONMENTBRDF) {
  41559. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41560. }
  41561. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41562. if (defines.LODBASEDMICROSFURACE) {
  41563. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41564. }
  41565. else {
  41566. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41567. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41568. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41569. }
  41570. }
  41571. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41572. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41573. }
  41574. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41575. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41576. }
  41577. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41578. if (this._metallicTexture) {
  41579. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41580. }
  41581. else if (this._reflectivityTexture) {
  41582. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41583. }
  41584. if (this._microSurfaceTexture) {
  41585. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41586. }
  41587. }
  41588. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41589. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41590. }
  41591. }
  41592. // Clip plane
  41593. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41594. // Colors
  41595. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41596. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41597. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41598. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41599. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41600. }
  41601. if (mustRebind || !this.isFrozen) {
  41602. // Lights
  41603. if (scene.lightsEnabled && !this._disableLighting) {
  41604. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41605. }
  41606. // View
  41607. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41608. this.bindView(effect);
  41609. }
  41610. // Fog
  41611. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41612. // Morph targets
  41613. if (defines.NUM_MORPH_INFLUENCERS) {
  41614. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41615. }
  41616. // image processing
  41617. this._imageProcessingConfiguration.bind(this._activeEffect);
  41618. // Log. depth
  41619. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41620. }
  41621. this._uniformBuffer.update();
  41622. this._afterBind(mesh);
  41623. };
  41624. /**
  41625. * Returns the animatable textures.
  41626. * @returns - Array of animatable textures.
  41627. */
  41628. PBRBaseMaterial.prototype.getAnimatables = function () {
  41629. var results = [];
  41630. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41631. results.push(this._albedoTexture);
  41632. }
  41633. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41634. results.push(this._ambientTexture);
  41635. }
  41636. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41637. results.push(this._opacityTexture);
  41638. }
  41639. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41640. results.push(this._reflectionTexture);
  41641. }
  41642. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41643. results.push(this._emissiveTexture);
  41644. }
  41645. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41646. results.push(this._metallicTexture);
  41647. }
  41648. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41649. results.push(this._reflectivityTexture);
  41650. }
  41651. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41652. results.push(this._bumpTexture);
  41653. }
  41654. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41655. results.push(this._lightmapTexture);
  41656. }
  41657. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41658. results.push(this._refractionTexture);
  41659. }
  41660. return results;
  41661. };
  41662. /**
  41663. * Returns the texture used for reflections.
  41664. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41665. */
  41666. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41667. if (this._reflectionTexture) {
  41668. return this._reflectionTexture;
  41669. }
  41670. return this.getScene().environmentTexture;
  41671. };
  41672. /**
  41673. * Returns the texture used for refraction or null if none is used.
  41674. * @returns - Refection texture if present. If no refraction texture and refraction
  41675. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41676. */
  41677. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41678. if (this._refractionTexture) {
  41679. return this._refractionTexture;
  41680. }
  41681. if (this._linkRefractionWithTransparency) {
  41682. return this.getScene().environmentTexture;
  41683. }
  41684. return null;
  41685. };
  41686. /**
  41687. * Disposes the resources of the material.
  41688. * @param forceDisposeEffect - Forces the disposal of effects.
  41689. * @param forceDisposeTextures - Forces the disposal of all textures.
  41690. */
  41691. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41692. if (forceDisposeTextures) {
  41693. if (this._albedoTexture) {
  41694. this._albedoTexture.dispose();
  41695. }
  41696. if (this._ambientTexture) {
  41697. this._ambientTexture.dispose();
  41698. }
  41699. if (this._opacityTexture) {
  41700. this._opacityTexture.dispose();
  41701. }
  41702. if (this._reflectionTexture) {
  41703. this._reflectionTexture.dispose();
  41704. }
  41705. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41706. this._environmentBRDFTexture.dispose();
  41707. }
  41708. if (this._emissiveTexture) {
  41709. this._emissiveTexture.dispose();
  41710. }
  41711. if (this._metallicTexture) {
  41712. this._metallicTexture.dispose();
  41713. }
  41714. if (this._reflectivityTexture) {
  41715. this._reflectivityTexture.dispose();
  41716. }
  41717. if (this._bumpTexture) {
  41718. this._bumpTexture.dispose();
  41719. }
  41720. if (this._lightmapTexture) {
  41721. this._lightmapTexture.dispose();
  41722. }
  41723. if (this._refractionTexture) {
  41724. this._refractionTexture.dispose();
  41725. }
  41726. }
  41727. this._renderTargets.dispose();
  41728. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41729. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41730. }
  41731. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41732. };
  41733. /**
  41734. * Stores the reflectivity values based on metallic roughness workflow.
  41735. */
  41736. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41737. __decorate([
  41738. BABYLON.serializeAsImageProcessingConfiguration()
  41739. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41740. __decorate([
  41741. BABYLON.serialize()
  41742. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41743. __decorate([
  41744. BABYLON.serialize()
  41745. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41746. return PBRBaseMaterial;
  41747. }(BABYLON.PushMaterial));
  41748. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41749. })(BABYLON || (BABYLON = {}));
  41750. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41751. var BABYLON;
  41752. (function (BABYLON) {
  41753. /**
  41754. * The Physically based simple base material of BJS.
  41755. *
  41756. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41757. * It is used as the base class for both the specGloss and metalRough conventions.
  41758. */
  41759. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41760. __extends(PBRBaseSimpleMaterial, _super);
  41761. /**
  41762. * Instantiates a new PBRMaterial instance.
  41763. *
  41764. * @param name The material name
  41765. * @param scene The scene the material will be use in.
  41766. */
  41767. function PBRBaseSimpleMaterial(name, scene) {
  41768. var _this = _super.call(this, name, scene) || this;
  41769. /**
  41770. * Number of Simultaneous lights allowed on the material.
  41771. */
  41772. _this.maxSimultaneousLights = 4;
  41773. /**
  41774. * If sets to true, disables all the lights affecting the material.
  41775. */
  41776. _this.disableLighting = false;
  41777. /**
  41778. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41779. */
  41780. _this.invertNormalMapX = false;
  41781. /**
  41782. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41783. */
  41784. _this.invertNormalMapY = false;
  41785. /**
  41786. * Emissivie color used to self-illuminate the model.
  41787. */
  41788. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41789. /**
  41790. * Occlusion Channel Strenght.
  41791. */
  41792. _this.occlusionStrength = 1.0;
  41793. _this.useLightmapAsShadowmap = false;
  41794. _this._useAlphaFromAlbedoTexture = true;
  41795. _this._useAmbientInGrayScale = true;
  41796. return _this;
  41797. }
  41798. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41799. /**
  41800. * Gets the current double sided mode.
  41801. */
  41802. get: function () {
  41803. return this._twoSidedLighting;
  41804. },
  41805. /**
  41806. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41807. */
  41808. set: function (value) {
  41809. if (this._twoSidedLighting === value) {
  41810. return;
  41811. }
  41812. this._twoSidedLighting = value;
  41813. this.backFaceCulling = !value;
  41814. this._markAllSubMeshesAsTexturesDirty();
  41815. },
  41816. enumerable: true,
  41817. configurable: true
  41818. });
  41819. /**
  41820. * Return the active textures of the material.
  41821. */
  41822. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41823. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41824. if (this.environmentTexture) {
  41825. activeTextures.push(this.environmentTexture);
  41826. }
  41827. if (this.normalTexture) {
  41828. activeTextures.push(this.normalTexture);
  41829. }
  41830. if (this.emissiveTexture) {
  41831. activeTextures.push(this.emissiveTexture);
  41832. }
  41833. if (this.occlusionTexture) {
  41834. activeTextures.push(this.occlusionTexture);
  41835. }
  41836. if (this.lightmapTexture) {
  41837. activeTextures.push(this.lightmapTexture);
  41838. }
  41839. return activeTextures;
  41840. };
  41841. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41842. if (_super.prototype.hasTexture.call(this, texture)) {
  41843. return true;
  41844. }
  41845. if (this.lightmapTexture === texture) {
  41846. return true;
  41847. }
  41848. return false;
  41849. };
  41850. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41851. return "PBRBaseSimpleMaterial";
  41852. };
  41853. __decorate([
  41854. BABYLON.serialize(),
  41855. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41856. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41857. __decorate([
  41858. BABYLON.serialize(),
  41859. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41860. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41861. __decorate([
  41862. BABYLON.serializeAsTexture(),
  41863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41864. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41865. __decorate([
  41866. BABYLON.serialize(),
  41867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41868. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41869. __decorate([
  41870. BABYLON.serialize(),
  41871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41872. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41873. __decorate([
  41874. BABYLON.serializeAsTexture(),
  41875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41876. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41877. __decorate([
  41878. BABYLON.serializeAsColor3("emissive"),
  41879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41880. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41881. __decorate([
  41882. BABYLON.serializeAsTexture(),
  41883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41884. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41885. __decorate([
  41886. BABYLON.serialize(),
  41887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41888. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41889. __decorate([
  41890. BABYLON.serializeAsTexture(),
  41891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41892. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41893. __decorate([
  41894. BABYLON.serialize(),
  41895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41896. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41897. __decorate([
  41898. BABYLON.serialize()
  41899. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41900. __decorate([
  41901. BABYLON.serializeAsTexture(),
  41902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41903. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41904. __decorate([
  41905. BABYLON.serialize(),
  41906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41907. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41908. return PBRBaseSimpleMaterial;
  41909. }(BABYLON.PBRBaseMaterial));
  41910. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41911. })(BABYLON || (BABYLON = {}));
  41912. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41913. var BABYLON;
  41914. (function (BABYLON) {
  41915. /**
  41916. * The Physically based material of BJS.
  41917. *
  41918. * This offers the main features of a standard PBR material.
  41919. * For more information, please refer to the documentation :
  41920. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41921. */
  41922. var PBRMaterial = /** @class */ (function (_super) {
  41923. __extends(PBRMaterial, _super);
  41924. /**
  41925. * Instantiates a new PBRMaterial instance.
  41926. *
  41927. * @param name The material name
  41928. * @param scene The scene the material will be use in.
  41929. */
  41930. function PBRMaterial(name, scene) {
  41931. var _this = _super.call(this, name, scene) || this;
  41932. /**
  41933. * Intensity of the direct lights e.g. the four lights available in your scene.
  41934. * This impacts both the direct diffuse and specular highlights.
  41935. */
  41936. _this.directIntensity = 1.0;
  41937. /**
  41938. * Intensity of the emissive part of the material.
  41939. * This helps controlling the emissive effect without modifying the emissive color.
  41940. */
  41941. _this.emissiveIntensity = 1.0;
  41942. /**
  41943. * Intensity of the environment e.g. how much the environment will light the object
  41944. * either through harmonics for rough material or through the refelction for shiny ones.
  41945. */
  41946. _this.environmentIntensity = 1.0;
  41947. /**
  41948. * This is a special control allowing the reduction of the specular highlights coming from the
  41949. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41950. */
  41951. _this.specularIntensity = 1.0;
  41952. /**
  41953. * Debug Control allowing disabling the bump map on this material.
  41954. */
  41955. _this.disableBumpMap = false;
  41956. /**
  41957. * AKA Occlusion Texture Intensity in other nomenclature.
  41958. */
  41959. _this.ambientTextureStrength = 1.0;
  41960. /**
  41961. * The color of a material in ambient lighting.
  41962. */
  41963. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41964. /**
  41965. * AKA Diffuse Color in other nomenclature.
  41966. */
  41967. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41968. /**
  41969. * AKA Specular Color in other nomenclature.
  41970. */
  41971. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41972. /**
  41973. * The color reflected from the material.
  41974. */
  41975. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41976. /**
  41977. * The color emitted from the material.
  41978. */
  41979. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41980. /**
  41981. * AKA Glossiness in other nomenclature.
  41982. */
  41983. _this.microSurface = 1.0;
  41984. /**
  41985. * source material index of refraction (IOR)' / 'destination material IOR.
  41986. */
  41987. _this.indexOfRefraction = 0.66;
  41988. /**
  41989. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41990. */
  41991. _this.invertRefractionY = false;
  41992. /**
  41993. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41994. * Materials half opaque for instance using refraction could benefit from this control.
  41995. */
  41996. _this.linkRefractionWithTransparency = false;
  41997. _this.useLightmapAsShadowmap = false;
  41998. /**
  41999. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42000. */
  42001. _this.useAlphaFromAlbedoTexture = false;
  42002. /**
  42003. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42004. */
  42005. _this.forceAlphaTest = false;
  42006. /**
  42007. * Defines the alpha limits in alpha test mode.
  42008. */
  42009. _this.alphaCutOff = 0.4;
  42010. /**
  42011. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42012. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42013. */
  42014. _this.useSpecularOverAlpha = true;
  42015. /**
  42016. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42017. */
  42018. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42019. /**
  42020. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42021. */
  42022. _this.useRoughnessFromMetallicTextureAlpha = true;
  42023. /**
  42024. * Specifies if the metallic texture contains the roughness information in its green channel.
  42025. */
  42026. _this.useRoughnessFromMetallicTextureGreen = false;
  42027. /**
  42028. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42029. */
  42030. _this.useMetallnessFromMetallicTextureBlue = false;
  42031. /**
  42032. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42033. */
  42034. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42035. /**
  42036. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42037. */
  42038. _this.useAmbientInGrayScale = false;
  42039. /**
  42040. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42041. * The material will try to infer what glossiness each pixel should be.
  42042. */
  42043. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42044. /**
  42045. * BJS is using an harcoded light falloff based on a manually sets up range.
  42046. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42047. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42048. */
  42049. _this.usePhysicalLightFalloff = true;
  42050. /**
  42051. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42052. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42053. */
  42054. _this.useRadianceOverAlpha = true;
  42055. /**
  42056. * Allows using an object space normal map (instead of tangent space).
  42057. */
  42058. _this.useObjectSpaceNormalMap = false;
  42059. /**
  42060. * Allows using the bump map in parallax mode.
  42061. */
  42062. _this.useParallax = false;
  42063. /**
  42064. * Allows using the bump map in parallax occlusion mode.
  42065. */
  42066. _this.useParallaxOcclusion = false;
  42067. /**
  42068. * Controls the scale bias of the parallax mode.
  42069. */
  42070. _this.parallaxScaleBias = 0.05;
  42071. /**
  42072. * If sets to true, disables all the lights affecting the material.
  42073. */
  42074. _this.disableLighting = false;
  42075. /**
  42076. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42077. */
  42078. _this.forceIrradianceInFragment = false;
  42079. /**
  42080. * Number of Simultaneous lights allowed on the material.
  42081. */
  42082. _this.maxSimultaneousLights = 4;
  42083. /**
  42084. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42085. */
  42086. _this.invertNormalMapX = false;
  42087. /**
  42088. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42089. */
  42090. _this.invertNormalMapY = false;
  42091. /**
  42092. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42093. */
  42094. _this.twoSidedLighting = false;
  42095. /**
  42096. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42097. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42098. */
  42099. _this.useAlphaFresnel = false;
  42100. /**
  42101. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42102. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42103. */
  42104. _this.useLinearAlphaFresnel = false;
  42105. /**
  42106. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42107. * And/Or occlude the blended part.
  42108. */
  42109. _this.environmentBRDFTexture = null;
  42110. /**
  42111. * Force normal to face away from face.
  42112. */
  42113. _this.forceNormalForward = false;
  42114. /**
  42115. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42116. * makes the reflect vector face the model (under horizon).
  42117. */
  42118. _this.useHorizonOcclusion = true;
  42119. /**
  42120. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42121. * too much the area relying on ambient texture to define their ambient occlusion.
  42122. */
  42123. _this.useRadianceOcclusion = true;
  42124. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42125. return _this;
  42126. }
  42127. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42128. /**
  42129. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42130. */
  42131. get: function () {
  42132. return this._PBRMATERIAL_OPAQUE;
  42133. },
  42134. enumerable: true,
  42135. configurable: true
  42136. });
  42137. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42138. /**
  42139. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42140. */
  42141. get: function () {
  42142. return this._PBRMATERIAL_ALPHATEST;
  42143. },
  42144. enumerable: true,
  42145. configurable: true
  42146. });
  42147. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42148. /**
  42149. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42150. */
  42151. get: function () {
  42152. return this._PBRMATERIAL_ALPHABLEND;
  42153. },
  42154. enumerable: true,
  42155. configurable: true
  42156. });
  42157. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42158. /**
  42159. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42160. * They are also discarded below the alpha cutoff threshold to improve performances.
  42161. */
  42162. get: function () {
  42163. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42164. },
  42165. enumerable: true,
  42166. configurable: true
  42167. });
  42168. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42169. /**
  42170. * Gets the image processing configuration used either in this material.
  42171. */
  42172. get: function () {
  42173. return this._imageProcessingConfiguration;
  42174. },
  42175. /**
  42176. * Sets the Default image processing configuration used either in the this material.
  42177. *
  42178. * If sets to null, the scene one is in use.
  42179. */
  42180. set: function (value) {
  42181. this._attachImageProcessingConfiguration(value);
  42182. // Ensure the effect will be rebuilt.
  42183. this._markAllSubMeshesAsTexturesDirty();
  42184. },
  42185. enumerable: true,
  42186. configurable: true
  42187. });
  42188. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42189. /**
  42190. * Gets wether the color curves effect is enabled.
  42191. */
  42192. get: function () {
  42193. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42194. },
  42195. /**
  42196. * Sets wether the color curves effect is enabled.
  42197. */
  42198. set: function (value) {
  42199. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42200. },
  42201. enumerable: true,
  42202. configurable: true
  42203. });
  42204. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42205. /**
  42206. * Gets wether the color grading effect is enabled.
  42207. */
  42208. get: function () {
  42209. return this.imageProcessingConfiguration.colorGradingEnabled;
  42210. },
  42211. /**
  42212. * Gets wether the color grading effect is enabled.
  42213. */
  42214. set: function (value) {
  42215. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42216. },
  42217. enumerable: true,
  42218. configurable: true
  42219. });
  42220. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42221. /**
  42222. * Gets wether tonemapping is enabled or not.
  42223. */
  42224. get: function () {
  42225. return this._imageProcessingConfiguration.toneMappingEnabled;
  42226. },
  42227. /**
  42228. * Sets wether tonemapping is enabled or not
  42229. */
  42230. set: function (value) {
  42231. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42232. },
  42233. enumerable: true,
  42234. configurable: true
  42235. });
  42236. ;
  42237. ;
  42238. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42239. /**
  42240. * The camera exposure used on this material.
  42241. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42242. * This corresponds to a photographic exposure.
  42243. */
  42244. get: function () {
  42245. return this._imageProcessingConfiguration.exposure;
  42246. },
  42247. /**
  42248. * The camera exposure used on this material.
  42249. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42250. * This corresponds to a photographic exposure.
  42251. */
  42252. set: function (value) {
  42253. this._imageProcessingConfiguration.exposure = value;
  42254. },
  42255. enumerable: true,
  42256. configurable: true
  42257. });
  42258. ;
  42259. ;
  42260. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42261. /**
  42262. * Gets The camera contrast used on this material.
  42263. */
  42264. get: function () {
  42265. return this._imageProcessingConfiguration.contrast;
  42266. },
  42267. /**
  42268. * Sets The camera contrast used on this material.
  42269. */
  42270. set: function (value) {
  42271. this._imageProcessingConfiguration.contrast = value;
  42272. },
  42273. enumerable: true,
  42274. configurable: true
  42275. });
  42276. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42277. /**
  42278. * Gets the Color Grading 2D Lookup Texture.
  42279. */
  42280. get: function () {
  42281. return this._imageProcessingConfiguration.colorGradingTexture;
  42282. },
  42283. /**
  42284. * Sets the Color Grading 2D Lookup Texture.
  42285. */
  42286. set: function (value) {
  42287. this._imageProcessingConfiguration.colorGradingTexture = value;
  42288. },
  42289. enumerable: true,
  42290. configurable: true
  42291. });
  42292. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42293. /**
  42294. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42295. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42296. * 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;
  42297. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42298. */
  42299. get: function () {
  42300. return this._imageProcessingConfiguration.colorCurves;
  42301. },
  42302. /**
  42303. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42304. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42305. * 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;
  42306. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42307. */
  42308. set: function (value) {
  42309. this._imageProcessingConfiguration.colorCurves = value;
  42310. },
  42311. enumerable: true,
  42312. configurable: true
  42313. });
  42314. /**
  42315. * Returns the name of this material class.
  42316. */
  42317. PBRMaterial.prototype.getClassName = function () {
  42318. return "PBRMaterial";
  42319. };
  42320. /**
  42321. * Returns an array of the actively used textures.
  42322. * @returns - Array of BaseTextures
  42323. */
  42324. PBRMaterial.prototype.getActiveTextures = function () {
  42325. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42326. if (this._albedoTexture) {
  42327. activeTextures.push(this._albedoTexture);
  42328. }
  42329. if (this._ambientTexture) {
  42330. activeTextures.push(this._ambientTexture);
  42331. }
  42332. if (this._opacityTexture) {
  42333. activeTextures.push(this._opacityTexture);
  42334. }
  42335. if (this._reflectionTexture) {
  42336. activeTextures.push(this._reflectionTexture);
  42337. }
  42338. if (this._emissiveTexture) {
  42339. activeTextures.push(this._emissiveTexture);
  42340. }
  42341. if (this._reflectivityTexture) {
  42342. activeTextures.push(this._reflectivityTexture);
  42343. }
  42344. if (this._metallicTexture) {
  42345. activeTextures.push(this._metallicTexture);
  42346. }
  42347. if (this._microSurfaceTexture) {
  42348. activeTextures.push(this._microSurfaceTexture);
  42349. }
  42350. if (this._bumpTexture) {
  42351. activeTextures.push(this._bumpTexture);
  42352. }
  42353. if (this._lightmapTexture) {
  42354. activeTextures.push(this._lightmapTexture);
  42355. }
  42356. if (this._refractionTexture) {
  42357. activeTextures.push(this._refractionTexture);
  42358. }
  42359. return activeTextures;
  42360. };
  42361. /**
  42362. * Checks to see if a texture is used in the material.
  42363. * @param texture - Base texture to use.
  42364. * @returns - Boolean specifying if a texture is used in the material.
  42365. */
  42366. PBRMaterial.prototype.hasTexture = function (texture) {
  42367. if (_super.prototype.hasTexture.call(this, texture)) {
  42368. return true;
  42369. }
  42370. if (this._albedoTexture === texture) {
  42371. return true;
  42372. }
  42373. if (this._ambientTexture === texture) {
  42374. return true;
  42375. }
  42376. if (this._opacityTexture === texture) {
  42377. return true;
  42378. }
  42379. if (this._reflectionTexture === texture) {
  42380. return true;
  42381. }
  42382. if (this._reflectivityTexture === texture) {
  42383. return true;
  42384. }
  42385. if (this._metallicTexture === texture) {
  42386. return true;
  42387. }
  42388. if (this._microSurfaceTexture === texture) {
  42389. return true;
  42390. }
  42391. if (this._bumpTexture === texture) {
  42392. return true;
  42393. }
  42394. if (this._lightmapTexture === texture) {
  42395. return true;
  42396. }
  42397. if (this._refractionTexture === texture) {
  42398. return true;
  42399. }
  42400. return false;
  42401. };
  42402. /**
  42403. * Makes a duplicate of the current material.
  42404. * @param name - name to use for the new material.
  42405. */
  42406. PBRMaterial.prototype.clone = function (name) {
  42407. var _this = this;
  42408. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42409. clone.id = name;
  42410. clone.name = name;
  42411. return clone;
  42412. };
  42413. /**
  42414. * Serializes this PBR Material.
  42415. * @returns - An object with the serialized material.
  42416. */
  42417. PBRMaterial.prototype.serialize = function () {
  42418. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42419. serializationObject.customType = "BABYLON.PBRMaterial";
  42420. return serializationObject;
  42421. };
  42422. // Statics
  42423. /**
  42424. * Parses a PBR Material from a serialized object.
  42425. * @param source - Serialized object.
  42426. * @param scene - BJS scene instance.
  42427. * @param rootUrl - url for the scene object
  42428. * @returns - PBRMaterial
  42429. */
  42430. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42431. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42432. };
  42433. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42434. /**
  42435. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42436. */
  42437. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42438. /**
  42439. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42440. */
  42441. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42442. /**
  42443. * 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.
  42444. * They are also discarded below the alpha cutoff threshold to improve performances.
  42445. */
  42446. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42447. __decorate([
  42448. BABYLON.serialize(),
  42449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42450. ], PBRMaterial.prototype, "directIntensity", void 0);
  42451. __decorate([
  42452. BABYLON.serialize(),
  42453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42454. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42455. __decorate([
  42456. BABYLON.serialize(),
  42457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42458. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42459. __decorate([
  42460. BABYLON.serialize(),
  42461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42462. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42463. __decorate([
  42464. BABYLON.serialize(),
  42465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42466. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42467. __decorate([
  42468. BABYLON.serializeAsTexture(),
  42469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42470. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42471. __decorate([
  42472. BABYLON.serializeAsTexture(),
  42473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42474. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42475. __decorate([
  42476. BABYLON.serialize(),
  42477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42478. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42479. __decorate([
  42480. BABYLON.serializeAsTexture(),
  42481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42482. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42483. __decorate([
  42484. BABYLON.serializeAsTexture(),
  42485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42486. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42487. __decorate([
  42488. BABYLON.serializeAsTexture(),
  42489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42490. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42491. __decorate([
  42492. BABYLON.serializeAsTexture(),
  42493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42494. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42495. __decorate([
  42496. BABYLON.serializeAsTexture(),
  42497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42498. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42499. __decorate([
  42500. BABYLON.serialize(),
  42501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42502. ], PBRMaterial.prototype, "metallic", void 0);
  42503. __decorate([
  42504. BABYLON.serialize(),
  42505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42506. ], PBRMaterial.prototype, "roughness", void 0);
  42507. __decorate([
  42508. BABYLON.serializeAsTexture(),
  42509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42510. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42511. __decorate([
  42512. BABYLON.serializeAsTexture(),
  42513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42514. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42515. __decorate([
  42516. BABYLON.serializeAsTexture(),
  42517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42518. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42519. __decorate([
  42520. BABYLON.serializeAsTexture(),
  42521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42522. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42523. __decorate([
  42524. BABYLON.serializeAsColor3("ambient"),
  42525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42526. ], PBRMaterial.prototype, "ambientColor", void 0);
  42527. __decorate([
  42528. BABYLON.serializeAsColor3("albedo"),
  42529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42530. ], PBRMaterial.prototype, "albedoColor", void 0);
  42531. __decorate([
  42532. BABYLON.serializeAsColor3("reflectivity"),
  42533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42534. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42535. __decorate([
  42536. BABYLON.serializeAsColor3("reflection"),
  42537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42538. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42539. __decorate([
  42540. BABYLON.serializeAsColor3("emissive"),
  42541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42542. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42543. __decorate([
  42544. BABYLON.serialize(),
  42545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42546. ], PBRMaterial.prototype, "microSurface", void 0);
  42547. __decorate([
  42548. BABYLON.serialize(),
  42549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42550. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42551. __decorate([
  42552. BABYLON.serialize(),
  42553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42554. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42555. __decorate([
  42556. BABYLON.serialize(),
  42557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42558. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42559. __decorate([
  42560. BABYLON.serialize(),
  42561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42562. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42563. __decorate([
  42564. BABYLON.serialize(),
  42565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42566. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42567. __decorate([
  42568. BABYLON.serialize(),
  42569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42570. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42571. __decorate([
  42572. BABYLON.serialize(),
  42573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42574. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42575. __decorate([
  42576. BABYLON.serialize(),
  42577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42578. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42579. __decorate([
  42580. BABYLON.serialize(),
  42581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42582. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42583. __decorate([
  42584. BABYLON.serialize(),
  42585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42586. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42587. __decorate([
  42588. BABYLON.serialize(),
  42589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42590. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42591. __decorate([
  42592. BABYLON.serialize(),
  42593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42594. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42595. __decorate([
  42596. BABYLON.serialize(),
  42597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42598. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42599. __decorate([
  42600. BABYLON.serialize(),
  42601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42602. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42603. __decorate([
  42604. BABYLON.serialize(),
  42605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42606. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42607. __decorate([
  42608. BABYLON.serialize(),
  42609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42610. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42611. __decorate([
  42612. BABYLON.serialize(),
  42613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42614. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42615. __decorate([
  42616. BABYLON.serialize(),
  42617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42618. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42619. __decorate([
  42620. BABYLON.serialize(),
  42621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42622. ], PBRMaterial.prototype, "useParallax", void 0);
  42623. __decorate([
  42624. BABYLON.serialize(),
  42625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42626. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42627. __decorate([
  42628. BABYLON.serialize(),
  42629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42630. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42631. __decorate([
  42632. BABYLON.serialize(),
  42633. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42634. ], PBRMaterial.prototype, "disableLighting", void 0);
  42635. __decorate([
  42636. BABYLON.serialize(),
  42637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42638. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42639. __decorate([
  42640. BABYLON.serialize(),
  42641. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42642. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42643. __decorate([
  42644. BABYLON.serialize(),
  42645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42646. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42647. __decorate([
  42648. BABYLON.serialize(),
  42649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42650. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42651. __decorate([
  42652. BABYLON.serialize(),
  42653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42654. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42655. __decorate([
  42656. BABYLON.serialize(),
  42657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42658. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42659. __decorate([
  42660. BABYLON.serialize(),
  42661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42662. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42663. __decorate([
  42664. BABYLON.serializeAsTexture(),
  42665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42666. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42667. __decorate([
  42668. BABYLON.serialize(),
  42669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42670. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42671. __decorate([
  42672. BABYLON.serialize(),
  42673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42674. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42675. __decorate([
  42676. BABYLON.serialize(),
  42677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42678. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42679. return PBRMaterial;
  42680. }(BABYLON.PBRBaseMaterial));
  42681. BABYLON.PBRMaterial = PBRMaterial;
  42682. })(BABYLON || (BABYLON = {}));
  42683. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42684. var BABYLON;
  42685. (function (BABYLON) {
  42686. /**
  42687. * The PBR material of BJS following the metal roughness convention.
  42688. *
  42689. * This fits to the PBR convention in the GLTF definition:
  42690. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42691. */
  42692. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42693. __extends(PBRMetallicRoughnessMaterial, _super);
  42694. /**
  42695. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42696. *
  42697. * @param name The material name
  42698. * @param scene The scene the material will be use in.
  42699. */
  42700. function PBRMetallicRoughnessMaterial(name, scene) {
  42701. var _this = _super.call(this, name, scene) || this;
  42702. _this._useRoughnessFromMetallicTextureAlpha = false;
  42703. _this._useRoughnessFromMetallicTextureGreen = true;
  42704. _this._useMetallnessFromMetallicTextureBlue = true;
  42705. _this.metallic = 1.0;
  42706. _this.roughness = 1.0;
  42707. return _this;
  42708. }
  42709. /**
  42710. * Return the currrent class name of the material.
  42711. */
  42712. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42713. return "PBRMetallicRoughnessMaterial";
  42714. };
  42715. /**
  42716. * Return the active textures of the material.
  42717. */
  42718. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42719. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42720. if (this.baseTexture) {
  42721. activeTextures.push(this.baseTexture);
  42722. }
  42723. if (this.metallicRoughnessTexture) {
  42724. activeTextures.push(this.metallicRoughnessTexture);
  42725. }
  42726. return activeTextures;
  42727. };
  42728. /**
  42729. * Checks to see if a texture is used in the material.
  42730. * @param texture - Base texture to use.
  42731. * @returns - Boolean specifying if a texture is used in the material.
  42732. */
  42733. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42734. if (_super.prototype.hasTexture.call(this, texture)) {
  42735. return true;
  42736. }
  42737. if (this.baseTexture === texture) {
  42738. return true;
  42739. }
  42740. if (this.metallicRoughnessTexture === texture) {
  42741. return true;
  42742. }
  42743. return false;
  42744. };
  42745. /**
  42746. * Makes a duplicate of the current material.
  42747. * @param name - name to use for the new material.
  42748. */
  42749. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42750. var _this = this;
  42751. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42752. clone.id = name;
  42753. clone.name = name;
  42754. return clone;
  42755. };
  42756. /**
  42757. * Serialize the material to a parsable JSON object.
  42758. */
  42759. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42760. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42761. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42762. return serializationObject;
  42763. };
  42764. /**
  42765. * Parses a JSON object correponding to the serialize function.
  42766. */
  42767. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42768. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42769. };
  42770. __decorate([
  42771. BABYLON.serializeAsColor3(),
  42772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42773. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42774. __decorate([
  42775. BABYLON.serializeAsTexture(),
  42776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42777. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42778. __decorate([
  42779. BABYLON.serialize(),
  42780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42781. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42782. __decorate([
  42783. BABYLON.serialize(),
  42784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42785. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42786. __decorate([
  42787. BABYLON.serializeAsTexture(),
  42788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42789. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42790. return PBRMetallicRoughnessMaterial;
  42791. }(BABYLON.PBRBaseSimpleMaterial));
  42792. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42793. })(BABYLON || (BABYLON = {}));
  42794. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42795. var BABYLON;
  42796. (function (BABYLON) {
  42797. /**
  42798. * The PBR material of BJS following the specular glossiness convention.
  42799. *
  42800. * This fits to the PBR convention in the GLTF definition:
  42801. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42802. */
  42803. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42804. __extends(PBRSpecularGlossinessMaterial, _super);
  42805. /**
  42806. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42807. *
  42808. * @param name The material name
  42809. * @param scene The scene the material will be use in.
  42810. */
  42811. function PBRSpecularGlossinessMaterial(name, scene) {
  42812. var _this = _super.call(this, name, scene) || this;
  42813. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42814. return _this;
  42815. }
  42816. /**
  42817. * Return the currrent class name of the material.
  42818. */
  42819. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42820. return "PBRSpecularGlossinessMaterial";
  42821. };
  42822. /**
  42823. * Return the active textures of the material.
  42824. */
  42825. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42826. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42827. if (this.diffuseTexture) {
  42828. activeTextures.push(this.diffuseTexture);
  42829. }
  42830. if (this.specularGlossinessTexture) {
  42831. activeTextures.push(this.specularGlossinessTexture);
  42832. }
  42833. return activeTextures;
  42834. };
  42835. /**
  42836. * Checks to see if a texture is used in the material.
  42837. * @param texture - Base texture to use.
  42838. * @returns - Boolean specifying if a texture is used in the material.
  42839. */
  42840. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42841. if (_super.prototype.hasTexture.call(this, texture)) {
  42842. return true;
  42843. }
  42844. if (this.diffuseTexture === texture) {
  42845. return true;
  42846. }
  42847. if (this.specularGlossinessTexture === texture) {
  42848. return true;
  42849. }
  42850. return false;
  42851. };
  42852. /**
  42853. * Makes a duplicate of the current material.
  42854. * @param name - name to use for the new material.
  42855. */
  42856. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42857. var _this = this;
  42858. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42859. clone.id = name;
  42860. clone.name = name;
  42861. return clone;
  42862. };
  42863. /**
  42864. * Serialize the material to a parsable JSON object.
  42865. */
  42866. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42867. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42868. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42869. return serializationObject;
  42870. };
  42871. /**
  42872. * Parses a JSON object correponding to the serialize function.
  42873. */
  42874. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42875. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42876. };
  42877. __decorate([
  42878. BABYLON.serializeAsColor3("diffuse"),
  42879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42880. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42881. __decorate([
  42882. BABYLON.serializeAsTexture(),
  42883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42884. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42885. __decorate([
  42886. BABYLON.serializeAsColor3("specular"),
  42887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42888. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42889. __decorate([
  42890. BABYLON.serialize(),
  42891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42892. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42893. __decorate([
  42894. BABYLON.serializeAsTexture(),
  42895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42896. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42897. return PBRSpecularGlossinessMaterial;
  42898. }(BABYLON.PBRBaseSimpleMaterial));
  42899. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42900. })(BABYLON || (BABYLON = {}));
  42901. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42902. var BABYLON;
  42903. (function (BABYLON) {
  42904. BABYLON.CameraInputTypes = {};
  42905. var CameraInputsManager = /** @class */ (function () {
  42906. function CameraInputsManager(camera) {
  42907. this.attached = {};
  42908. this.camera = camera;
  42909. this.checkInputs = function () { };
  42910. }
  42911. /**
  42912. * Add an input method to a camera.
  42913. * builtin inputs example: camera.inputs.addGamepad();
  42914. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42915. * @param input camera input method
  42916. */
  42917. CameraInputsManager.prototype.add = function (input) {
  42918. var type = input.getSimpleName();
  42919. if (this.attached[type]) {
  42920. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42921. return;
  42922. }
  42923. this.attached[type] = input;
  42924. input.camera = this.camera;
  42925. //for checkInputs, we are dynamically creating a function
  42926. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42927. if (input.checkInputs) {
  42928. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42929. }
  42930. if (this.attachedElement) {
  42931. input.attachControl(this.attachedElement);
  42932. }
  42933. };
  42934. /**
  42935. * Remove a specific input method from a camera
  42936. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42937. * @param inputToRemove camera input method
  42938. */
  42939. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42940. for (var cam in this.attached) {
  42941. var input = this.attached[cam];
  42942. if (input === inputToRemove) {
  42943. input.detachControl(this.attachedElement);
  42944. input.camera = null;
  42945. delete this.attached[cam];
  42946. this.rebuildInputCheck();
  42947. }
  42948. }
  42949. };
  42950. CameraInputsManager.prototype.removeByType = function (inputType) {
  42951. for (var cam in this.attached) {
  42952. var input = this.attached[cam];
  42953. if (input.getClassName() === inputType) {
  42954. input.detachControl(this.attachedElement);
  42955. input.camera = null;
  42956. delete this.attached[cam];
  42957. this.rebuildInputCheck();
  42958. }
  42959. }
  42960. };
  42961. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42962. var current = this.checkInputs;
  42963. return function () {
  42964. current();
  42965. fn();
  42966. };
  42967. };
  42968. CameraInputsManager.prototype.attachInput = function (input) {
  42969. if (this.attachedElement) {
  42970. input.attachControl(this.attachedElement, this.noPreventDefault);
  42971. }
  42972. };
  42973. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42974. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42975. if (this.attachedElement) {
  42976. return;
  42977. }
  42978. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42979. this.attachedElement = element;
  42980. this.noPreventDefault = noPreventDefault;
  42981. for (var cam in this.attached) {
  42982. this.attached[cam].attachControl(element, noPreventDefault);
  42983. }
  42984. };
  42985. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42986. if (disconnect === void 0) { disconnect = false; }
  42987. if (this.attachedElement !== element) {
  42988. return;
  42989. }
  42990. for (var cam in this.attached) {
  42991. this.attached[cam].detachControl(element);
  42992. if (disconnect) {
  42993. this.attached[cam].camera = null;
  42994. }
  42995. }
  42996. this.attachedElement = null;
  42997. };
  42998. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42999. this.checkInputs = function () { };
  43000. for (var cam in this.attached) {
  43001. var input = this.attached[cam];
  43002. if (input.checkInputs) {
  43003. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43004. }
  43005. }
  43006. };
  43007. /**
  43008. * Remove all attached input methods from a camera
  43009. */
  43010. CameraInputsManager.prototype.clear = function () {
  43011. if (this.attachedElement) {
  43012. this.detachElement(this.attachedElement, true);
  43013. }
  43014. this.attached = {};
  43015. this.attachedElement = null;
  43016. this.checkInputs = function () { };
  43017. };
  43018. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43019. var inputs = {};
  43020. for (var cam in this.attached) {
  43021. var input = this.attached[cam];
  43022. var res = BABYLON.SerializationHelper.Serialize(input);
  43023. inputs[input.getClassName()] = res;
  43024. }
  43025. serializedCamera.inputsmgr = inputs;
  43026. };
  43027. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43028. var parsedInputs = parsedCamera.inputsmgr;
  43029. if (parsedInputs) {
  43030. this.clear();
  43031. for (var n in parsedInputs) {
  43032. var construct = BABYLON.CameraInputTypes[n];
  43033. if (construct) {
  43034. var parsedinput = parsedInputs[n];
  43035. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43036. this.add(input);
  43037. }
  43038. }
  43039. }
  43040. else {
  43041. //2016-03-08 this part is for managing backward compatibility
  43042. for (var n in this.attached) {
  43043. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43044. if (construct) {
  43045. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43046. this.remove(this.attached[n]);
  43047. this.add(input);
  43048. }
  43049. }
  43050. }
  43051. };
  43052. return CameraInputsManager;
  43053. }());
  43054. BABYLON.CameraInputsManager = CameraInputsManager;
  43055. })(BABYLON || (BABYLON = {}));
  43056. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43057. var BABYLON;
  43058. (function (BABYLON) {
  43059. var TargetCamera = /** @class */ (function (_super) {
  43060. __extends(TargetCamera, _super);
  43061. function TargetCamera(name, position, scene) {
  43062. var _this = _super.call(this, name, position, scene) || this;
  43063. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43064. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43065. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43066. _this.speed = 2.0;
  43067. _this.noRotationConstraint = false;
  43068. _this.lockedTarget = null;
  43069. _this._currentTarget = BABYLON.Vector3.Zero();
  43070. _this._viewMatrix = BABYLON.Matrix.Zero();
  43071. _this._camMatrix = BABYLON.Matrix.Zero();
  43072. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43073. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43074. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43075. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43076. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43077. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43078. _this._tempMatrix = BABYLON.Matrix.Zero();
  43079. return _this;
  43080. }
  43081. TargetCamera.prototype.getFrontPosition = function (distance) {
  43082. this.getWorldMatrix();
  43083. var direction = this.getTarget().subtract(this.position);
  43084. direction.normalize();
  43085. direction.scaleInPlace(distance);
  43086. return this.globalPosition.add(direction);
  43087. };
  43088. TargetCamera.prototype._getLockedTargetPosition = function () {
  43089. if (!this.lockedTarget) {
  43090. return null;
  43091. }
  43092. if (this.lockedTarget.absolutePosition) {
  43093. this.lockedTarget.computeWorldMatrix();
  43094. }
  43095. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43096. };
  43097. TargetCamera.prototype.storeState = function () {
  43098. this._storedPosition = this.position.clone();
  43099. this._storedRotation = this.rotation.clone();
  43100. if (this.rotationQuaternion) {
  43101. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43102. }
  43103. return _super.prototype.storeState.call(this);
  43104. };
  43105. /**
  43106. * Restored camera state. You must call storeState() first
  43107. */
  43108. TargetCamera.prototype._restoreStateValues = function () {
  43109. if (!_super.prototype._restoreStateValues.call(this)) {
  43110. return false;
  43111. }
  43112. this.position = this._storedPosition.clone();
  43113. this.rotation = this._storedRotation.clone();
  43114. if (this.rotationQuaternion) {
  43115. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43116. }
  43117. this.cameraDirection.copyFromFloats(0, 0, 0);
  43118. this.cameraRotation.copyFromFloats(0, 0);
  43119. return true;
  43120. };
  43121. // Cache
  43122. TargetCamera.prototype._initCache = function () {
  43123. _super.prototype._initCache.call(this);
  43124. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43125. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43126. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43127. };
  43128. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43129. if (!ignoreParentClass) {
  43130. _super.prototype._updateCache.call(this);
  43131. }
  43132. var lockedTargetPosition = this._getLockedTargetPosition();
  43133. if (!lockedTargetPosition) {
  43134. this._cache.lockedTarget = null;
  43135. }
  43136. else {
  43137. if (!this._cache.lockedTarget) {
  43138. this._cache.lockedTarget = lockedTargetPosition.clone();
  43139. }
  43140. else {
  43141. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43142. }
  43143. }
  43144. this._cache.rotation.copyFrom(this.rotation);
  43145. if (this.rotationQuaternion)
  43146. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43147. };
  43148. // Synchronized
  43149. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43150. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43151. return false;
  43152. }
  43153. var lockedTargetPosition = this._getLockedTargetPosition();
  43154. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43155. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43156. };
  43157. // Methods
  43158. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43159. var engine = this.getEngine();
  43160. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43161. };
  43162. // Target
  43163. TargetCamera.prototype.setTarget = function (target) {
  43164. this.upVector.normalize();
  43165. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43166. this._camMatrix.invert();
  43167. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43168. var vDir = target.subtract(this.position);
  43169. if (vDir.x >= 0.0) {
  43170. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43171. }
  43172. else {
  43173. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43174. }
  43175. this.rotation.z = 0;
  43176. if (isNaN(this.rotation.x)) {
  43177. this.rotation.x = 0;
  43178. }
  43179. if (isNaN(this.rotation.y)) {
  43180. this.rotation.y = 0;
  43181. }
  43182. if (isNaN(this.rotation.z)) {
  43183. this.rotation.z = 0;
  43184. }
  43185. if (this.rotationQuaternion) {
  43186. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43187. }
  43188. };
  43189. /**
  43190. * Return the current target position of the camera. This value is expressed in local space.
  43191. */
  43192. TargetCamera.prototype.getTarget = function () {
  43193. return this._currentTarget;
  43194. };
  43195. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43196. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43197. };
  43198. TargetCamera.prototype._updatePosition = function () {
  43199. if (this.parent) {
  43200. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43201. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43202. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43203. return;
  43204. }
  43205. this.position.addInPlace(this.cameraDirection);
  43206. };
  43207. TargetCamera.prototype._checkInputs = function () {
  43208. var needToMove = this._decideIfNeedsToMove();
  43209. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43210. // Move
  43211. if (needToMove) {
  43212. this._updatePosition();
  43213. }
  43214. // Rotate
  43215. if (needToRotate) {
  43216. this.rotation.x += this.cameraRotation.x;
  43217. this.rotation.y += this.cameraRotation.y;
  43218. //rotate, if quaternion is set and rotation was used
  43219. if (this.rotationQuaternion) {
  43220. var len = this.rotation.lengthSquared();
  43221. if (len) {
  43222. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43223. }
  43224. }
  43225. if (!this.noRotationConstraint) {
  43226. var limit = (Math.PI / 2) * 0.95;
  43227. if (this.rotation.x > limit)
  43228. this.rotation.x = limit;
  43229. if (this.rotation.x < -limit)
  43230. this.rotation.x = -limit;
  43231. }
  43232. }
  43233. // Inertia
  43234. if (needToMove) {
  43235. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43236. this.cameraDirection.x = 0;
  43237. }
  43238. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43239. this.cameraDirection.y = 0;
  43240. }
  43241. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43242. this.cameraDirection.z = 0;
  43243. }
  43244. this.cameraDirection.scaleInPlace(this.inertia);
  43245. }
  43246. if (needToRotate) {
  43247. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43248. this.cameraRotation.x = 0;
  43249. }
  43250. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43251. this.cameraRotation.y = 0;
  43252. }
  43253. this.cameraRotation.scaleInPlace(this.inertia);
  43254. }
  43255. _super.prototype._checkInputs.call(this);
  43256. };
  43257. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43258. if (this.rotationQuaternion) {
  43259. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43260. }
  43261. else {
  43262. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43263. }
  43264. //update the up vector!
  43265. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43266. };
  43267. TargetCamera.prototype._getViewMatrix = function () {
  43268. if (this.lockedTarget) {
  43269. this.setTarget(this._getLockedTargetPosition());
  43270. }
  43271. // Compute
  43272. this._updateCameraRotationMatrix();
  43273. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43274. // Computing target and final matrix
  43275. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43276. if (this.getScene().useRightHandedSystem) {
  43277. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43278. }
  43279. else {
  43280. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43281. }
  43282. return this._viewMatrix;
  43283. };
  43284. /**
  43285. * @override
  43286. * Override Camera.createRigCamera
  43287. */
  43288. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43289. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43290. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43291. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43292. if (!this.rotationQuaternion) {
  43293. this.rotationQuaternion = new BABYLON.Quaternion();
  43294. }
  43295. rigCamera._cameraRigParams = {};
  43296. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43297. }
  43298. return rigCamera;
  43299. }
  43300. return null;
  43301. };
  43302. /**
  43303. * @override
  43304. * Override Camera._updateRigCameras
  43305. */
  43306. TargetCamera.prototype._updateRigCameras = function () {
  43307. var camLeft = this._rigCameras[0];
  43308. var camRight = this._rigCameras[1];
  43309. switch (this.cameraRigMode) {
  43310. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43311. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43312. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43313. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43314. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43315. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43316. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43317. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43318. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43319. camLeft.setTarget(this.getTarget());
  43320. camRight.setTarget(this.getTarget());
  43321. break;
  43322. case BABYLON.Camera.RIG_MODE_VR:
  43323. if (camLeft.rotationQuaternion) {
  43324. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43325. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43326. }
  43327. else {
  43328. camLeft.rotation.copyFrom(this.rotation);
  43329. camRight.rotation.copyFrom(this.rotation);
  43330. }
  43331. camLeft.position.copyFrom(this.position);
  43332. camRight.position.copyFrom(this.position);
  43333. break;
  43334. }
  43335. _super.prototype._updateRigCameras.call(this);
  43336. };
  43337. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43338. if (!this._rigCamTransformMatrix) {
  43339. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43340. }
  43341. var target = this.getTarget();
  43342. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43343. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43344. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43345. };
  43346. TargetCamera.prototype.getClassName = function () {
  43347. return "TargetCamera";
  43348. };
  43349. __decorate([
  43350. BABYLON.serializeAsVector3()
  43351. ], TargetCamera.prototype, "rotation", void 0);
  43352. __decorate([
  43353. BABYLON.serialize()
  43354. ], TargetCamera.prototype, "speed", void 0);
  43355. __decorate([
  43356. BABYLON.serializeAsMeshReference("lockedTargetId")
  43357. ], TargetCamera.prototype, "lockedTarget", void 0);
  43358. return TargetCamera;
  43359. }(BABYLON.Camera));
  43360. BABYLON.TargetCamera = TargetCamera;
  43361. })(BABYLON || (BABYLON = {}));
  43362. //# sourceMappingURL=babylon.targetCamera.js.map
  43363. var BABYLON;
  43364. (function (BABYLON) {
  43365. var FreeCameraMouseInput = /** @class */ (function () {
  43366. function FreeCameraMouseInput(touchEnabled) {
  43367. if (touchEnabled === void 0) { touchEnabled = true; }
  43368. this.touchEnabled = touchEnabled;
  43369. this.buttons = [0, 1, 2];
  43370. this.angularSensibility = 2000.0;
  43371. this.previousPosition = null;
  43372. }
  43373. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43374. var _this = this;
  43375. var engine = this.camera.getEngine();
  43376. if (!this._pointerInput) {
  43377. this._pointerInput = function (p, s) {
  43378. var evt = p.event;
  43379. if (engine.isInVRExclusivePointerMode) {
  43380. return;
  43381. }
  43382. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43383. return;
  43384. }
  43385. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43386. return;
  43387. }
  43388. var srcElement = (evt.srcElement || evt.target);
  43389. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43390. try {
  43391. srcElement.setPointerCapture(evt.pointerId);
  43392. }
  43393. catch (e) {
  43394. //Nothing to do with the error. Execution will continue.
  43395. }
  43396. _this.previousPosition = {
  43397. x: evt.clientX,
  43398. y: evt.clientY
  43399. };
  43400. if (!noPreventDefault) {
  43401. evt.preventDefault();
  43402. element.focus();
  43403. }
  43404. }
  43405. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43406. try {
  43407. srcElement.releasePointerCapture(evt.pointerId);
  43408. }
  43409. catch (e) {
  43410. //Nothing to do with the error.
  43411. }
  43412. _this.previousPosition = null;
  43413. if (!noPreventDefault) {
  43414. evt.preventDefault();
  43415. }
  43416. }
  43417. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43418. if (!_this.previousPosition || engine.isPointerLock) {
  43419. return;
  43420. }
  43421. var offsetX = evt.clientX - _this.previousPosition.x;
  43422. var offsetY = evt.clientY - _this.previousPosition.y;
  43423. if (_this.camera.getScene().useRightHandedSystem) {
  43424. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43425. }
  43426. else {
  43427. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43428. }
  43429. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43430. _this.previousPosition = {
  43431. x: evt.clientX,
  43432. y: evt.clientY
  43433. };
  43434. if (!noPreventDefault) {
  43435. evt.preventDefault();
  43436. }
  43437. }
  43438. };
  43439. }
  43440. this._onMouseMove = function (evt) {
  43441. if (!engine.isPointerLock) {
  43442. return;
  43443. }
  43444. if (engine.isInVRExclusivePointerMode) {
  43445. return;
  43446. }
  43447. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43448. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43449. if (_this.camera.getScene().useRightHandedSystem) {
  43450. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43451. }
  43452. else {
  43453. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43454. }
  43455. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43456. _this.previousPosition = null;
  43457. if (!noPreventDefault) {
  43458. evt.preventDefault();
  43459. }
  43460. };
  43461. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43462. element.addEventListener("mousemove", this._onMouseMove, false);
  43463. };
  43464. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43465. if (this._observer && element) {
  43466. this.camera.getScene().onPointerObservable.remove(this._observer);
  43467. if (this._onMouseMove) {
  43468. element.removeEventListener("mousemove", this._onMouseMove);
  43469. }
  43470. this._observer = null;
  43471. this._onMouseMove = null;
  43472. this.previousPosition = null;
  43473. }
  43474. };
  43475. FreeCameraMouseInput.prototype.getClassName = function () {
  43476. return "FreeCameraMouseInput";
  43477. };
  43478. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43479. return "mouse";
  43480. };
  43481. __decorate([
  43482. BABYLON.serialize()
  43483. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43484. __decorate([
  43485. BABYLON.serialize()
  43486. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43487. return FreeCameraMouseInput;
  43488. }());
  43489. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43490. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43491. })(BABYLON || (BABYLON = {}));
  43492. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43493. var BABYLON;
  43494. (function (BABYLON) {
  43495. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43496. function FreeCameraKeyboardMoveInput() {
  43497. this._keys = new Array();
  43498. this.keysUp = [38];
  43499. this.keysDown = [40];
  43500. this.keysLeft = [37];
  43501. this.keysRight = [39];
  43502. }
  43503. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43504. var _this = this;
  43505. if (this._onCanvasBlurObserver) {
  43506. return;
  43507. }
  43508. this._scene = this.camera.getScene();
  43509. this._engine = this._scene.getEngine();
  43510. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43511. _this._keys = [];
  43512. });
  43513. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43514. var evt = info.event;
  43515. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43516. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43517. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43518. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43519. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43520. var index = _this._keys.indexOf(evt.keyCode);
  43521. if (index === -1) {
  43522. _this._keys.push(evt.keyCode);
  43523. }
  43524. if (!noPreventDefault) {
  43525. evt.preventDefault();
  43526. }
  43527. }
  43528. }
  43529. else {
  43530. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43531. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43532. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43533. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43534. var index = _this._keys.indexOf(evt.keyCode);
  43535. if (index >= 0) {
  43536. _this._keys.splice(index, 1);
  43537. }
  43538. if (!noPreventDefault) {
  43539. evt.preventDefault();
  43540. }
  43541. }
  43542. }
  43543. });
  43544. };
  43545. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43546. if (this._scene) {
  43547. if (this._onKeyboardObserver) {
  43548. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43549. }
  43550. if (this._onCanvasBlurObserver) {
  43551. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43552. }
  43553. this._onKeyboardObserver = null;
  43554. this._onCanvasBlurObserver = null;
  43555. }
  43556. this._keys = [];
  43557. };
  43558. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43559. if (this._onKeyboardObserver) {
  43560. var camera = this.camera;
  43561. // Keyboard
  43562. for (var index = 0; index < this._keys.length; index++) {
  43563. var keyCode = this._keys[index];
  43564. var speed = camera._computeLocalCameraSpeed();
  43565. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43566. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43567. }
  43568. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43569. camera._localDirection.copyFromFloats(0, 0, speed);
  43570. }
  43571. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43572. camera._localDirection.copyFromFloats(speed, 0, 0);
  43573. }
  43574. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43575. camera._localDirection.copyFromFloats(0, 0, -speed);
  43576. }
  43577. if (camera.getScene().useRightHandedSystem) {
  43578. camera._localDirection.z *= -1;
  43579. }
  43580. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43581. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43582. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43583. }
  43584. }
  43585. };
  43586. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43587. return "FreeCameraKeyboardMoveInput";
  43588. };
  43589. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43590. this._keys = [];
  43591. };
  43592. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43593. return "keyboard";
  43594. };
  43595. __decorate([
  43596. BABYLON.serialize()
  43597. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43598. __decorate([
  43599. BABYLON.serialize()
  43600. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43601. __decorate([
  43602. BABYLON.serialize()
  43603. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43604. __decorate([
  43605. BABYLON.serialize()
  43606. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43607. return FreeCameraKeyboardMoveInput;
  43608. }());
  43609. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43610. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43611. })(BABYLON || (BABYLON = {}));
  43612. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43613. var BABYLON;
  43614. (function (BABYLON) {
  43615. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43616. __extends(FreeCameraInputsManager, _super);
  43617. function FreeCameraInputsManager(camera) {
  43618. return _super.call(this, camera) || this;
  43619. }
  43620. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43621. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43622. return this;
  43623. };
  43624. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43625. if (touchEnabled === void 0) { touchEnabled = true; }
  43626. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43627. return this;
  43628. };
  43629. FreeCameraInputsManager.prototype.addGamepad = function () {
  43630. this.add(new BABYLON.FreeCameraGamepadInput());
  43631. return this;
  43632. };
  43633. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43634. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43635. return this;
  43636. };
  43637. FreeCameraInputsManager.prototype.addTouch = function () {
  43638. this.add(new BABYLON.FreeCameraTouchInput());
  43639. return this;
  43640. };
  43641. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43642. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43643. return this;
  43644. };
  43645. return FreeCameraInputsManager;
  43646. }(BABYLON.CameraInputsManager));
  43647. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43648. })(BABYLON || (BABYLON = {}));
  43649. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43650. var BABYLON;
  43651. (function (BABYLON) {
  43652. var FreeCamera = /** @class */ (function (_super) {
  43653. __extends(FreeCamera, _super);
  43654. function FreeCamera(name, position, scene) {
  43655. var _this = _super.call(this, name, position, scene) || this;
  43656. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43657. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43658. _this.checkCollisions = false;
  43659. _this.applyGravity = false;
  43660. _this._needMoveForGravity = false;
  43661. _this._oldPosition = BABYLON.Vector3.Zero();
  43662. _this._diffPosition = BABYLON.Vector3.Zero();
  43663. _this._newPosition = BABYLON.Vector3.Zero();
  43664. // Collisions
  43665. _this._collisionMask = -1;
  43666. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43667. if (collidedMesh === void 0) { collidedMesh = null; }
  43668. //TODO move this to the collision coordinator!
  43669. if (_this.getScene().workerCollisions)
  43670. newPosition.multiplyInPlace(_this._collider._radius);
  43671. var updatePosition = function (newPos) {
  43672. _this._newPosition.copyFrom(newPos);
  43673. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43674. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43675. _this.position.addInPlace(_this._diffPosition);
  43676. if (_this.onCollide && collidedMesh) {
  43677. _this.onCollide(collidedMesh);
  43678. }
  43679. }
  43680. };
  43681. updatePosition(newPosition);
  43682. };
  43683. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43684. _this.inputs.addKeyboard().addMouse();
  43685. return _this;
  43686. }
  43687. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43688. //-- begin properties for backward compatibility for inputs
  43689. /**
  43690. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43691. * Higher values reduce sensitivity.
  43692. */
  43693. get: function () {
  43694. var mouse = this.inputs.attached["mouse"];
  43695. if (mouse)
  43696. return mouse.angularSensibility;
  43697. return 0;
  43698. },
  43699. /**
  43700. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43701. * Higher values reduce sensitivity.
  43702. */
  43703. set: function (value) {
  43704. var mouse = this.inputs.attached["mouse"];
  43705. if (mouse)
  43706. mouse.angularSensibility = value;
  43707. },
  43708. enumerable: true,
  43709. configurable: true
  43710. });
  43711. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43712. get: function () {
  43713. var keyboard = this.inputs.attached["keyboard"];
  43714. if (keyboard)
  43715. return keyboard.keysUp;
  43716. return [];
  43717. },
  43718. set: function (value) {
  43719. var keyboard = this.inputs.attached["keyboard"];
  43720. if (keyboard)
  43721. keyboard.keysUp = value;
  43722. },
  43723. enumerable: true,
  43724. configurable: true
  43725. });
  43726. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43727. get: function () {
  43728. var keyboard = this.inputs.attached["keyboard"];
  43729. if (keyboard)
  43730. return keyboard.keysDown;
  43731. return [];
  43732. },
  43733. set: function (value) {
  43734. var keyboard = this.inputs.attached["keyboard"];
  43735. if (keyboard)
  43736. keyboard.keysDown = value;
  43737. },
  43738. enumerable: true,
  43739. configurable: true
  43740. });
  43741. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43742. get: function () {
  43743. var keyboard = this.inputs.attached["keyboard"];
  43744. if (keyboard)
  43745. return keyboard.keysLeft;
  43746. return [];
  43747. },
  43748. set: function (value) {
  43749. var keyboard = this.inputs.attached["keyboard"];
  43750. if (keyboard)
  43751. keyboard.keysLeft = value;
  43752. },
  43753. enumerable: true,
  43754. configurable: true
  43755. });
  43756. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43757. get: function () {
  43758. var keyboard = this.inputs.attached["keyboard"];
  43759. if (keyboard)
  43760. return keyboard.keysRight;
  43761. return [];
  43762. },
  43763. set: function (value) {
  43764. var keyboard = this.inputs.attached["keyboard"];
  43765. if (keyboard)
  43766. keyboard.keysRight = value;
  43767. },
  43768. enumerable: true,
  43769. configurable: true
  43770. });
  43771. // Controls
  43772. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43773. this.inputs.attachElement(element, noPreventDefault);
  43774. };
  43775. FreeCamera.prototype.detachControl = function (element) {
  43776. this.inputs.detachElement(element);
  43777. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43778. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43779. };
  43780. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43781. get: function () {
  43782. return this._collisionMask;
  43783. },
  43784. set: function (mask) {
  43785. this._collisionMask = !isNaN(mask) ? mask : -1;
  43786. },
  43787. enumerable: true,
  43788. configurable: true
  43789. });
  43790. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43791. var globalPosition;
  43792. if (this.parent) {
  43793. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43794. }
  43795. else {
  43796. globalPosition = this.position;
  43797. }
  43798. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43799. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43800. if (!this._collider) {
  43801. this._collider = new BABYLON.Collider();
  43802. }
  43803. this._collider._radius = this.ellipsoid;
  43804. this._collider.collisionMask = this._collisionMask;
  43805. //no need for clone, as long as gravity is not on.
  43806. var actualDisplacement = displacement;
  43807. //add gravity to the direction to prevent the dual-collision checking
  43808. if (this.applyGravity) {
  43809. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43810. actualDisplacement = displacement.add(this.getScene().gravity);
  43811. }
  43812. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43813. };
  43814. FreeCamera.prototype._checkInputs = function () {
  43815. if (!this._localDirection) {
  43816. this._localDirection = BABYLON.Vector3.Zero();
  43817. this._transformedDirection = BABYLON.Vector3.Zero();
  43818. }
  43819. this.inputs.checkInputs();
  43820. _super.prototype._checkInputs.call(this);
  43821. };
  43822. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43823. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43824. };
  43825. FreeCamera.prototype._updatePosition = function () {
  43826. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43827. this._collideWithWorld(this.cameraDirection);
  43828. }
  43829. else {
  43830. _super.prototype._updatePosition.call(this);
  43831. }
  43832. };
  43833. FreeCamera.prototype.dispose = function () {
  43834. this.inputs.clear();
  43835. _super.prototype.dispose.call(this);
  43836. };
  43837. FreeCamera.prototype.getClassName = function () {
  43838. return "FreeCamera";
  43839. };
  43840. __decorate([
  43841. BABYLON.serializeAsVector3()
  43842. ], FreeCamera.prototype, "ellipsoid", void 0);
  43843. __decorate([
  43844. BABYLON.serializeAsVector3()
  43845. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43846. __decorate([
  43847. BABYLON.serialize()
  43848. ], FreeCamera.prototype, "checkCollisions", void 0);
  43849. __decorate([
  43850. BABYLON.serialize()
  43851. ], FreeCamera.prototype, "applyGravity", void 0);
  43852. return FreeCamera;
  43853. }(BABYLON.TargetCamera));
  43854. BABYLON.FreeCamera = FreeCamera;
  43855. })(BABYLON || (BABYLON = {}));
  43856. //# sourceMappingURL=babylon.freeCamera.js.map
  43857. var BABYLON;
  43858. (function (BABYLON) {
  43859. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43860. function ArcRotateCameraKeyboardMoveInput() {
  43861. this._keys = new Array();
  43862. this.keysUp = [38];
  43863. this.keysDown = [40];
  43864. this.keysLeft = [37];
  43865. this.keysRight = [39];
  43866. this.keysReset = [220];
  43867. this.panningSensibility = 50.0;
  43868. this.zoomingSensibility = 25.0;
  43869. this.useAltToZoom = true;
  43870. }
  43871. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43872. var _this = this;
  43873. if (this._onCanvasBlurObserver) {
  43874. return;
  43875. }
  43876. this._scene = this.camera.getScene();
  43877. this._engine = this._scene.getEngine();
  43878. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43879. _this._keys = [];
  43880. });
  43881. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43882. var evt = info.event;
  43883. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43884. _this._ctrlPressed = evt.ctrlKey;
  43885. _this._altPressed = evt.altKey;
  43886. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43887. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43888. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43889. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43890. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43891. var index = _this._keys.indexOf(evt.keyCode);
  43892. if (index === -1) {
  43893. _this._keys.push(evt.keyCode);
  43894. }
  43895. if (evt.preventDefault) {
  43896. if (!noPreventDefault) {
  43897. evt.preventDefault();
  43898. }
  43899. }
  43900. }
  43901. }
  43902. else {
  43903. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43904. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43905. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43906. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43907. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43908. var index = _this._keys.indexOf(evt.keyCode);
  43909. if (index >= 0) {
  43910. _this._keys.splice(index, 1);
  43911. }
  43912. if (evt.preventDefault) {
  43913. if (!noPreventDefault) {
  43914. evt.preventDefault();
  43915. }
  43916. }
  43917. }
  43918. }
  43919. });
  43920. };
  43921. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43922. if (this._scene) {
  43923. if (this._onKeyboardObserver) {
  43924. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43925. }
  43926. if (this._onCanvasBlurObserver) {
  43927. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43928. }
  43929. this._onKeyboardObserver = null;
  43930. this._onCanvasBlurObserver = null;
  43931. }
  43932. this._keys = [];
  43933. };
  43934. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43935. if (this._onKeyboardObserver) {
  43936. var camera = this.camera;
  43937. for (var index = 0; index < this._keys.length; index++) {
  43938. var keyCode = this._keys[index];
  43939. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43940. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43941. camera.inertialPanningX -= 1 / this.panningSensibility;
  43942. }
  43943. else {
  43944. camera.inertialAlphaOffset -= 0.01;
  43945. }
  43946. }
  43947. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43948. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43949. camera.inertialPanningY += 1 / this.panningSensibility;
  43950. }
  43951. else if (this._altPressed && this.useAltToZoom) {
  43952. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43953. }
  43954. else {
  43955. camera.inertialBetaOffset -= 0.01;
  43956. }
  43957. }
  43958. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43959. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43960. camera.inertialPanningX += 1 / this.panningSensibility;
  43961. }
  43962. else {
  43963. camera.inertialAlphaOffset += 0.01;
  43964. }
  43965. }
  43966. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43967. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43968. camera.inertialPanningY -= 1 / this.panningSensibility;
  43969. }
  43970. else if (this._altPressed && this.useAltToZoom) {
  43971. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43972. }
  43973. else {
  43974. camera.inertialBetaOffset += 0.01;
  43975. }
  43976. }
  43977. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43978. camera.restoreState();
  43979. }
  43980. }
  43981. }
  43982. };
  43983. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43984. return "ArcRotateCameraKeyboardMoveInput";
  43985. };
  43986. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43987. return "keyboard";
  43988. };
  43989. __decorate([
  43990. BABYLON.serialize()
  43991. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43992. __decorate([
  43993. BABYLON.serialize()
  43994. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43995. __decorate([
  43996. BABYLON.serialize()
  43997. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43998. __decorate([
  43999. BABYLON.serialize()
  44000. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44001. __decorate([
  44002. BABYLON.serialize()
  44003. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44004. __decorate([
  44005. BABYLON.serialize()
  44006. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44007. __decorate([
  44008. BABYLON.serialize()
  44009. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44010. __decorate([
  44011. BABYLON.serialize()
  44012. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44013. return ArcRotateCameraKeyboardMoveInput;
  44014. }());
  44015. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44016. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44017. })(BABYLON || (BABYLON = {}));
  44018. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44019. var BABYLON;
  44020. (function (BABYLON) {
  44021. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44022. function ArcRotateCameraMouseWheelInput() {
  44023. this.wheelPrecision = 3.0;
  44024. /**
  44025. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44026. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44027. */
  44028. this.wheelDeltaPercentage = 0;
  44029. }
  44030. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44031. var _this = this;
  44032. this._wheel = function (p, s) {
  44033. //sanity check - this should be a PointerWheel event.
  44034. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44035. return;
  44036. var event = p.event;
  44037. var delta = 0;
  44038. if (event.wheelDelta) {
  44039. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44040. }
  44041. else if (event.detail) {
  44042. delta = -event.detail / _this.wheelPrecision;
  44043. }
  44044. if (delta)
  44045. _this.camera.inertialRadiusOffset += delta;
  44046. if (event.preventDefault) {
  44047. if (!noPreventDefault) {
  44048. event.preventDefault();
  44049. }
  44050. }
  44051. };
  44052. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44053. };
  44054. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44055. if (this._observer && element) {
  44056. this.camera.getScene().onPointerObservable.remove(this._observer);
  44057. this._observer = null;
  44058. this._wheel = null;
  44059. }
  44060. };
  44061. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44062. return "ArcRotateCameraMouseWheelInput";
  44063. };
  44064. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44065. return "mousewheel";
  44066. };
  44067. __decorate([
  44068. BABYLON.serialize()
  44069. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44070. __decorate([
  44071. BABYLON.serialize()
  44072. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44073. return ArcRotateCameraMouseWheelInput;
  44074. }());
  44075. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44076. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44077. })(BABYLON || (BABYLON = {}));
  44078. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44079. var BABYLON;
  44080. (function (BABYLON) {
  44081. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44082. function ArcRotateCameraPointersInput() {
  44083. this.buttons = [0, 1, 2];
  44084. this.angularSensibilityX = 1000.0;
  44085. this.angularSensibilityY = 1000.0;
  44086. this.pinchPrecision = 12.0;
  44087. /**
  44088. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44089. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44090. */
  44091. this.pinchDeltaPercentage = 0;
  44092. this.panningSensibility = 1000.0;
  44093. this.multiTouchPanning = true;
  44094. this.multiTouchPanAndZoom = true;
  44095. this._isPanClick = false;
  44096. this.pinchInwards = true;
  44097. }
  44098. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44099. var _this = this;
  44100. var engine = this.camera.getEngine();
  44101. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44102. var pointA = null;
  44103. var pointB = null;
  44104. var previousPinchSquaredDistance = 0;
  44105. var initialDistance = 0;
  44106. var twoFingerActivityCount = 0;
  44107. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44108. this._pointerInput = function (p, s) {
  44109. var evt = p.event;
  44110. var isTouch = p.event.pointerType === "touch";
  44111. if (engine.isInVRExclusivePointerMode) {
  44112. return;
  44113. }
  44114. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44115. return;
  44116. }
  44117. var srcElement = (evt.srcElement || evt.target);
  44118. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44119. try {
  44120. srcElement.setPointerCapture(evt.pointerId);
  44121. }
  44122. catch (e) {
  44123. //Nothing to do with the error. Execution will continue.
  44124. }
  44125. // Manage panning with pan button click
  44126. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44127. // manage pointers
  44128. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44129. if (pointA === null) {
  44130. pointA = cacheSoloPointer;
  44131. }
  44132. else if (pointB === null) {
  44133. pointB = cacheSoloPointer;
  44134. }
  44135. if (!noPreventDefault) {
  44136. evt.preventDefault();
  44137. element.focus();
  44138. }
  44139. }
  44140. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44141. _this.camera.restoreState();
  44142. }
  44143. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44144. try {
  44145. srcElement.releasePointerCapture(evt.pointerId);
  44146. }
  44147. catch (e) {
  44148. //Nothing to do with the error.
  44149. }
  44150. cacheSoloPointer = null;
  44151. previousPinchSquaredDistance = 0;
  44152. previousMultiTouchPanPosition.isPaning = false;
  44153. previousMultiTouchPanPosition.isPinching = false;
  44154. twoFingerActivityCount = 0;
  44155. initialDistance = 0;
  44156. if (!isTouch) {
  44157. pointB = null; // Mouse and pen are mono pointer
  44158. }
  44159. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44160. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44161. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44162. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44163. if (engine.badOS) {
  44164. pointA = pointB = null;
  44165. }
  44166. else {
  44167. //only remove the impacted pointer in case of multitouch allowing on most
  44168. //platforms switching from rotate to zoom and pan seamlessly.
  44169. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44170. pointA = pointB;
  44171. pointB = null;
  44172. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44173. }
  44174. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44175. pointB = null;
  44176. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44177. }
  44178. else {
  44179. pointA = pointB = null;
  44180. }
  44181. }
  44182. if (!noPreventDefault) {
  44183. evt.preventDefault();
  44184. }
  44185. }
  44186. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44187. if (!noPreventDefault) {
  44188. evt.preventDefault();
  44189. }
  44190. // One button down
  44191. if (pointA && pointB === null && cacheSoloPointer) {
  44192. if (_this.panningSensibility !== 0 &&
  44193. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44194. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44195. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44196. }
  44197. else {
  44198. var offsetX = evt.clientX - cacheSoloPointer.x;
  44199. var offsetY = evt.clientY - cacheSoloPointer.y;
  44200. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44201. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44202. }
  44203. cacheSoloPointer.x = evt.clientX;
  44204. cacheSoloPointer.y = evt.clientY;
  44205. }
  44206. else if (pointA && pointB) {
  44207. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44208. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44209. ed.x = evt.clientX;
  44210. ed.y = evt.clientY;
  44211. var direction = _this.pinchInwards ? 1 : -1;
  44212. var distX = pointA.x - pointB.x;
  44213. var distY = pointA.y - pointB.y;
  44214. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44215. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44216. if (previousPinchSquaredDistance === 0) {
  44217. initialDistance = pinchDistance;
  44218. previousPinchSquaredDistance = pinchSquaredDistance;
  44219. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44220. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44221. return;
  44222. }
  44223. if (_this.multiTouchPanAndZoom) {
  44224. if (_this.pinchDeltaPercentage) {
  44225. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44226. }
  44227. else {
  44228. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44229. (_this.pinchPrecision *
  44230. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44231. direction);
  44232. }
  44233. if (_this.panningSensibility !== 0) {
  44234. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44235. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44236. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44237. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44238. previousMultiTouchPanPosition.x = pointersCenterX;
  44239. previousMultiTouchPanPosition.y = pointersCenterY;
  44240. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44241. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44242. }
  44243. }
  44244. else {
  44245. twoFingerActivityCount++;
  44246. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44247. if (_this.pinchDeltaPercentage) {
  44248. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44249. }
  44250. else {
  44251. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44252. (_this.pinchPrecision *
  44253. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44254. direction);
  44255. }
  44256. previousMultiTouchPanPosition.isPaning = false;
  44257. previousMultiTouchPanPosition.isPinching = true;
  44258. }
  44259. else {
  44260. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44261. if (!previousMultiTouchPanPosition.isPaning) {
  44262. previousMultiTouchPanPosition.isPaning = true;
  44263. previousMultiTouchPanPosition.isPinching = false;
  44264. previousMultiTouchPanPosition.x = ed.x;
  44265. previousMultiTouchPanPosition.y = ed.y;
  44266. return;
  44267. }
  44268. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44269. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44270. }
  44271. }
  44272. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44273. previousMultiTouchPanPosition.x = ed.x;
  44274. previousMultiTouchPanPosition.y = ed.y;
  44275. }
  44276. }
  44277. previousPinchSquaredDistance = pinchSquaredDistance;
  44278. }
  44279. }
  44280. };
  44281. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44282. this._onContextMenu = function (evt) {
  44283. evt.preventDefault();
  44284. };
  44285. if (!this.camera._useCtrlForPanning) {
  44286. element.addEventListener("contextmenu", this._onContextMenu, false);
  44287. }
  44288. this._onLostFocus = function () {
  44289. //this._keys = [];
  44290. pointA = pointB = null;
  44291. previousPinchSquaredDistance = 0;
  44292. previousMultiTouchPanPosition.isPaning = false;
  44293. previousMultiTouchPanPosition.isPinching = false;
  44294. twoFingerActivityCount = 0;
  44295. cacheSoloPointer = null;
  44296. initialDistance = 0;
  44297. };
  44298. this._onMouseMove = function (evt) {
  44299. if (!engine.isPointerLock) {
  44300. return;
  44301. }
  44302. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44303. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44304. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44305. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44306. if (!noPreventDefault) {
  44307. evt.preventDefault();
  44308. }
  44309. };
  44310. this._onGestureStart = function (e) {
  44311. if (window.MSGesture === undefined) {
  44312. return;
  44313. }
  44314. if (!_this._MSGestureHandler) {
  44315. _this._MSGestureHandler = new MSGesture();
  44316. _this._MSGestureHandler.target = element;
  44317. }
  44318. _this._MSGestureHandler.addPointer(e.pointerId);
  44319. };
  44320. this._onGesture = function (e) {
  44321. _this.camera.radius *= e.scale;
  44322. if (e.preventDefault) {
  44323. if (!noPreventDefault) {
  44324. e.stopPropagation();
  44325. e.preventDefault();
  44326. }
  44327. }
  44328. };
  44329. element.addEventListener("mousemove", this._onMouseMove, false);
  44330. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44331. element.addEventListener("MSGestureChange", this._onGesture, false);
  44332. BABYLON.Tools.RegisterTopRootEvents([
  44333. { name: "blur", handler: this._onLostFocus }
  44334. ]);
  44335. };
  44336. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44337. if (this._onLostFocus) {
  44338. BABYLON.Tools.UnregisterTopRootEvents([
  44339. { name: "blur", handler: this._onLostFocus }
  44340. ]);
  44341. }
  44342. if (element && this._observer) {
  44343. this.camera.getScene().onPointerObservable.remove(this._observer);
  44344. this._observer = null;
  44345. if (this._onContextMenu) {
  44346. element.removeEventListener("contextmenu", this._onContextMenu);
  44347. }
  44348. if (this._onMouseMove) {
  44349. element.removeEventListener("mousemove", this._onMouseMove);
  44350. }
  44351. if (this._onGestureStart) {
  44352. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44353. }
  44354. if (this._onGesture) {
  44355. element.removeEventListener("MSGestureChange", this._onGesture);
  44356. }
  44357. this._isPanClick = false;
  44358. this.pinchInwards = true;
  44359. this._onMouseMove = null;
  44360. this._onGestureStart = null;
  44361. this._onGesture = null;
  44362. this._MSGestureHandler = null;
  44363. this._onLostFocus = null;
  44364. this._onContextMenu = null;
  44365. }
  44366. };
  44367. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44368. return "ArcRotateCameraPointersInput";
  44369. };
  44370. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44371. return "pointers";
  44372. };
  44373. __decorate([
  44374. BABYLON.serialize()
  44375. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44376. __decorate([
  44377. BABYLON.serialize()
  44378. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44379. __decorate([
  44380. BABYLON.serialize()
  44381. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44382. __decorate([
  44383. BABYLON.serialize()
  44384. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44385. __decorate([
  44386. BABYLON.serialize()
  44387. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44388. __decorate([
  44389. BABYLON.serialize()
  44390. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44391. __decorate([
  44392. BABYLON.serialize()
  44393. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44394. __decorate([
  44395. BABYLON.serialize()
  44396. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44397. return ArcRotateCameraPointersInput;
  44398. }());
  44399. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44400. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44401. })(BABYLON || (BABYLON = {}));
  44402. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44403. var BABYLON;
  44404. (function (BABYLON) {
  44405. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44406. __extends(ArcRotateCameraInputsManager, _super);
  44407. function ArcRotateCameraInputsManager(camera) {
  44408. return _super.call(this, camera) || this;
  44409. }
  44410. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44411. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44412. return this;
  44413. };
  44414. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44415. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44416. return this;
  44417. };
  44418. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44419. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44420. return this;
  44421. };
  44422. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44423. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44424. return this;
  44425. };
  44426. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44427. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44428. return this;
  44429. };
  44430. return ArcRotateCameraInputsManager;
  44431. }(BABYLON.CameraInputsManager));
  44432. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44433. })(BABYLON || (BABYLON = {}));
  44434. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44435. var BABYLON;
  44436. (function (BABYLON) {
  44437. var ArcRotateCamera = /** @class */ (function (_super) {
  44438. __extends(ArcRotateCamera, _super);
  44439. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44440. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44441. _this.inertialAlphaOffset = 0;
  44442. _this.inertialBetaOffset = 0;
  44443. _this.inertialRadiusOffset = 0;
  44444. _this.lowerAlphaLimit = null;
  44445. _this.upperAlphaLimit = null;
  44446. _this.lowerBetaLimit = 0.01;
  44447. _this.upperBetaLimit = Math.PI;
  44448. _this.lowerRadiusLimit = null;
  44449. _this.upperRadiusLimit = null;
  44450. _this.inertialPanningX = 0;
  44451. _this.inertialPanningY = 0;
  44452. _this.pinchToPanMaxDistance = 20;
  44453. _this.panningDistanceLimit = null;
  44454. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44455. _this.panningInertia = 0.9;
  44456. //-- end properties for backward compatibility for inputs
  44457. _this.zoomOnFactor = 1;
  44458. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44459. _this.allowUpsideDown = true;
  44460. _this._viewMatrix = new BABYLON.Matrix();
  44461. // Panning
  44462. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44463. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44464. _this.checkCollisions = false;
  44465. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44466. _this._previousPosition = BABYLON.Vector3.Zero();
  44467. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44468. _this._newPosition = BABYLON.Vector3.Zero();
  44469. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44470. if (collidedMesh === void 0) { collidedMesh = null; }
  44471. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44472. newPosition.multiplyInPlace(_this._collider._radius);
  44473. }
  44474. if (!collidedMesh) {
  44475. _this._previousPosition.copyFrom(_this.position);
  44476. }
  44477. else {
  44478. _this.setPosition(newPosition);
  44479. if (_this.onCollide) {
  44480. _this.onCollide(collidedMesh);
  44481. }
  44482. }
  44483. // Recompute because of constraints
  44484. var cosa = Math.cos(_this.alpha);
  44485. var sina = Math.sin(_this.alpha);
  44486. var cosb = Math.cos(_this.beta);
  44487. var sinb = Math.sin(_this.beta);
  44488. if (sinb === 0) {
  44489. sinb = 0.0001;
  44490. }
  44491. var target = _this._getTargetPosition();
  44492. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  44493. _this.position.copyFrom(_this._newPosition);
  44494. var up = _this.upVector;
  44495. if (_this.allowUpsideDown && _this.beta < 0) {
  44496. up = up.clone();
  44497. up = up.negate();
  44498. }
  44499. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44500. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44501. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44502. _this._collisionTriggered = false;
  44503. };
  44504. _this._target = BABYLON.Vector3.Zero();
  44505. if (target) {
  44506. _this.setTarget(target);
  44507. }
  44508. _this.alpha = alpha;
  44509. _this.beta = beta;
  44510. _this.radius = radius;
  44511. _this.getViewMatrix();
  44512. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44513. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44514. return _this;
  44515. }
  44516. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44517. get: function () {
  44518. return this._target;
  44519. },
  44520. set: function (value) {
  44521. this.setTarget(value);
  44522. },
  44523. enumerable: true,
  44524. configurable: true
  44525. });
  44526. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44527. //-- begin properties for backward compatibility for inputs
  44528. get: function () {
  44529. var pointers = this.inputs.attached["pointers"];
  44530. if (pointers)
  44531. return pointers.angularSensibilityX;
  44532. return 0;
  44533. },
  44534. set: function (value) {
  44535. var pointers = this.inputs.attached["pointers"];
  44536. if (pointers) {
  44537. pointers.angularSensibilityX = value;
  44538. }
  44539. },
  44540. enumerable: true,
  44541. configurable: true
  44542. });
  44543. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44544. get: function () {
  44545. var pointers = this.inputs.attached["pointers"];
  44546. if (pointers)
  44547. return pointers.angularSensibilityY;
  44548. return 0;
  44549. },
  44550. set: function (value) {
  44551. var pointers = this.inputs.attached["pointers"];
  44552. if (pointers) {
  44553. pointers.angularSensibilityY = value;
  44554. }
  44555. },
  44556. enumerable: true,
  44557. configurable: true
  44558. });
  44559. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44560. get: function () {
  44561. var pointers = this.inputs.attached["pointers"];
  44562. if (pointers)
  44563. return pointers.pinchPrecision;
  44564. return 0;
  44565. },
  44566. set: function (value) {
  44567. var pointers = this.inputs.attached["pointers"];
  44568. if (pointers) {
  44569. pointers.pinchPrecision = value;
  44570. }
  44571. },
  44572. enumerable: true,
  44573. configurable: true
  44574. });
  44575. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44576. get: function () {
  44577. var pointers = this.inputs.attached["pointers"];
  44578. if (pointers)
  44579. return pointers.pinchDeltaPercentage;
  44580. return 0;
  44581. },
  44582. set: function (value) {
  44583. var pointers = this.inputs.attached["pointers"];
  44584. if (pointers) {
  44585. pointers.pinchDeltaPercentage = value;
  44586. }
  44587. },
  44588. enumerable: true,
  44589. configurable: true
  44590. });
  44591. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44592. get: function () {
  44593. var pointers = this.inputs.attached["pointers"];
  44594. if (pointers)
  44595. return pointers.panningSensibility;
  44596. return 0;
  44597. },
  44598. set: function (value) {
  44599. var pointers = this.inputs.attached["pointers"];
  44600. if (pointers) {
  44601. pointers.panningSensibility = value;
  44602. }
  44603. },
  44604. enumerable: true,
  44605. configurable: true
  44606. });
  44607. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44608. get: function () {
  44609. var keyboard = this.inputs.attached["keyboard"];
  44610. if (keyboard)
  44611. return keyboard.keysUp;
  44612. return [];
  44613. },
  44614. set: function (value) {
  44615. var keyboard = this.inputs.attached["keyboard"];
  44616. if (keyboard)
  44617. keyboard.keysUp = value;
  44618. },
  44619. enumerable: true,
  44620. configurable: true
  44621. });
  44622. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44623. get: function () {
  44624. var keyboard = this.inputs.attached["keyboard"];
  44625. if (keyboard)
  44626. return keyboard.keysDown;
  44627. return [];
  44628. },
  44629. set: function (value) {
  44630. var keyboard = this.inputs.attached["keyboard"];
  44631. if (keyboard)
  44632. keyboard.keysDown = value;
  44633. },
  44634. enumerable: true,
  44635. configurable: true
  44636. });
  44637. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44638. get: function () {
  44639. var keyboard = this.inputs.attached["keyboard"];
  44640. if (keyboard)
  44641. return keyboard.keysLeft;
  44642. return [];
  44643. },
  44644. set: function (value) {
  44645. var keyboard = this.inputs.attached["keyboard"];
  44646. if (keyboard)
  44647. keyboard.keysLeft = value;
  44648. },
  44649. enumerable: true,
  44650. configurable: true
  44651. });
  44652. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44653. get: function () {
  44654. var keyboard = this.inputs.attached["keyboard"];
  44655. if (keyboard)
  44656. return keyboard.keysRight;
  44657. return [];
  44658. },
  44659. set: function (value) {
  44660. var keyboard = this.inputs.attached["keyboard"];
  44661. if (keyboard)
  44662. keyboard.keysRight = value;
  44663. },
  44664. enumerable: true,
  44665. configurable: true
  44666. });
  44667. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44668. get: function () {
  44669. var mousewheel = this.inputs.attached["mousewheel"];
  44670. if (mousewheel)
  44671. return mousewheel.wheelPrecision;
  44672. return 0;
  44673. },
  44674. set: function (value) {
  44675. var mousewheel = this.inputs.attached["mousewheel"];
  44676. if (mousewheel)
  44677. mousewheel.wheelPrecision = value;
  44678. },
  44679. enumerable: true,
  44680. configurable: true
  44681. });
  44682. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44683. get: function () {
  44684. var mousewheel = this.inputs.attached["mousewheel"];
  44685. if (mousewheel)
  44686. return mousewheel.wheelDeltaPercentage;
  44687. return 0;
  44688. },
  44689. set: function (value) {
  44690. var mousewheel = this.inputs.attached["mousewheel"];
  44691. if (mousewheel)
  44692. mousewheel.wheelDeltaPercentage = value;
  44693. },
  44694. enumerable: true,
  44695. configurable: true
  44696. });
  44697. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44698. get: function () {
  44699. return this._bouncingBehavior;
  44700. },
  44701. enumerable: true,
  44702. configurable: true
  44703. });
  44704. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44705. get: function () {
  44706. return this._bouncingBehavior != null;
  44707. },
  44708. set: function (value) {
  44709. if (value === this.useBouncingBehavior) {
  44710. return;
  44711. }
  44712. if (value) {
  44713. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44714. this.addBehavior(this._bouncingBehavior);
  44715. }
  44716. else if (this._bouncingBehavior) {
  44717. this.removeBehavior(this._bouncingBehavior);
  44718. this._bouncingBehavior = null;
  44719. }
  44720. },
  44721. enumerable: true,
  44722. configurable: true
  44723. });
  44724. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44725. get: function () {
  44726. return this._framingBehavior;
  44727. },
  44728. enumerable: true,
  44729. configurable: true
  44730. });
  44731. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44732. get: function () {
  44733. return this._framingBehavior != null;
  44734. },
  44735. set: function (value) {
  44736. if (value === this.useFramingBehavior) {
  44737. return;
  44738. }
  44739. if (value) {
  44740. this._framingBehavior = new BABYLON.FramingBehavior();
  44741. this.addBehavior(this._framingBehavior);
  44742. }
  44743. else if (this._framingBehavior) {
  44744. this.removeBehavior(this._framingBehavior);
  44745. this._framingBehavior = null;
  44746. }
  44747. },
  44748. enumerable: true,
  44749. configurable: true
  44750. });
  44751. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44752. get: function () {
  44753. return this._autoRotationBehavior;
  44754. },
  44755. enumerable: true,
  44756. configurable: true
  44757. });
  44758. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44759. get: function () {
  44760. return this._autoRotationBehavior != null;
  44761. },
  44762. set: function (value) {
  44763. if (value === this.useAutoRotationBehavior) {
  44764. return;
  44765. }
  44766. if (value) {
  44767. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44768. this.addBehavior(this._autoRotationBehavior);
  44769. }
  44770. else if (this._autoRotationBehavior) {
  44771. this.removeBehavior(this._autoRotationBehavior);
  44772. this._autoRotationBehavior = null;
  44773. }
  44774. },
  44775. enumerable: true,
  44776. configurable: true
  44777. });
  44778. // Cache
  44779. ArcRotateCamera.prototype._initCache = function () {
  44780. _super.prototype._initCache.call(this);
  44781. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44782. this._cache.alpha = undefined;
  44783. this._cache.beta = undefined;
  44784. this._cache.radius = undefined;
  44785. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44786. };
  44787. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44788. if (!ignoreParentClass) {
  44789. _super.prototype._updateCache.call(this);
  44790. }
  44791. this._cache._target.copyFrom(this._getTargetPosition());
  44792. this._cache.alpha = this.alpha;
  44793. this._cache.beta = this.beta;
  44794. this._cache.radius = this.radius;
  44795. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44796. };
  44797. ArcRotateCamera.prototype._getTargetPosition = function () {
  44798. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44799. var pos = this._targetHost.getAbsolutePosition();
  44800. if (this._targetBoundingCenter) {
  44801. pos.addToRef(this._targetBoundingCenter, this._target);
  44802. }
  44803. else {
  44804. this._target.copyFrom(pos);
  44805. }
  44806. }
  44807. var lockedTargetPosition = this._getLockedTargetPosition();
  44808. if (lockedTargetPosition) {
  44809. return lockedTargetPosition;
  44810. }
  44811. return this._target;
  44812. };
  44813. ArcRotateCamera.prototype.storeState = function () {
  44814. this._storedAlpha = this.alpha;
  44815. this._storedBeta = this.beta;
  44816. this._storedRadius = this.radius;
  44817. this._storedTarget = this._getTargetPosition().clone();
  44818. return _super.prototype.storeState.call(this);
  44819. };
  44820. /**
  44821. * Restored camera state. You must call storeState() first
  44822. */
  44823. ArcRotateCamera.prototype._restoreStateValues = function () {
  44824. if (!_super.prototype._restoreStateValues.call(this)) {
  44825. return false;
  44826. }
  44827. this.alpha = this._storedAlpha;
  44828. this.beta = this._storedBeta;
  44829. this.radius = this._storedRadius;
  44830. this.setTarget(this._storedTarget.clone());
  44831. this.inertialAlphaOffset = 0;
  44832. this.inertialBetaOffset = 0;
  44833. this.inertialRadiusOffset = 0;
  44834. this.inertialPanningX = 0;
  44835. this.inertialPanningY = 0;
  44836. return true;
  44837. };
  44838. // Synchronized
  44839. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44840. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44841. return false;
  44842. return this._cache._target.equals(this._getTargetPosition())
  44843. && this._cache.alpha === this.alpha
  44844. && this._cache.beta === this.beta
  44845. && this._cache.radius === this.radius
  44846. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44847. };
  44848. // Methods
  44849. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44850. var _this = this;
  44851. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44852. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44853. this._useCtrlForPanning = useCtrlForPanning;
  44854. this._panningMouseButton = panningMouseButton;
  44855. this.inputs.attachElement(element, noPreventDefault);
  44856. this._reset = function () {
  44857. _this.inertialAlphaOffset = 0;
  44858. _this.inertialBetaOffset = 0;
  44859. _this.inertialRadiusOffset = 0;
  44860. _this.inertialPanningX = 0;
  44861. _this.inertialPanningY = 0;
  44862. };
  44863. };
  44864. ArcRotateCamera.prototype.detachControl = function (element) {
  44865. this.inputs.detachElement(element);
  44866. if (this._reset) {
  44867. this._reset();
  44868. }
  44869. };
  44870. ArcRotateCamera.prototype._checkInputs = function () {
  44871. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44872. if (this._collisionTriggered) {
  44873. return;
  44874. }
  44875. this.inputs.checkInputs();
  44876. // Inertia
  44877. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44878. if (this.getScene().useRightHandedSystem) {
  44879. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44880. }
  44881. else {
  44882. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44883. }
  44884. this.beta += this.inertialBetaOffset;
  44885. this.radius -= this.inertialRadiusOffset;
  44886. this.inertialAlphaOffset *= this.inertia;
  44887. this.inertialBetaOffset *= this.inertia;
  44888. this.inertialRadiusOffset *= this.inertia;
  44889. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44890. this.inertialAlphaOffset = 0;
  44891. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44892. this.inertialBetaOffset = 0;
  44893. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44894. this.inertialRadiusOffset = 0;
  44895. }
  44896. // Panning inertia
  44897. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44898. if (!this._localDirection) {
  44899. this._localDirection = BABYLON.Vector3.Zero();
  44900. this._transformedDirection = BABYLON.Vector3.Zero();
  44901. }
  44902. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44903. this._localDirection.multiplyInPlace(this.panningAxis);
  44904. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44905. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44906. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44907. if (!this.panningAxis.y) {
  44908. this._transformedDirection.y = 0;
  44909. }
  44910. if (!this._targetHost) {
  44911. if (this.panningDistanceLimit) {
  44912. this._transformedDirection.addInPlace(this._target);
  44913. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44914. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44915. this._target.copyFrom(this._transformedDirection);
  44916. }
  44917. }
  44918. else {
  44919. this._target.addInPlace(this._transformedDirection);
  44920. }
  44921. }
  44922. this.inertialPanningX *= this.panningInertia;
  44923. this.inertialPanningY *= this.panningInertia;
  44924. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44925. this.inertialPanningX = 0;
  44926. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44927. this.inertialPanningY = 0;
  44928. }
  44929. // Limits
  44930. this._checkLimits();
  44931. _super.prototype._checkInputs.call(this);
  44932. };
  44933. ArcRotateCamera.prototype._checkLimits = function () {
  44934. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44935. if (this.allowUpsideDown && this.beta > Math.PI) {
  44936. this.beta = this.beta - (2 * Math.PI);
  44937. }
  44938. }
  44939. else {
  44940. if (this.beta < this.lowerBetaLimit) {
  44941. this.beta = this.lowerBetaLimit;
  44942. }
  44943. }
  44944. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44945. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44946. this.beta = this.beta + (2 * Math.PI);
  44947. }
  44948. }
  44949. else {
  44950. if (this.beta > this.upperBetaLimit) {
  44951. this.beta = this.upperBetaLimit;
  44952. }
  44953. }
  44954. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44955. this.alpha = this.lowerAlphaLimit;
  44956. }
  44957. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44958. this.alpha = this.upperAlphaLimit;
  44959. }
  44960. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44961. this.radius = this.lowerRadiusLimit;
  44962. }
  44963. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44964. this.radius = this.upperRadiusLimit;
  44965. }
  44966. };
  44967. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44968. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44969. this.radius = radiusv3.length();
  44970. if (this.radius === 0) {
  44971. this.radius = 0.0001; // Just to avoid division by zero
  44972. }
  44973. // Alpha
  44974. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44975. if (radiusv3.z < 0) {
  44976. this.alpha = 2 * Math.PI - this.alpha;
  44977. }
  44978. // Beta
  44979. this.beta = Math.acos(radiusv3.y / this.radius);
  44980. this._checkLimits();
  44981. };
  44982. ArcRotateCamera.prototype.setPosition = function (position) {
  44983. if (this.position.equals(position)) {
  44984. return;
  44985. }
  44986. this.position.copyFrom(position);
  44987. this.rebuildAnglesAndRadius();
  44988. };
  44989. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44990. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44991. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44992. if (target.getBoundingInfo) {
  44993. if (toBoundingCenter) {
  44994. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44995. }
  44996. else {
  44997. this._targetBoundingCenter = null;
  44998. }
  44999. this._targetHost = target;
  45000. this._target = this._getTargetPosition();
  45001. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45002. }
  45003. else {
  45004. var newTarget = target;
  45005. var currentTarget = this._getTargetPosition();
  45006. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45007. return;
  45008. }
  45009. this._targetHost = null;
  45010. this._target = newTarget;
  45011. this._targetBoundingCenter = null;
  45012. this.onMeshTargetChangedObservable.notifyObservers(null);
  45013. }
  45014. this.rebuildAnglesAndRadius();
  45015. };
  45016. ArcRotateCamera.prototype._getViewMatrix = function () {
  45017. // Compute
  45018. var cosa = Math.cos(this.alpha);
  45019. var sina = Math.sin(this.alpha);
  45020. var cosb = Math.cos(this.beta);
  45021. var sinb = Math.sin(this.beta);
  45022. if (sinb === 0) {
  45023. sinb = 0.0001;
  45024. }
  45025. var target = this._getTargetPosition();
  45026. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  45027. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45028. if (!this._collider) {
  45029. this._collider = new BABYLON.Collider();
  45030. }
  45031. this._collider._radius = this.collisionRadius;
  45032. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45033. this._collisionTriggered = true;
  45034. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45035. }
  45036. else {
  45037. this.position.copyFrom(this._newPosition);
  45038. var up = this.upVector;
  45039. if (this.allowUpsideDown && sinb < 0) {
  45040. up = up.clone();
  45041. up = up.negate();
  45042. }
  45043. if (this.getScene().useRightHandedSystem) {
  45044. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45045. }
  45046. else {
  45047. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45048. }
  45049. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45050. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45051. }
  45052. this._currentTarget = target;
  45053. return this._viewMatrix;
  45054. };
  45055. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45056. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45057. meshes = meshes || this.getScene().meshes;
  45058. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45059. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45060. this.radius = distance * this.zoomOnFactor;
  45061. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45062. };
  45063. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45064. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45065. var meshesOrMinMaxVector;
  45066. var distance;
  45067. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45068. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45069. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45070. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45071. }
  45072. else {
  45073. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45074. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45075. distance = minMaxVectorAndDistance.distance;
  45076. }
  45077. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45078. if (!doNotUpdateMaxZ) {
  45079. this.maxZ = distance * 2;
  45080. }
  45081. };
  45082. /**
  45083. * @override
  45084. * Override Camera.createRigCamera
  45085. */
  45086. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45087. var alphaShift = 0;
  45088. switch (this.cameraRigMode) {
  45089. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45090. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45091. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45092. case BABYLON.Camera.RIG_MODE_VR:
  45093. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45094. break;
  45095. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45096. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45097. break;
  45098. }
  45099. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45100. rigCam._cameraRigParams = {};
  45101. return rigCam;
  45102. };
  45103. /**
  45104. * @override
  45105. * Override Camera._updateRigCameras
  45106. */
  45107. ArcRotateCamera.prototype._updateRigCameras = function () {
  45108. var camLeft = this._rigCameras[0];
  45109. var camRight = this._rigCameras[1];
  45110. camLeft.beta = camRight.beta = this.beta;
  45111. camLeft.radius = camRight.radius = this.radius;
  45112. switch (this.cameraRigMode) {
  45113. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45114. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45115. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45116. case BABYLON.Camera.RIG_MODE_VR:
  45117. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45118. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45119. break;
  45120. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45121. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45122. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45123. break;
  45124. }
  45125. _super.prototype._updateRigCameras.call(this);
  45126. };
  45127. ArcRotateCamera.prototype.dispose = function () {
  45128. this.inputs.clear();
  45129. _super.prototype.dispose.call(this);
  45130. };
  45131. ArcRotateCamera.prototype.getClassName = function () {
  45132. return "ArcRotateCamera";
  45133. };
  45134. __decorate([
  45135. BABYLON.serialize()
  45136. ], ArcRotateCamera.prototype, "alpha", void 0);
  45137. __decorate([
  45138. BABYLON.serialize()
  45139. ], ArcRotateCamera.prototype, "beta", void 0);
  45140. __decorate([
  45141. BABYLON.serialize()
  45142. ], ArcRotateCamera.prototype, "radius", void 0);
  45143. __decorate([
  45144. BABYLON.serializeAsVector3("target")
  45145. ], ArcRotateCamera.prototype, "_target", void 0);
  45146. __decorate([
  45147. BABYLON.serialize()
  45148. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45149. __decorate([
  45150. BABYLON.serialize()
  45151. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45152. __decorate([
  45153. BABYLON.serialize()
  45154. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45155. __decorate([
  45156. BABYLON.serialize()
  45157. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45158. __decorate([
  45159. BABYLON.serialize()
  45160. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45161. __decorate([
  45162. BABYLON.serialize()
  45163. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45164. __decorate([
  45165. BABYLON.serialize()
  45166. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45167. __decorate([
  45168. BABYLON.serialize()
  45169. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45170. __decorate([
  45171. BABYLON.serialize()
  45172. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45173. __decorate([
  45174. BABYLON.serialize()
  45175. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45176. __decorate([
  45177. BABYLON.serialize()
  45178. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45179. __decorate([
  45180. BABYLON.serialize()
  45181. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45182. __decorate([
  45183. BABYLON.serialize()
  45184. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45185. __decorate([
  45186. BABYLON.serializeAsVector3()
  45187. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45188. __decorate([
  45189. BABYLON.serialize()
  45190. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45191. __decorate([
  45192. BABYLON.serialize()
  45193. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45194. __decorate([
  45195. BABYLON.serialize()
  45196. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45197. return ArcRotateCamera;
  45198. }(BABYLON.TargetCamera));
  45199. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45200. })(BABYLON || (BABYLON = {}));
  45201. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45202. var BABYLON;
  45203. (function (BABYLON) {
  45204. /**
  45205. * The HemisphericLight simulates the ambient environment light,
  45206. * so the passed direction is the light reflection direction, not the incoming direction.
  45207. */
  45208. var HemisphericLight = /** @class */ (function (_super) {
  45209. __extends(HemisphericLight, _super);
  45210. /**
  45211. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45212. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45213. * The HemisphericLight can't cast shadows.
  45214. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45215. * @param name The friendly name of the light
  45216. * @param direction The direction of the light reflection
  45217. * @param scene The scene the light belongs to
  45218. */
  45219. function HemisphericLight(name, direction, scene) {
  45220. var _this = _super.call(this, name, scene) || this;
  45221. /**
  45222. * The groundColor is the light in the opposite direction to the one specified during creation.
  45223. * 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.
  45224. */
  45225. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45226. _this.direction = direction || BABYLON.Vector3.Up();
  45227. return _this;
  45228. }
  45229. HemisphericLight.prototype._buildUniformLayout = function () {
  45230. this._uniformBuffer.addUniform("vLightData", 4);
  45231. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45232. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45233. this._uniformBuffer.addUniform("vLightGround", 3);
  45234. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45235. this._uniformBuffer.addUniform("depthValues", 2);
  45236. this._uniformBuffer.create();
  45237. };
  45238. /**
  45239. * Returns the string "HemisphericLight".
  45240. * @return The class name
  45241. */
  45242. HemisphericLight.prototype.getClassName = function () {
  45243. return "HemisphericLight";
  45244. };
  45245. /**
  45246. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45247. * Returns the updated direction.
  45248. * @param target The target the direction should point to
  45249. * @return The computed direction
  45250. */
  45251. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45252. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45253. return this.direction;
  45254. };
  45255. /**
  45256. * Returns the shadow generator associated to the light.
  45257. * @returns Always null for hemispheric lights because it does not support shadows.
  45258. */
  45259. HemisphericLight.prototype.getShadowGenerator = function () {
  45260. return null;
  45261. };
  45262. /**
  45263. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45264. * @param effect The effect to update
  45265. * @param lightIndex The index of the light in the effect to update
  45266. * @returns The hemispheric light
  45267. */
  45268. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45269. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45270. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45271. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45272. return this;
  45273. };
  45274. /**
  45275. * @ignore internal use only.
  45276. */
  45277. HemisphericLight.prototype._getWorldMatrix = function () {
  45278. if (!this._worldMatrix) {
  45279. this._worldMatrix = BABYLON.Matrix.Identity();
  45280. }
  45281. return this._worldMatrix;
  45282. };
  45283. /**
  45284. * Returns the integer 3.
  45285. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45286. */
  45287. HemisphericLight.prototype.getTypeID = function () {
  45288. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45289. };
  45290. __decorate([
  45291. BABYLON.serializeAsColor3()
  45292. ], HemisphericLight.prototype, "groundColor", void 0);
  45293. __decorate([
  45294. BABYLON.serializeAsVector3()
  45295. ], HemisphericLight.prototype, "direction", void 0);
  45296. return HemisphericLight;
  45297. }(BABYLON.Light));
  45298. BABYLON.HemisphericLight = HemisphericLight;
  45299. })(BABYLON || (BABYLON = {}));
  45300. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45301. var BABYLON;
  45302. (function (BABYLON) {
  45303. /**
  45304. * Base implementation of @see IShadowLight
  45305. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45306. */
  45307. var ShadowLight = /** @class */ (function (_super) {
  45308. __extends(ShadowLight, _super);
  45309. function ShadowLight() {
  45310. var _this = _super !== null && _super.apply(this, arguments) || this;
  45311. _this._needProjectionMatrixCompute = true;
  45312. return _this;
  45313. }
  45314. ShadowLight.prototype._setPosition = function (value) {
  45315. this._position = value;
  45316. };
  45317. Object.defineProperty(ShadowLight.prototype, "position", {
  45318. /**
  45319. * Sets the position the shadow will be casted from. Also use as the light position for both
  45320. * point and spot lights.
  45321. */
  45322. get: function () {
  45323. return this._position;
  45324. },
  45325. /**
  45326. * Sets the position the shadow will be casted from. Also use as the light position for both
  45327. * point and spot lights.
  45328. */
  45329. set: function (value) {
  45330. this._setPosition(value);
  45331. },
  45332. enumerable: true,
  45333. configurable: true
  45334. });
  45335. ShadowLight.prototype._setDirection = function (value) {
  45336. this._direction = value;
  45337. };
  45338. Object.defineProperty(ShadowLight.prototype, "direction", {
  45339. /**
  45340. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45341. * Also use as the light direction on spot and directional lights.
  45342. */
  45343. get: function () {
  45344. return this._direction;
  45345. },
  45346. /**
  45347. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45348. * Also use as the light direction on spot and directional lights.
  45349. */
  45350. set: function (value) {
  45351. this._setDirection(value);
  45352. },
  45353. enumerable: true,
  45354. configurable: true
  45355. });
  45356. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45357. /**
  45358. * Gets the shadow projection clipping minimum z value.
  45359. */
  45360. get: function () {
  45361. return this._shadowMinZ;
  45362. },
  45363. /**
  45364. * Sets the shadow projection clipping minimum z value.
  45365. */
  45366. set: function (value) {
  45367. this._shadowMinZ = value;
  45368. this.forceProjectionMatrixCompute();
  45369. },
  45370. enumerable: true,
  45371. configurable: true
  45372. });
  45373. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45374. /**
  45375. * Sets the shadow projection clipping maximum z value.
  45376. */
  45377. get: function () {
  45378. return this._shadowMaxZ;
  45379. },
  45380. /**
  45381. * Gets the shadow projection clipping maximum z value.
  45382. */
  45383. set: function (value) {
  45384. this._shadowMaxZ = value;
  45385. this.forceProjectionMatrixCompute();
  45386. },
  45387. enumerable: true,
  45388. configurable: true
  45389. });
  45390. /**
  45391. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45392. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45393. */
  45394. ShadowLight.prototype.computeTransformedInformation = function () {
  45395. if (this.parent && this.parent.getWorldMatrix) {
  45396. if (!this.transformedPosition) {
  45397. this.transformedPosition = BABYLON.Vector3.Zero();
  45398. }
  45399. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45400. // In case the direction is present.
  45401. if (this.direction) {
  45402. if (!this.transformedDirection) {
  45403. this.transformedDirection = BABYLON.Vector3.Zero();
  45404. }
  45405. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45406. }
  45407. return true;
  45408. }
  45409. return false;
  45410. };
  45411. /**
  45412. * Return the depth scale used for the shadow map.
  45413. * @returns the depth scale.
  45414. */
  45415. ShadowLight.prototype.getDepthScale = function () {
  45416. return 50.0;
  45417. };
  45418. /**
  45419. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45420. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45421. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45422. */
  45423. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45424. return this.transformedDirection ? this.transformedDirection : this.direction;
  45425. };
  45426. /**
  45427. * Returns the ShadowLight absolute position in the World.
  45428. * @returns the position vector in world space
  45429. */
  45430. ShadowLight.prototype.getAbsolutePosition = function () {
  45431. return this.transformedPosition ? this.transformedPosition : this.position;
  45432. };
  45433. /**
  45434. * Sets the ShadowLight direction toward the passed target.
  45435. * @param target The point tot target in local space
  45436. * @returns the updated ShadowLight direction
  45437. */
  45438. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45439. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45440. return this.direction;
  45441. };
  45442. /**
  45443. * Returns the light rotation in euler definition.
  45444. * @returns the x y z rotation in local space.
  45445. */
  45446. ShadowLight.prototype.getRotation = function () {
  45447. this.direction.normalize();
  45448. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45449. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45450. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45451. };
  45452. /**
  45453. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45454. * @returns true if a cube texture needs to be use
  45455. */
  45456. ShadowLight.prototype.needCube = function () {
  45457. return false;
  45458. };
  45459. /**
  45460. * Detects if the projection matrix requires to be recomputed this frame.
  45461. * @returns true if it requires to be recomputed otherwise, false.
  45462. */
  45463. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45464. return this._needProjectionMatrixCompute;
  45465. };
  45466. /**
  45467. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45468. */
  45469. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45470. this._needProjectionMatrixCompute = true;
  45471. };
  45472. /**
  45473. * Get the world matrix of the sahdow lights.
  45474. * @ignore Internal Use Only
  45475. */
  45476. ShadowLight.prototype._getWorldMatrix = function () {
  45477. if (!this._worldMatrix) {
  45478. this._worldMatrix = BABYLON.Matrix.Identity();
  45479. }
  45480. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45481. return this._worldMatrix;
  45482. };
  45483. /**
  45484. * Gets the minZ used for shadow according to both the scene and the light.
  45485. * @param activeCamera The camera we are returning the min for
  45486. * @returns the depth min z
  45487. */
  45488. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45489. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45490. };
  45491. /**
  45492. * Gets the maxZ used for shadow according to both the scene and the light.
  45493. * @param activeCamera The camera we are returning the max for
  45494. * @returns the depth max z
  45495. */
  45496. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45497. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45498. };
  45499. /**
  45500. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45501. * @param matrix The materix to updated with the projection information
  45502. * @param viewMatrix The transform matrix of the light
  45503. * @param renderList The list of mesh to render in the map
  45504. * @returns The current light
  45505. */
  45506. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45507. if (this.customProjectionMatrixBuilder) {
  45508. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45509. }
  45510. else {
  45511. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45512. }
  45513. return this;
  45514. };
  45515. __decorate([
  45516. BABYLON.serializeAsVector3()
  45517. ], ShadowLight.prototype, "position", null);
  45518. __decorate([
  45519. BABYLON.serializeAsVector3()
  45520. ], ShadowLight.prototype, "direction", null);
  45521. __decorate([
  45522. BABYLON.serialize()
  45523. ], ShadowLight.prototype, "shadowMinZ", null);
  45524. __decorate([
  45525. BABYLON.serialize()
  45526. ], ShadowLight.prototype, "shadowMaxZ", null);
  45527. return ShadowLight;
  45528. }(BABYLON.Light));
  45529. BABYLON.ShadowLight = ShadowLight;
  45530. })(BABYLON || (BABYLON = {}));
  45531. //# sourceMappingURL=babylon.shadowLight.js.map
  45532. var BABYLON;
  45533. (function (BABYLON) {
  45534. /**
  45535. * A point light is a light defined by an unique point in world space.
  45536. * The light is emitted in every direction from this point.
  45537. * A good example of a point light is a standard light bulb.
  45538. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45539. */
  45540. var PointLight = /** @class */ (function (_super) {
  45541. __extends(PointLight, _super);
  45542. /**
  45543. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45544. * A PointLight emits the light in every direction.
  45545. * It can cast shadows.
  45546. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45547. * ```javascript
  45548. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45549. * ```
  45550. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45551. * @param name The light friendly name
  45552. * @param position The position of the point light in the scene
  45553. * @param scene The scene the lights belongs to
  45554. */
  45555. function PointLight(name, position, scene) {
  45556. var _this = _super.call(this, name, scene) || this;
  45557. _this._shadowAngle = Math.PI / 2;
  45558. _this.position = position;
  45559. return _this;
  45560. }
  45561. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45562. /**
  45563. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45564. * This specifies what angle the shadow will use to be created.
  45565. *
  45566. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45567. */
  45568. get: function () {
  45569. return this._shadowAngle;
  45570. },
  45571. /**
  45572. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45573. * This specifies what angle the shadow will use to be created.
  45574. *
  45575. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45576. */
  45577. set: function (value) {
  45578. this._shadowAngle = value;
  45579. this.forceProjectionMatrixCompute();
  45580. },
  45581. enumerable: true,
  45582. configurable: true
  45583. });
  45584. Object.defineProperty(PointLight.prototype, "direction", {
  45585. /**
  45586. * Gets the direction if it has been set.
  45587. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45588. */
  45589. get: function () {
  45590. return this._direction;
  45591. },
  45592. /**
  45593. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45594. */
  45595. set: function (value) {
  45596. var previousNeedCube = this.needCube();
  45597. this._direction = value;
  45598. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45599. this._shadowGenerator.recreateShadowMap();
  45600. }
  45601. },
  45602. enumerable: true,
  45603. configurable: true
  45604. });
  45605. /**
  45606. * Returns the string "PointLight"
  45607. * @returns the class name
  45608. */
  45609. PointLight.prototype.getClassName = function () {
  45610. return "PointLight";
  45611. };
  45612. /**
  45613. * Returns the integer 0.
  45614. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45615. */
  45616. PointLight.prototype.getTypeID = function () {
  45617. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45618. };
  45619. /**
  45620. * Specifies wether or not the shadowmap should be a cube texture.
  45621. * @returns true if the shadowmap needs to be a cube texture.
  45622. */
  45623. PointLight.prototype.needCube = function () {
  45624. return !this.direction;
  45625. };
  45626. /**
  45627. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45628. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45629. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45630. */
  45631. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45632. if (this.direction) {
  45633. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45634. }
  45635. else {
  45636. switch (faceIndex) {
  45637. case 0:
  45638. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45639. case 1:
  45640. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45641. case 2:
  45642. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45643. case 3:
  45644. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45645. case 4:
  45646. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45647. case 5:
  45648. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45649. }
  45650. }
  45651. return BABYLON.Vector3.Zero();
  45652. };
  45653. /**
  45654. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45655. * - fov = PI / 2
  45656. * - aspect ratio : 1.0
  45657. * - z-near and far equal to the active camera minZ and maxZ.
  45658. * Returns the PointLight.
  45659. */
  45660. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45661. var activeCamera = this.getScene().activeCamera;
  45662. if (!activeCamera) {
  45663. return;
  45664. }
  45665. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45666. };
  45667. PointLight.prototype._buildUniformLayout = function () {
  45668. this._uniformBuffer.addUniform("vLightData", 4);
  45669. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45670. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45671. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45672. this._uniformBuffer.addUniform("depthValues", 2);
  45673. this._uniformBuffer.create();
  45674. };
  45675. /**
  45676. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45677. * @param effect The effect to update
  45678. * @param lightIndex The index of the light in the effect to update
  45679. * @returns The point light
  45680. */
  45681. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45682. if (this.computeTransformedInformation()) {
  45683. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45684. return this;
  45685. }
  45686. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45687. return this;
  45688. };
  45689. __decorate([
  45690. BABYLON.serialize()
  45691. ], PointLight.prototype, "shadowAngle", null);
  45692. return PointLight;
  45693. }(BABYLON.ShadowLight));
  45694. BABYLON.PointLight = PointLight;
  45695. })(BABYLON || (BABYLON = {}));
  45696. //# sourceMappingURL=babylon.pointLight.js.map
  45697. var BABYLON;
  45698. (function (BABYLON) {
  45699. /**
  45700. * A directional light is defined by a direction (what a surprise!).
  45701. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45702. * 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.
  45703. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45704. */
  45705. var DirectionalLight = /** @class */ (function (_super) {
  45706. __extends(DirectionalLight, _super);
  45707. /**
  45708. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45709. * The directional light is emitted from everywhere in the given direction.
  45710. * It can cast shawdows.
  45711. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45712. * @param name The friendly name of the light
  45713. * @param direction The direction of the light
  45714. * @param scene The scene the light belongs to
  45715. */
  45716. function DirectionalLight(name, direction, scene) {
  45717. var _this = _super.call(this, name, scene) || this;
  45718. _this._shadowFrustumSize = 0;
  45719. _this._shadowOrthoScale = 0.5;
  45720. /**
  45721. * Automatically compute the projection matrix to best fit (including all the casters)
  45722. * on each frame.
  45723. */
  45724. _this.autoUpdateExtends = true;
  45725. // Cache
  45726. _this._orthoLeft = Number.MAX_VALUE;
  45727. _this._orthoRight = Number.MIN_VALUE;
  45728. _this._orthoTop = Number.MIN_VALUE;
  45729. _this._orthoBottom = Number.MAX_VALUE;
  45730. _this.position = direction.scale(-1.0);
  45731. _this.direction = direction;
  45732. return _this;
  45733. }
  45734. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45735. /**
  45736. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45737. */
  45738. get: function () {
  45739. return this._shadowFrustumSize;
  45740. },
  45741. /**
  45742. * Specifies a fix frustum size for the shadow generation.
  45743. */
  45744. set: function (value) {
  45745. this._shadowFrustumSize = value;
  45746. this.forceProjectionMatrixCompute();
  45747. },
  45748. enumerable: true,
  45749. configurable: true
  45750. });
  45751. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45752. /**
  45753. * Gets the shadow projection scale against the optimal computed one.
  45754. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45755. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45756. */
  45757. get: function () {
  45758. return this._shadowOrthoScale;
  45759. },
  45760. /**
  45761. * Sets the shadow projection scale against the optimal computed one.
  45762. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45763. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45764. */
  45765. set: function (value) {
  45766. this._shadowOrthoScale = value;
  45767. this.forceProjectionMatrixCompute();
  45768. },
  45769. enumerable: true,
  45770. configurable: true
  45771. });
  45772. /**
  45773. * Returns the string "DirectionalLight".
  45774. * @return The class name
  45775. */
  45776. DirectionalLight.prototype.getClassName = function () {
  45777. return "DirectionalLight";
  45778. };
  45779. /**
  45780. * Returns the integer 1.
  45781. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45782. */
  45783. DirectionalLight.prototype.getTypeID = function () {
  45784. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45785. };
  45786. /**
  45787. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45788. * Returns the DirectionalLight Shadow projection matrix.
  45789. */
  45790. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45791. if (this.shadowFrustumSize > 0) {
  45792. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45793. }
  45794. else {
  45795. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45796. }
  45797. };
  45798. /**
  45799. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45800. * Returns the DirectionalLight Shadow projection matrix.
  45801. */
  45802. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45803. var activeCamera = this.getScene().activeCamera;
  45804. if (!activeCamera) {
  45805. return;
  45806. }
  45807. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45808. };
  45809. /**
  45810. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45811. * Returns the DirectionalLight Shadow projection matrix.
  45812. */
  45813. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45814. var activeCamera = this.getScene().activeCamera;
  45815. if (!activeCamera) {
  45816. return;
  45817. }
  45818. // Check extends
  45819. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45820. var tempVector3 = BABYLON.Vector3.Zero();
  45821. this._orthoLeft = Number.MAX_VALUE;
  45822. this._orthoRight = Number.MIN_VALUE;
  45823. this._orthoTop = Number.MIN_VALUE;
  45824. this._orthoBottom = Number.MAX_VALUE;
  45825. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45826. var mesh = renderList[meshIndex];
  45827. if (!mesh) {
  45828. continue;
  45829. }
  45830. var boundingInfo = mesh.getBoundingInfo();
  45831. var boundingBox = boundingInfo.boundingBox;
  45832. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45833. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45834. if (tempVector3.x < this._orthoLeft)
  45835. this._orthoLeft = tempVector3.x;
  45836. if (tempVector3.y < this._orthoBottom)
  45837. this._orthoBottom = tempVector3.y;
  45838. if (tempVector3.x > this._orthoRight)
  45839. this._orthoRight = tempVector3.x;
  45840. if (tempVector3.y > this._orthoTop)
  45841. this._orthoTop = tempVector3.y;
  45842. }
  45843. }
  45844. }
  45845. var xOffset = this._orthoRight - this._orthoLeft;
  45846. var yOffset = this._orthoTop - this._orthoBottom;
  45847. 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);
  45848. };
  45849. DirectionalLight.prototype._buildUniformLayout = function () {
  45850. this._uniformBuffer.addUniform("vLightData", 4);
  45851. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45852. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45853. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45854. this._uniformBuffer.addUniform("depthValues", 2);
  45855. this._uniformBuffer.create();
  45856. };
  45857. /**
  45858. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45859. * @param effect The effect to update
  45860. * @param lightIndex The index of the light in the effect to update
  45861. * @returns The directional light
  45862. */
  45863. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45864. if (this.computeTransformedInformation()) {
  45865. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45866. return this;
  45867. }
  45868. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45869. return this;
  45870. };
  45871. /**
  45872. * Gets the minZ used for shadow according to both the scene and the light.
  45873. *
  45874. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45875. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45876. * @param activeCamera The camera we are returning the min for
  45877. * @returns the depth min z
  45878. */
  45879. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45880. return 1;
  45881. };
  45882. /**
  45883. * Gets the maxZ used for shadow according to both the scene and the light.
  45884. *
  45885. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45886. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45887. * @param activeCamera The camera we are returning the max for
  45888. * @returns the depth max z
  45889. */
  45890. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45891. return 1;
  45892. };
  45893. __decorate([
  45894. BABYLON.serialize()
  45895. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45896. __decorate([
  45897. BABYLON.serialize()
  45898. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45899. __decorate([
  45900. BABYLON.serialize()
  45901. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45902. return DirectionalLight;
  45903. }(BABYLON.ShadowLight));
  45904. BABYLON.DirectionalLight = DirectionalLight;
  45905. })(BABYLON || (BABYLON = {}));
  45906. //# sourceMappingURL=babylon.directionalLight.js.map
  45907. var BABYLON;
  45908. (function (BABYLON) {
  45909. /**
  45910. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45911. * These values define a cone of light starting from the position, emitting toward the direction.
  45912. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45913. * and the exponent defines the speed of the decay of the light with distance (reach).
  45914. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45915. */
  45916. var SpotLight = /** @class */ (function (_super) {
  45917. __extends(SpotLight, _super);
  45918. /**
  45919. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45920. * It can cast shadows.
  45921. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45922. * @param name The light friendly name
  45923. * @param position The position of the spot light in the scene
  45924. * @param direction The direction of the light in the scene
  45925. * @param angle The cone angle of the light in Radians
  45926. * @param exponent The light decay speed with the distance from the emission spot
  45927. * @param scene The scene the lights belongs to
  45928. */
  45929. function SpotLight(name, position, direction, angle, exponent, scene) {
  45930. var _this = _super.call(this, name, scene) || this;
  45931. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45932. _this._projectionTextureLightNear = 1e-6;
  45933. _this._projectionTextureLightFar = 1000.0;
  45934. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45935. _this._projectionTextureViewLightDirty = true;
  45936. _this._projectionTextureProjectionLightDirty = true;
  45937. _this._projectionTextureDirty = true;
  45938. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45939. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45940. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45941. _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);
  45942. _this.position = position;
  45943. _this.direction = direction;
  45944. _this.angle = angle;
  45945. _this.exponent = exponent;
  45946. return _this;
  45947. }
  45948. Object.defineProperty(SpotLight.prototype, "angle", {
  45949. /**
  45950. * Gets the cone angle of the spot light in Radians.
  45951. */
  45952. get: function () {
  45953. return this._angle;
  45954. },
  45955. /**
  45956. * Sets the cone angle of the spot light in Radians.
  45957. */
  45958. set: function (value) {
  45959. this._angle = value;
  45960. this._projectionTextureProjectionLightDirty = true;
  45961. this.forceProjectionMatrixCompute();
  45962. },
  45963. enumerable: true,
  45964. configurable: true
  45965. });
  45966. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45967. /**
  45968. * Allows scaling the angle of the light for shadow generation only.
  45969. */
  45970. get: function () {
  45971. return this._shadowAngleScale;
  45972. },
  45973. /**
  45974. * Allows scaling the angle of the light for shadow generation only.
  45975. */
  45976. set: function (value) {
  45977. this._shadowAngleScale = value;
  45978. this.forceProjectionMatrixCompute();
  45979. },
  45980. enumerable: true,
  45981. configurable: true
  45982. });
  45983. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45984. /**
  45985. * Allows reading the projecton texture
  45986. */
  45987. get: function () {
  45988. return this._projectionTextureMatrix;
  45989. },
  45990. enumerable: true,
  45991. configurable: true
  45992. });
  45993. ;
  45994. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45995. /**
  45996. * Gets the near clip of the Spotlight for texture projection.
  45997. */
  45998. get: function () {
  45999. return this._projectionTextureLightNear;
  46000. },
  46001. /**
  46002. * Sets the near clip of the Spotlight for texture projection.
  46003. */
  46004. set: function (value) {
  46005. this._projectionTextureLightNear = value;
  46006. this._projectionTextureProjectionLightDirty = true;
  46007. },
  46008. enumerable: true,
  46009. configurable: true
  46010. });
  46011. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46012. /**
  46013. * Gets the far clip of the Spotlight for texture projection.
  46014. */
  46015. get: function () {
  46016. return this._projectionTextureLightFar;
  46017. },
  46018. /**
  46019. * Sets the far clip of the Spotlight for texture projection.
  46020. */
  46021. set: function (value) {
  46022. this._projectionTextureLightFar = value;
  46023. this._projectionTextureProjectionLightDirty = true;
  46024. },
  46025. enumerable: true,
  46026. configurable: true
  46027. });
  46028. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46029. /**
  46030. * Gets the Up vector of the Spotlight for texture projection.
  46031. */
  46032. get: function () {
  46033. return this._projectionTextureUpDirection;
  46034. },
  46035. /**
  46036. * Sets the Up vector of the Spotlight for texture projection.
  46037. */
  46038. set: function (value) {
  46039. this._projectionTextureUpDirection = value;
  46040. this._projectionTextureProjectionLightDirty = true;
  46041. },
  46042. enumerable: true,
  46043. configurable: true
  46044. });
  46045. ;
  46046. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46047. /**
  46048. * Gets the projection texture of the light.
  46049. */
  46050. get: function () {
  46051. return this._projectionTexture;
  46052. },
  46053. /**
  46054. * Sets the projection texture of the light.
  46055. */
  46056. set: function (value) {
  46057. this._projectionTexture = value;
  46058. this._projectionTextureDirty = true;
  46059. },
  46060. enumerable: true,
  46061. configurable: true
  46062. });
  46063. /**
  46064. * Returns the string "SpotLight".
  46065. * @returns the class name
  46066. */
  46067. SpotLight.prototype.getClassName = function () {
  46068. return "SpotLight";
  46069. };
  46070. /**
  46071. * Returns the integer 2.
  46072. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46073. */
  46074. SpotLight.prototype.getTypeID = function () {
  46075. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46076. };
  46077. /**
  46078. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46079. */
  46080. SpotLight.prototype._setDirection = function (value) {
  46081. _super.prototype._setDirection.call(this, value);
  46082. this._projectionTextureViewLightDirty = true;
  46083. };
  46084. /**
  46085. * Overrides the position setter to recompute the projection texture view light Matrix.
  46086. */
  46087. SpotLight.prototype._setPosition = function (value) {
  46088. _super.prototype._setPosition.call(this, value);
  46089. this._projectionTextureViewLightDirty = true;
  46090. };
  46091. /**
  46092. * 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.
  46093. * Returns the SpotLight.
  46094. */
  46095. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46096. var activeCamera = this.getScene().activeCamera;
  46097. if (!activeCamera) {
  46098. return;
  46099. }
  46100. this._shadowAngleScale = this._shadowAngleScale || 1;
  46101. var angle = this._shadowAngleScale * this._angle;
  46102. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46103. };
  46104. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46105. this._projectionTextureViewLightDirty = false;
  46106. this._projectionTextureDirty = true;
  46107. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46108. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46109. };
  46110. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46111. this._projectionTextureProjectionLightDirty = false;
  46112. this._projectionTextureDirty = true;
  46113. var light_far = this.projectionTextureLightFar;
  46114. var light_near = this.projectionTextureLightNear;
  46115. var P = light_far / (light_far - light_near);
  46116. var Q = -P * light_near;
  46117. var S = 1.0 / Math.tan(this._angle / 2.0);
  46118. var A = 1.0;
  46119. 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);
  46120. };
  46121. /**
  46122. * Main function for light texture projection matrix computing.
  46123. */
  46124. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46125. this._projectionTextureDirty = false;
  46126. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46127. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46128. };
  46129. SpotLight.prototype._buildUniformLayout = function () {
  46130. this._uniformBuffer.addUniform("vLightData", 4);
  46131. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46132. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46133. this._uniformBuffer.addUniform("vLightDirection", 3);
  46134. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46135. this._uniformBuffer.addUniform("depthValues", 2);
  46136. this._uniformBuffer.create();
  46137. };
  46138. /**
  46139. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46140. * @param effect The effect to update
  46141. * @param lightIndex The index of the light in the effect to update
  46142. * @returns The spot light
  46143. */
  46144. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46145. var normalizeDirection;
  46146. if (this.computeTransformedInformation()) {
  46147. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46148. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46149. }
  46150. else {
  46151. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46152. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46153. }
  46154. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46155. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46156. if (this._projectionTextureViewLightDirty) {
  46157. this._computeProjectionTextureViewLightMatrix();
  46158. }
  46159. if (this._projectionTextureProjectionLightDirty) {
  46160. this._computeProjectionTextureProjectionLightMatrix();
  46161. }
  46162. if (this._projectionTextureDirty) {
  46163. this._computeProjectionTextureMatrix();
  46164. }
  46165. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46166. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46167. }
  46168. return this;
  46169. };
  46170. /**
  46171. * Disposes the light and the associated resources.
  46172. */
  46173. SpotLight.prototype.dispose = function () {
  46174. _super.prototype.dispose.call(this);
  46175. if (this._projectionTexture) {
  46176. this._projectionTexture.dispose();
  46177. }
  46178. };
  46179. __decorate([
  46180. BABYLON.serialize()
  46181. ], SpotLight.prototype, "angle", null);
  46182. __decorate([
  46183. BABYLON.serialize()
  46184. ], SpotLight.prototype, "shadowAngleScale", null);
  46185. __decorate([
  46186. BABYLON.serialize()
  46187. ], SpotLight.prototype, "exponent", void 0);
  46188. __decorate([
  46189. BABYLON.serialize()
  46190. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46191. __decorate([
  46192. BABYLON.serialize()
  46193. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46194. __decorate([
  46195. BABYLON.serialize()
  46196. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46197. __decorate([
  46198. BABYLON.serializeAsTexture("projectedLightTexture")
  46199. ], SpotLight.prototype, "_projectionTexture", void 0);
  46200. return SpotLight;
  46201. }(BABYLON.ShadowLight));
  46202. BABYLON.SpotLight = SpotLight;
  46203. })(BABYLON || (BABYLON = {}));
  46204. //# sourceMappingURL=babylon.spotLight.js.map
  46205. var BABYLON;
  46206. (function (BABYLON) {
  46207. /**
  46208. * Class used to override all child animations of a given target
  46209. */
  46210. var AnimationPropertiesOverride = /** @class */ (function () {
  46211. function AnimationPropertiesOverride() {
  46212. /**
  46213. * Gets or sets a value indicating if animation blending must be used
  46214. */
  46215. this.enableBlending = false;
  46216. /**
  46217. * Gets or sets the blending speed to use when enableBlending is true
  46218. */
  46219. this.blendingSpeed = 0.01;
  46220. /**
  46221. * Gets or sets the default loop mode to use
  46222. */
  46223. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46224. }
  46225. return AnimationPropertiesOverride;
  46226. }());
  46227. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46228. })(BABYLON || (BABYLON = {}));
  46229. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46230. var BABYLON;
  46231. (function (BABYLON) {
  46232. var AnimationRange = /** @class */ (function () {
  46233. function AnimationRange(name, from, to) {
  46234. this.name = name;
  46235. this.from = from;
  46236. this.to = to;
  46237. }
  46238. AnimationRange.prototype.clone = function () {
  46239. return new AnimationRange(this.name, this.from, this.to);
  46240. };
  46241. return AnimationRange;
  46242. }());
  46243. BABYLON.AnimationRange = AnimationRange;
  46244. /**
  46245. * Composed of a frame, and an action function
  46246. */
  46247. var AnimationEvent = /** @class */ (function () {
  46248. function AnimationEvent(frame, action, onlyOnce) {
  46249. this.frame = frame;
  46250. this.action = action;
  46251. this.onlyOnce = onlyOnce;
  46252. this.isDone = false;
  46253. }
  46254. return AnimationEvent;
  46255. }());
  46256. BABYLON.AnimationEvent = AnimationEvent;
  46257. var PathCursor = /** @class */ (function () {
  46258. function PathCursor(path) {
  46259. this.path = path;
  46260. this._onchange = new Array();
  46261. this.value = 0;
  46262. this.animations = new Array();
  46263. }
  46264. PathCursor.prototype.getPoint = function () {
  46265. var point = this.path.getPointAtLengthPosition(this.value);
  46266. return new BABYLON.Vector3(point.x, 0, point.y);
  46267. };
  46268. PathCursor.prototype.moveAhead = function (step) {
  46269. if (step === void 0) { step = 0.002; }
  46270. this.move(step);
  46271. return this;
  46272. };
  46273. PathCursor.prototype.moveBack = function (step) {
  46274. if (step === void 0) { step = 0.002; }
  46275. this.move(-step);
  46276. return this;
  46277. };
  46278. PathCursor.prototype.move = function (step) {
  46279. if (Math.abs(step) > 1) {
  46280. throw "step size should be less than 1.";
  46281. }
  46282. this.value += step;
  46283. this.ensureLimits();
  46284. this.raiseOnChange();
  46285. return this;
  46286. };
  46287. PathCursor.prototype.ensureLimits = function () {
  46288. while (this.value > 1) {
  46289. this.value -= 1;
  46290. }
  46291. while (this.value < 0) {
  46292. this.value += 1;
  46293. }
  46294. return this;
  46295. };
  46296. // used by animation engine
  46297. PathCursor.prototype.raiseOnChange = function () {
  46298. var _this = this;
  46299. this._onchange.forEach(function (f) { return f(_this); });
  46300. return this;
  46301. };
  46302. PathCursor.prototype.onchange = function (f) {
  46303. this._onchange.push(f);
  46304. return this;
  46305. };
  46306. return PathCursor;
  46307. }());
  46308. BABYLON.PathCursor = PathCursor;
  46309. var AnimationKeyInterpolation;
  46310. (function (AnimationKeyInterpolation) {
  46311. /**
  46312. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46313. */
  46314. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46315. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46316. var Animation = /** @class */ (function () {
  46317. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46318. this.name = name;
  46319. this.targetProperty = targetProperty;
  46320. this.framePerSecond = framePerSecond;
  46321. this.dataType = dataType;
  46322. this.loopMode = loopMode;
  46323. this.enableBlending = enableBlending;
  46324. this._runtimeAnimations = new Array();
  46325. // The set of event that will be linked to this animation
  46326. this._events = new Array();
  46327. this.blendingSpeed = 0.01;
  46328. this._ranges = {};
  46329. this.targetPropertyPath = targetProperty.split(".");
  46330. this.dataType = dataType;
  46331. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46332. }
  46333. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46334. var dataType = undefined;
  46335. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46336. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46337. }
  46338. else if (from instanceof BABYLON.Quaternion) {
  46339. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46340. }
  46341. else if (from instanceof BABYLON.Vector3) {
  46342. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46343. }
  46344. else if (from instanceof BABYLON.Vector2) {
  46345. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46346. }
  46347. else if (from instanceof BABYLON.Color3) {
  46348. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46349. }
  46350. else if (from instanceof BABYLON.Size) {
  46351. dataType = Animation.ANIMATIONTYPE_SIZE;
  46352. }
  46353. if (dataType == undefined) {
  46354. return null;
  46355. }
  46356. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46357. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46358. animation.setKeys(keys);
  46359. if (easingFunction !== undefined) {
  46360. animation.setEasingFunction(easingFunction);
  46361. }
  46362. return animation;
  46363. };
  46364. /**
  46365. * Sets up an animation.
  46366. * @param property the property to animate
  46367. * @param animationType the animation type to apply
  46368. * @param easingFunction the easing function used in the animation
  46369. * @returns The created animation
  46370. */
  46371. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46372. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46373. animation.setEasingFunction(easingFunction);
  46374. return animation;
  46375. };
  46376. /**
  46377. * Create and start an animation on a node
  46378. * @param {string} name defines the name of the global animation that will be run on all nodes
  46379. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46380. * @param {string} targetProperty defines property to animate
  46381. * @param {number} framePerSecond defines the number of frame per second yo use
  46382. * @param {number} totalFrame defines the number of frames in total
  46383. * @param {any} from defines the initial value
  46384. * @param {any} to defines the final value
  46385. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46386. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46387. * @param onAnimationEnd defines the callback to call when animation end
  46388. * @returns the animatable created for this animation
  46389. */
  46390. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46391. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46392. if (!animation) {
  46393. return null;
  46394. }
  46395. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46396. };
  46397. /**
  46398. * Create and start an animation on a node and its descendants
  46399. * @param {string} name defines the name of the global animation that will be run on all nodes
  46400. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46401. * @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.
  46402. * @param {string} targetProperty defines property to animate
  46403. * @param {number} framePerSecond defines the number of frame per second yo use
  46404. * @param {number} totalFrame defines the number of frames in total
  46405. * @param {any} from defines the initial value
  46406. * @param {any} to defines the final value
  46407. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46408. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46409. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46410. * @returns the list of animatables created for all nodes
  46411. * @example https://www.babylonjs-playground.com/#MH0VLI
  46412. */
  46413. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46414. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46415. if (!animation) {
  46416. return null;
  46417. }
  46418. var scene = node.getScene();
  46419. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46420. };
  46421. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46422. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46423. if (!animation) {
  46424. return null;
  46425. }
  46426. node.animations.push(animation);
  46427. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46428. };
  46429. /**
  46430. * Transition property of the Camera to the target Value.
  46431. * @param property The property to transition
  46432. * @param targetValue The target Value of the property
  46433. * @param host The object where the property to animate belongs
  46434. * @param scene Scene used to run the animation
  46435. * @param frameRate Framerate (in frame/s) to use
  46436. * @param transition The transition type we want to use
  46437. * @param duration The duration of the animation, in milliseconds
  46438. * @param onAnimationEnd Call back trigger at the end of the animation.
  46439. */
  46440. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46441. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46442. if (duration <= 0) {
  46443. host[property] = targetValue;
  46444. if (onAnimationEnd) {
  46445. onAnimationEnd();
  46446. }
  46447. return null;
  46448. }
  46449. var endFrame = frameRate * (duration / 1000);
  46450. transition.setKeys([{
  46451. frame: 0,
  46452. value: host[property].clone ? host[property].clone() : host[property]
  46453. },
  46454. {
  46455. frame: endFrame,
  46456. value: targetValue
  46457. }]);
  46458. if (!host.animations) {
  46459. host.animations = [];
  46460. }
  46461. host.animations.push(transition);
  46462. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46463. animation.onAnimationEnd = onAnimationEnd;
  46464. return animation;
  46465. };
  46466. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46467. /**
  46468. * Return the array of runtime animations currently using this animation
  46469. */
  46470. get: function () {
  46471. return this._runtimeAnimations;
  46472. },
  46473. enumerable: true,
  46474. configurable: true
  46475. });
  46476. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46477. get: function () {
  46478. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46479. var runtimeAnimation = _a[_i];
  46480. if (!runtimeAnimation.isStopped) {
  46481. return true;
  46482. }
  46483. }
  46484. return false;
  46485. },
  46486. enumerable: true,
  46487. configurable: true
  46488. });
  46489. // Methods
  46490. /**
  46491. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46492. */
  46493. Animation.prototype.toString = function (fullDetails) {
  46494. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46495. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46496. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46497. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46498. if (fullDetails) {
  46499. ret += ", Ranges: {";
  46500. var first = true;
  46501. for (var name in this._ranges) {
  46502. if (first) {
  46503. ret += ", ";
  46504. first = false;
  46505. }
  46506. ret += name;
  46507. }
  46508. ret += "}";
  46509. }
  46510. return ret;
  46511. };
  46512. /**
  46513. * Add an event to this animation.
  46514. */
  46515. Animation.prototype.addEvent = function (event) {
  46516. this._events.push(event);
  46517. };
  46518. /**
  46519. * Remove all events found at the given frame
  46520. * @param frame
  46521. */
  46522. Animation.prototype.removeEvents = function (frame) {
  46523. for (var index = 0; index < this._events.length; index++) {
  46524. if (this._events[index].frame === frame) {
  46525. this._events.splice(index, 1);
  46526. index--;
  46527. }
  46528. }
  46529. };
  46530. Animation.prototype.getEvents = function () {
  46531. return this._events;
  46532. };
  46533. Animation.prototype.createRange = function (name, from, to) {
  46534. // check name not already in use; could happen for bones after serialized
  46535. if (!this._ranges[name]) {
  46536. this._ranges[name] = new AnimationRange(name, from, to);
  46537. }
  46538. };
  46539. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46540. if (deleteFrames === void 0) { deleteFrames = true; }
  46541. var range = this._ranges[name];
  46542. if (!range) {
  46543. return;
  46544. }
  46545. if (deleteFrames) {
  46546. var from = range.from;
  46547. var to = range.to;
  46548. // this loop MUST go high to low for multiple splices to work
  46549. for (var key = this._keys.length - 1; key >= 0; key--) {
  46550. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46551. this._keys.splice(key, 1);
  46552. }
  46553. }
  46554. }
  46555. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46556. };
  46557. Animation.prototype.getRange = function (name) {
  46558. return this._ranges[name];
  46559. };
  46560. Animation.prototype.getKeys = function () {
  46561. return this._keys;
  46562. };
  46563. Animation.prototype.getHighestFrame = function () {
  46564. var ret = 0;
  46565. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46566. if (ret < this._keys[key].frame) {
  46567. ret = this._keys[key].frame;
  46568. }
  46569. }
  46570. return ret;
  46571. };
  46572. Animation.prototype.getEasingFunction = function () {
  46573. return this._easingFunction;
  46574. };
  46575. Animation.prototype.setEasingFunction = function (easingFunction) {
  46576. this._easingFunction = easingFunction;
  46577. };
  46578. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46579. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46580. };
  46581. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46582. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46583. };
  46584. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46585. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46586. };
  46587. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46588. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46589. };
  46590. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46591. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46592. };
  46593. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46594. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46595. };
  46596. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46597. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46598. };
  46599. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46600. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46601. };
  46602. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46603. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46604. };
  46605. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46606. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46607. };
  46608. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46609. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46610. };
  46611. Animation.prototype.clone = function () {
  46612. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46613. clone.enableBlending = this.enableBlending;
  46614. clone.blendingSpeed = this.blendingSpeed;
  46615. if (this._keys) {
  46616. clone.setKeys(this._keys);
  46617. }
  46618. if (this._ranges) {
  46619. clone._ranges = {};
  46620. for (var name in this._ranges) {
  46621. var range = this._ranges[name];
  46622. if (!range) {
  46623. continue;
  46624. }
  46625. clone._ranges[name] = range.clone();
  46626. }
  46627. }
  46628. return clone;
  46629. };
  46630. Animation.prototype.setKeys = function (values) {
  46631. this._keys = values.slice(0);
  46632. };
  46633. Animation.prototype.serialize = function () {
  46634. var serializationObject = {};
  46635. serializationObject.name = this.name;
  46636. serializationObject.property = this.targetProperty;
  46637. serializationObject.framePerSecond = this.framePerSecond;
  46638. serializationObject.dataType = this.dataType;
  46639. serializationObject.loopBehavior = this.loopMode;
  46640. serializationObject.enableBlending = this.enableBlending;
  46641. serializationObject.blendingSpeed = this.blendingSpeed;
  46642. var dataType = this.dataType;
  46643. serializationObject.keys = [];
  46644. var keys = this.getKeys();
  46645. for (var index = 0; index < keys.length; index++) {
  46646. var animationKey = keys[index];
  46647. var key = {};
  46648. key.frame = animationKey.frame;
  46649. switch (dataType) {
  46650. case Animation.ANIMATIONTYPE_FLOAT:
  46651. key.values = [animationKey.value];
  46652. break;
  46653. case Animation.ANIMATIONTYPE_QUATERNION:
  46654. case Animation.ANIMATIONTYPE_MATRIX:
  46655. case Animation.ANIMATIONTYPE_VECTOR3:
  46656. case Animation.ANIMATIONTYPE_COLOR3:
  46657. key.values = animationKey.value.asArray();
  46658. break;
  46659. }
  46660. serializationObject.keys.push(key);
  46661. }
  46662. serializationObject.ranges = [];
  46663. for (var name in this._ranges) {
  46664. var source = this._ranges[name];
  46665. if (!source) {
  46666. continue;
  46667. }
  46668. var range = {};
  46669. range.name = name;
  46670. range.from = source.from;
  46671. range.to = source.to;
  46672. serializationObject.ranges.push(range);
  46673. }
  46674. return serializationObject;
  46675. };
  46676. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46677. get: function () {
  46678. return Animation._ANIMATIONTYPE_FLOAT;
  46679. },
  46680. enumerable: true,
  46681. configurable: true
  46682. });
  46683. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46684. get: function () {
  46685. return Animation._ANIMATIONTYPE_VECTOR3;
  46686. },
  46687. enumerable: true,
  46688. configurable: true
  46689. });
  46690. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46691. get: function () {
  46692. return Animation._ANIMATIONTYPE_VECTOR2;
  46693. },
  46694. enumerable: true,
  46695. configurable: true
  46696. });
  46697. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46698. get: function () {
  46699. return Animation._ANIMATIONTYPE_SIZE;
  46700. },
  46701. enumerable: true,
  46702. configurable: true
  46703. });
  46704. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46705. get: function () {
  46706. return Animation._ANIMATIONTYPE_QUATERNION;
  46707. },
  46708. enumerable: true,
  46709. configurable: true
  46710. });
  46711. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46712. get: function () {
  46713. return Animation._ANIMATIONTYPE_MATRIX;
  46714. },
  46715. enumerable: true,
  46716. configurable: true
  46717. });
  46718. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46719. get: function () {
  46720. return Animation._ANIMATIONTYPE_COLOR3;
  46721. },
  46722. enumerable: true,
  46723. configurable: true
  46724. });
  46725. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46726. get: function () {
  46727. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46728. },
  46729. enumerable: true,
  46730. configurable: true
  46731. });
  46732. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46733. get: function () {
  46734. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46735. },
  46736. enumerable: true,
  46737. configurable: true
  46738. });
  46739. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46740. get: function () {
  46741. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46742. },
  46743. enumerable: true,
  46744. configurable: true
  46745. });
  46746. Animation.Parse = function (parsedAnimation) {
  46747. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46748. var dataType = parsedAnimation.dataType;
  46749. var keys = [];
  46750. var data;
  46751. var index;
  46752. if (parsedAnimation.enableBlending) {
  46753. animation.enableBlending = parsedAnimation.enableBlending;
  46754. }
  46755. if (parsedAnimation.blendingSpeed) {
  46756. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46757. }
  46758. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46759. var key = parsedAnimation.keys[index];
  46760. var inTangent;
  46761. var outTangent;
  46762. switch (dataType) {
  46763. case Animation.ANIMATIONTYPE_FLOAT:
  46764. data = key.values[0];
  46765. if (key.values.length >= 1) {
  46766. inTangent = key.values[1];
  46767. }
  46768. if (key.values.length >= 2) {
  46769. outTangent = key.values[2];
  46770. }
  46771. break;
  46772. case Animation.ANIMATIONTYPE_QUATERNION:
  46773. data = BABYLON.Quaternion.FromArray(key.values);
  46774. if (key.values.length >= 8) {
  46775. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46776. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46777. inTangent = _inTangent;
  46778. }
  46779. }
  46780. if (key.values.length >= 12) {
  46781. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46782. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46783. outTangent = _outTangent;
  46784. }
  46785. }
  46786. break;
  46787. case Animation.ANIMATIONTYPE_MATRIX:
  46788. data = BABYLON.Matrix.FromArray(key.values);
  46789. break;
  46790. case Animation.ANIMATIONTYPE_COLOR3:
  46791. data = BABYLON.Color3.FromArray(key.values);
  46792. break;
  46793. case Animation.ANIMATIONTYPE_VECTOR3:
  46794. default:
  46795. data = BABYLON.Vector3.FromArray(key.values);
  46796. break;
  46797. }
  46798. var keyData = {};
  46799. keyData.frame = key.frame;
  46800. keyData.value = data;
  46801. if (inTangent != undefined) {
  46802. keyData.inTangent = inTangent;
  46803. }
  46804. if (outTangent != undefined) {
  46805. keyData.outTangent = outTangent;
  46806. }
  46807. keys.push(keyData);
  46808. }
  46809. animation.setKeys(keys);
  46810. if (parsedAnimation.ranges) {
  46811. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46812. data = parsedAnimation.ranges[index];
  46813. animation.createRange(data.name, data.from, data.to);
  46814. }
  46815. }
  46816. return animation;
  46817. };
  46818. Animation.AppendSerializedAnimations = function (source, destination) {
  46819. if (source.animations) {
  46820. destination.animations = [];
  46821. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46822. var animation = source.animations[animationIndex];
  46823. destination.animations.push(animation.serialize());
  46824. }
  46825. }
  46826. };
  46827. Animation.AllowMatricesInterpolation = false;
  46828. // Statics
  46829. Animation._ANIMATIONTYPE_FLOAT = 0;
  46830. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46831. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46832. Animation._ANIMATIONTYPE_MATRIX = 3;
  46833. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46834. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46835. Animation._ANIMATIONTYPE_SIZE = 6;
  46836. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46837. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46838. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46839. return Animation;
  46840. }());
  46841. BABYLON.Animation = Animation;
  46842. })(BABYLON || (BABYLON = {}));
  46843. //# sourceMappingURL=babylon.animation.js.map
  46844. var BABYLON;
  46845. (function (BABYLON) {
  46846. /**
  46847. * This class defines the direct association between an animation and a target
  46848. */
  46849. var TargetedAnimation = /** @class */ (function () {
  46850. function TargetedAnimation() {
  46851. }
  46852. return TargetedAnimation;
  46853. }());
  46854. BABYLON.TargetedAnimation = TargetedAnimation;
  46855. /**
  46856. * Use this class to create coordinated animations on multiple targets
  46857. */
  46858. var AnimationGroup = /** @class */ (function () {
  46859. function AnimationGroup(name, scene) {
  46860. if (scene === void 0) { scene = null; }
  46861. this.name = name;
  46862. this._targetedAnimations = new Array();
  46863. this._animatables = new Array();
  46864. this._from = Number.MAX_VALUE;
  46865. this._to = -Number.MAX_VALUE;
  46866. this._speedRatio = 1;
  46867. this.onAnimationEndObservable = new BABYLON.Observable();
  46868. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46869. this._scene.animationGroups.push(this);
  46870. }
  46871. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46872. /**
  46873. * Define if the animations are started
  46874. */
  46875. get: function () {
  46876. return this._isStarted;
  46877. },
  46878. enumerable: true,
  46879. configurable: true
  46880. });
  46881. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46882. /**
  46883. * Gets or sets the speed ratio to use for all animations
  46884. */
  46885. get: function () {
  46886. return this._speedRatio;
  46887. },
  46888. /**
  46889. * Gets or sets the speed ratio to use for all animations
  46890. */
  46891. set: function (value) {
  46892. if (this._speedRatio === value) {
  46893. return;
  46894. }
  46895. this._speedRatio = value;
  46896. for (var index = 0; index < this._animatables.length; index++) {
  46897. var animatable = this._animatables[index];
  46898. animatable.speedRatio = this._speedRatio;
  46899. }
  46900. },
  46901. enumerable: true,
  46902. configurable: true
  46903. });
  46904. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46905. /**
  46906. * Gets the targeted animations for this animation group
  46907. */
  46908. get: function () {
  46909. return this._targetedAnimations;
  46910. },
  46911. enumerable: true,
  46912. configurable: true
  46913. });
  46914. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  46915. /**
  46916. * returning the list of animatables controlled by this animation group.
  46917. */
  46918. get: function () {
  46919. return this._animatables;
  46920. },
  46921. enumerable: true,
  46922. configurable: true
  46923. });
  46924. /**
  46925. * Add an animation (with its target) in the group
  46926. * @param animation defines the animation we want to add
  46927. * @param target defines the target of the animation
  46928. * @returns the {BABYLON.TargetedAnimation} object
  46929. */
  46930. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46931. var targetedAnimation = {
  46932. animation: animation,
  46933. target: target
  46934. };
  46935. var keys = animation.getKeys();
  46936. if (this._from > keys[0].frame) {
  46937. this._from = keys[0].frame;
  46938. }
  46939. if (this._to < keys[keys.length - 1].frame) {
  46940. this._to = keys[keys.length - 1].frame;
  46941. }
  46942. this._targetedAnimations.push(targetedAnimation);
  46943. return targetedAnimation;
  46944. };
  46945. /**
  46946. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46947. * It can add constant keys at begin or end
  46948. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46949. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46950. */
  46951. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46952. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46953. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46954. beginFrame = Math.max(beginFrame, this._from);
  46955. endFrame = Math.min(endFrame, this._to);
  46956. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46957. var targetedAnimation = this._targetedAnimations[index];
  46958. var keys = targetedAnimation.animation.getKeys();
  46959. var startKey = keys[0];
  46960. var endKey = keys[keys.length - 1];
  46961. if (startKey.frame > beginFrame) {
  46962. var newKey = {
  46963. frame: beginFrame,
  46964. value: startKey.value,
  46965. inTangent: startKey.inTangent,
  46966. outTangent: startKey.outTangent,
  46967. interpolation: startKey.interpolation
  46968. };
  46969. keys.splice(0, 0, newKey);
  46970. }
  46971. if (endKey.frame < endFrame) {
  46972. var newKey = {
  46973. frame: endFrame,
  46974. value: endKey.value,
  46975. inTangent: endKey.outTangent,
  46976. outTangent: endKey.outTangent,
  46977. interpolation: endKey.interpolation
  46978. };
  46979. keys.push(newKey);
  46980. }
  46981. }
  46982. return this;
  46983. };
  46984. /**
  46985. * Start all animations on given targets
  46986. * @param loop defines if animations must loop
  46987. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46988. */
  46989. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46990. var _this = this;
  46991. if (loop === void 0) { loop = false; }
  46992. if (speedRatio === void 0) { speedRatio = 1; }
  46993. if (this._isStarted || this._targetedAnimations.length === 0) {
  46994. return this;
  46995. }
  46996. var _loop_1 = function () {
  46997. var targetedAnimation = this_1._targetedAnimations[index];
  46998. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46999. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47000. }));
  47001. };
  47002. var this_1 = this;
  47003. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47004. _loop_1();
  47005. }
  47006. this._speedRatio = speedRatio;
  47007. this._isStarted = true;
  47008. return this;
  47009. };
  47010. /**
  47011. * Pause all animations
  47012. */
  47013. AnimationGroup.prototype.pause = function () {
  47014. if (!this._isStarted) {
  47015. return this;
  47016. }
  47017. for (var index = 0; index < this._animatables.length; index++) {
  47018. var animatable = this._animatables[index];
  47019. animatable.pause();
  47020. }
  47021. return this;
  47022. };
  47023. /**
  47024. * Play all animations to initial state
  47025. * This function will start() the animations if they were not started or will restart() them if they were paused
  47026. * @param loop defines if animations must loop
  47027. */
  47028. AnimationGroup.prototype.play = function (loop) {
  47029. if (this.isStarted) {
  47030. if (loop !== undefined) {
  47031. for (var index = 0; index < this._animatables.length; index++) {
  47032. var animatable = this._animatables[index];
  47033. animatable.loopAnimation = loop;
  47034. }
  47035. }
  47036. this.restart();
  47037. }
  47038. else {
  47039. this.start(loop, this._speedRatio);
  47040. }
  47041. return this;
  47042. };
  47043. /**
  47044. * Reset all animations to initial state
  47045. */
  47046. AnimationGroup.prototype.reset = function () {
  47047. if (!this._isStarted) {
  47048. return this;
  47049. }
  47050. for (var index = 0; index < this._animatables.length; index++) {
  47051. var animatable = this._animatables[index];
  47052. animatable.reset();
  47053. }
  47054. return this;
  47055. };
  47056. /**
  47057. * Restart animations from key 0
  47058. */
  47059. AnimationGroup.prototype.restart = function () {
  47060. if (!this._isStarted) {
  47061. return this;
  47062. }
  47063. for (var index = 0; index < this._animatables.length; index++) {
  47064. var animatable = this._animatables[index];
  47065. animatable.restart();
  47066. }
  47067. return this;
  47068. };
  47069. /**
  47070. * Stop all animations
  47071. */
  47072. AnimationGroup.prototype.stop = function () {
  47073. if (!this._isStarted) {
  47074. return this;
  47075. }
  47076. for (var index = 0; index < this._animatables.length; index++) {
  47077. var animatable = this._animatables[index];
  47078. animatable.stop();
  47079. }
  47080. this._isStarted = false;
  47081. return this;
  47082. };
  47083. /**
  47084. * Goes to a specific frame in this animation group
  47085. *
  47086. * @param frame the frame number to go to
  47087. * @return the animationGroup
  47088. */
  47089. AnimationGroup.prototype.goToFrame = function (frame) {
  47090. if (!this._isStarted) {
  47091. return this;
  47092. }
  47093. for (var index = 0; index < this._animatables.length; index++) {
  47094. var animatable = this._animatables[index];
  47095. animatable.goToFrame(frame);
  47096. }
  47097. return this;
  47098. };
  47099. /**
  47100. * Dispose all associated resources
  47101. */
  47102. AnimationGroup.prototype.dispose = function () {
  47103. this._targetedAnimations = [];
  47104. this._animatables = [];
  47105. var index = this._scene.animationGroups.indexOf(this);
  47106. if (index > -1) {
  47107. this._scene.animationGroups.splice(index, 1);
  47108. }
  47109. };
  47110. return AnimationGroup;
  47111. }());
  47112. BABYLON.AnimationGroup = AnimationGroup;
  47113. })(BABYLON || (BABYLON = {}));
  47114. //# sourceMappingURL=babylon.animationGroup.js.map
  47115. var BABYLON;
  47116. (function (BABYLON) {
  47117. var RuntimeAnimation = /** @class */ (function () {
  47118. function RuntimeAnimation(target, animation) {
  47119. this._offsetsCache = {};
  47120. this._highLimitsCache = {};
  47121. this._stopped = false;
  47122. this._blendingFactor = 0;
  47123. this._ratioOffset = 0;
  47124. this._animation = animation;
  47125. this._target = target;
  47126. animation._runtimeAnimations.push(this);
  47127. }
  47128. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47129. get: function () {
  47130. return this._animation;
  47131. },
  47132. enumerable: true,
  47133. configurable: true
  47134. });
  47135. RuntimeAnimation.prototype.reset = function () {
  47136. this._offsetsCache = {};
  47137. this._highLimitsCache = {};
  47138. this.currentFrame = 0;
  47139. this._blendingFactor = 0;
  47140. this._originalBlendValue = null;
  47141. };
  47142. RuntimeAnimation.prototype.isStopped = function () {
  47143. return this._stopped;
  47144. };
  47145. RuntimeAnimation.prototype.dispose = function () {
  47146. var index = this._animation.runtimeAnimations.indexOf(this);
  47147. if (index > -1) {
  47148. this._animation.runtimeAnimations.splice(index, 1);
  47149. }
  47150. };
  47151. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47152. if (typeof value === "function") {
  47153. return value();
  47154. }
  47155. return value;
  47156. };
  47157. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47158. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47159. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47160. }
  47161. this.currentFrame = currentFrame;
  47162. var keys = this._animation.getKeys();
  47163. // Try to get a hash to find the right key
  47164. 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));
  47165. if (keys[startKeyIndex].frame >= currentFrame) {
  47166. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47167. startKeyIndex--;
  47168. }
  47169. }
  47170. for (var key = startKeyIndex; key < keys.length; key++) {
  47171. var endKey = keys[key + 1];
  47172. if (endKey.frame >= currentFrame) {
  47173. var startKey = keys[key];
  47174. var startValue = this._getKeyValue(startKey.value);
  47175. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47176. return startValue;
  47177. }
  47178. var endValue = this._getKeyValue(endKey.value);
  47179. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47180. var frameDelta = endKey.frame - startKey.frame;
  47181. // gradient : percent of currentFrame between the frame inf and the frame sup
  47182. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47183. // check for easingFunction and correction of gradient
  47184. var easingFunction = this._animation.getEasingFunction();
  47185. if (easingFunction != null) {
  47186. gradient = easingFunction.ease(gradient);
  47187. }
  47188. switch (this._animation.dataType) {
  47189. // Float
  47190. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47191. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47192. switch (loopMode) {
  47193. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47194. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47195. return floatValue;
  47196. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47197. return offsetValue * repeatCount + floatValue;
  47198. }
  47199. break;
  47200. // Quaternion
  47201. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47202. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47203. switch (loopMode) {
  47204. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47205. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47206. return quatValue;
  47207. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47208. return quatValue.add(offsetValue.scale(repeatCount));
  47209. }
  47210. return quatValue;
  47211. // Vector3
  47212. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47213. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47214. switch (loopMode) {
  47215. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47216. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47217. return vec3Value;
  47218. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47219. return vec3Value.add(offsetValue.scale(repeatCount));
  47220. }
  47221. // Vector2
  47222. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47223. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47224. switch (loopMode) {
  47225. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47226. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47227. return vec2Value;
  47228. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47229. return vec2Value.add(offsetValue.scale(repeatCount));
  47230. }
  47231. // Size
  47232. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47233. switch (loopMode) {
  47234. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47235. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47236. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47237. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47238. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47239. }
  47240. // Color3
  47241. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47242. switch (loopMode) {
  47243. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47244. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47245. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47246. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47247. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47248. }
  47249. // Matrix
  47250. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47251. switch (loopMode) {
  47252. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47253. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47254. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47255. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47256. }
  47257. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47258. return startValue;
  47259. }
  47260. default:
  47261. break;
  47262. }
  47263. break;
  47264. }
  47265. }
  47266. return this._getKeyValue(keys[keys.length - 1].value);
  47267. };
  47268. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47269. if (blend === void 0) { blend = false; }
  47270. // Set value
  47271. var path;
  47272. var destination;
  47273. var targetPropertyPath = this._animation.targetPropertyPath;
  47274. if (targetPropertyPath.length > 1) {
  47275. var property = this._target[targetPropertyPath[0]];
  47276. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47277. property = property[targetPropertyPath[index]];
  47278. }
  47279. path = targetPropertyPath[targetPropertyPath.length - 1];
  47280. destination = property;
  47281. }
  47282. else {
  47283. path = targetPropertyPath[0];
  47284. destination = this._target;
  47285. }
  47286. // Blending
  47287. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47288. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47289. if (enableBlending && this._blendingFactor <= 1.0) {
  47290. if (!this._originalBlendValue) {
  47291. if (destination[path].clone) {
  47292. this._originalBlendValue = destination[path].clone();
  47293. }
  47294. else {
  47295. this._originalBlendValue = destination[path];
  47296. }
  47297. }
  47298. if (this._originalBlendValue.prototype) {
  47299. if (this._originalBlendValue.prototype.Lerp) {
  47300. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47301. }
  47302. else {
  47303. destination[path] = currentValue;
  47304. }
  47305. }
  47306. else if (this._originalBlendValue.m) {
  47307. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47308. }
  47309. else {
  47310. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47311. }
  47312. this._blendingFactor += blendingSpeed;
  47313. }
  47314. else {
  47315. destination[path] = currentValue;
  47316. }
  47317. if (this._target.markAsDirty) {
  47318. this._target.markAsDirty(this._animation.targetProperty);
  47319. }
  47320. };
  47321. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47322. if (this._target && this._target.animationPropertiesOverride) {
  47323. return this._target.animationPropertiesOverride.loopMode;
  47324. }
  47325. return this._animation.loopMode;
  47326. };
  47327. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47328. var keys = this._animation.getKeys();
  47329. if (frame < keys[0].frame) {
  47330. frame = keys[0].frame;
  47331. }
  47332. else if (frame > keys[keys.length - 1].frame) {
  47333. frame = keys[keys.length - 1].frame;
  47334. }
  47335. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47336. this.setValue(currentValue);
  47337. };
  47338. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47339. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47340. this._ratioOffset = this._previousRatio - newRatio;
  47341. };
  47342. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47343. if (blend === void 0) { blend = false; }
  47344. var targetPropertyPath = this._animation.targetPropertyPath;
  47345. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47346. this._stopped = true;
  47347. return false;
  47348. }
  47349. var returnValue = true;
  47350. var keys = this._animation.getKeys();
  47351. // Adding a start key at frame 0 if missing
  47352. if (keys[0].frame !== 0) {
  47353. var newKey = { frame: 0, value: keys[0].value };
  47354. keys.splice(0, 0, newKey);
  47355. }
  47356. // Check limits
  47357. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47358. from = keys[0].frame;
  47359. }
  47360. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47361. to = keys[keys.length - 1].frame;
  47362. }
  47363. //to and from cannot be the same key
  47364. if (from === to) {
  47365. if (from > keys[0].frame) {
  47366. from--;
  47367. }
  47368. else if (to < keys[keys.length - 1].frame) {
  47369. to++;
  47370. }
  47371. }
  47372. // Compute ratio
  47373. var range = to - from;
  47374. var offsetValue;
  47375. // ratio represents the frame delta between from and to
  47376. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47377. var highLimitValue = 0;
  47378. this._previousDelay = delay;
  47379. this._previousRatio = ratio;
  47380. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47381. returnValue = false;
  47382. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47383. }
  47384. else {
  47385. // Get max value if required
  47386. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47387. var keyOffset = to.toString() + from.toString();
  47388. if (!this._offsetsCache[keyOffset]) {
  47389. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47390. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47391. switch (this._animation.dataType) {
  47392. // Float
  47393. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47394. this._offsetsCache[keyOffset] = toValue - fromValue;
  47395. break;
  47396. // Quaternion
  47397. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47398. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47399. break;
  47400. // Vector3
  47401. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47402. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47403. // Vector2
  47404. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47405. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47406. // Size
  47407. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47408. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47409. // Color3
  47410. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47411. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47412. default:
  47413. break;
  47414. }
  47415. this._highLimitsCache[keyOffset] = toValue;
  47416. }
  47417. highLimitValue = this._highLimitsCache[keyOffset];
  47418. offsetValue = this._offsetsCache[keyOffset];
  47419. }
  47420. }
  47421. if (offsetValue === undefined) {
  47422. switch (this._animation.dataType) {
  47423. // Float
  47424. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47425. offsetValue = 0;
  47426. break;
  47427. // Quaternion
  47428. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47429. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47430. break;
  47431. // Vector3
  47432. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47433. offsetValue = BABYLON.Vector3.Zero();
  47434. break;
  47435. // Vector2
  47436. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47437. offsetValue = BABYLON.Vector2.Zero();
  47438. break;
  47439. // Size
  47440. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47441. offsetValue = BABYLON.Size.Zero();
  47442. break;
  47443. // Color3
  47444. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47445. offsetValue = BABYLON.Color3.Black();
  47446. }
  47447. }
  47448. // Compute value
  47449. var repeatCount = (ratio / range) >> 0;
  47450. var currentFrame = returnValue ? from + ratio % range : to;
  47451. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47452. // Set value
  47453. this.setValue(currentValue);
  47454. // Check events
  47455. var events = this._animation.getEvents();
  47456. for (var index = 0; index < events.length; index++) {
  47457. // Make sure current frame has passed event frame and that event frame is within the current range
  47458. // Also, handle both forward and reverse animations
  47459. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47460. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47461. var event = events[index];
  47462. if (!event.isDone) {
  47463. // If event should be done only once, remove it.
  47464. if (event.onlyOnce) {
  47465. events.splice(index, 1);
  47466. index--;
  47467. }
  47468. event.isDone = true;
  47469. event.action();
  47470. } // Don't do anything if the event has already be done.
  47471. }
  47472. else if (events[index].isDone && !events[index].onlyOnce) {
  47473. // reset event, the animation is looping
  47474. events[index].isDone = false;
  47475. }
  47476. }
  47477. if (!returnValue) {
  47478. this._stopped = true;
  47479. }
  47480. return returnValue;
  47481. };
  47482. return RuntimeAnimation;
  47483. }());
  47484. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47485. })(BABYLON || (BABYLON = {}));
  47486. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47487. var BABYLON;
  47488. (function (BABYLON) {
  47489. var Animatable = /** @class */ (function () {
  47490. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47491. if (fromFrame === void 0) { fromFrame = 0; }
  47492. if (toFrame === void 0) { toFrame = 100; }
  47493. if (loopAnimation === void 0) { loopAnimation = false; }
  47494. if (speedRatio === void 0) { speedRatio = 1.0; }
  47495. this.target = target;
  47496. this.fromFrame = fromFrame;
  47497. this.toFrame = toFrame;
  47498. this.loopAnimation = loopAnimation;
  47499. this.onAnimationEnd = onAnimationEnd;
  47500. this._localDelayOffset = null;
  47501. this._pausedDelay = null;
  47502. this._runtimeAnimations = new Array();
  47503. this._paused = false;
  47504. this._speedRatio = 1;
  47505. this.animationStarted = false;
  47506. if (animations) {
  47507. this.appendAnimations(target, animations);
  47508. }
  47509. this._speedRatio = speedRatio;
  47510. this._scene = scene;
  47511. scene._activeAnimatables.push(this);
  47512. }
  47513. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47514. get: function () {
  47515. return this._speedRatio;
  47516. },
  47517. set: function (value) {
  47518. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47519. var animation = this._runtimeAnimations[index];
  47520. animation._prepareForSpeedRatioChange(value);
  47521. }
  47522. this._speedRatio = value;
  47523. },
  47524. enumerable: true,
  47525. configurable: true
  47526. });
  47527. // Methods
  47528. Animatable.prototype.getAnimations = function () {
  47529. return this._runtimeAnimations;
  47530. };
  47531. Animatable.prototype.appendAnimations = function (target, animations) {
  47532. for (var index = 0; index < animations.length; index++) {
  47533. var animation = animations[index];
  47534. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47535. }
  47536. };
  47537. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47538. var runtimeAnimations = this._runtimeAnimations;
  47539. for (var index = 0; index < runtimeAnimations.length; index++) {
  47540. if (runtimeAnimations[index].animation.targetProperty === property) {
  47541. return runtimeAnimations[index].animation;
  47542. }
  47543. }
  47544. return null;
  47545. };
  47546. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47547. var runtimeAnimations = this._runtimeAnimations;
  47548. for (var index = 0; index < runtimeAnimations.length; index++) {
  47549. if (runtimeAnimations[index].animation.targetProperty === property) {
  47550. return runtimeAnimations[index];
  47551. }
  47552. }
  47553. return null;
  47554. };
  47555. Animatable.prototype.reset = function () {
  47556. var runtimeAnimations = this._runtimeAnimations;
  47557. for (var index = 0; index < runtimeAnimations.length; index++) {
  47558. runtimeAnimations[index].reset();
  47559. }
  47560. // Reset to original value
  47561. for (index = 0; index < runtimeAnimations.length; index++) {
  47562. var animation = runtimeAnimations[index];
  47563. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47564. }
  47565. this._localDelayOffset = null;
  47566. this._pausedDelay = null;
  47567. };
  47568. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47569. var runtimeAnimations = this._runtimeAnimations;
  47570. for (var index = 0; index < runtimeAnimations.length; index++) {
  47571. runtimeAnimations[index].animation.enableBlending = true;
  47572. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47573. }
  47574. };
  47575. Animatable.prototype.disableBlending = function () {
  47576. var runtimeAnimations = this._runtimeAnimations;
  47577. for (var index = 0; index < runtimeAnimations.length; index++) {
  47578. runtimeAnimations[index].animation.enableBlending = false;
  47579. }
  47580. };
  47581. Animatable.prototype.goToFrame = function (frame) {
  47582. var runtimeAnimations = this._runtimeAnimations;
  47583. if (runtimeAnimations[0]) {
  47584. var fps = runtimeAnimations[0].animation.framePerSecond;
  47585. var currentFrame = runtimeAnimations[0].currentFrame;
  47586. var adjustTime = frame - currentFrame;
  47587. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47588. if (this._localDelayOffset === null) {
  47589. this._localDelayOffset = 0;
  47590. }
  47591. this._localDelayOffset -= delay;
  47592. }
  47593. for (var index = 0; index < runtimeAnimations.length; index++) {
  47594. runtimeAnimations[index].goToFrame(frame);
  47595. }
  47596. };
  47597. Animatable.prototype.pause = function () {
  47598. if (this._paused) {
  47599. return;
  47600. }
  47601. this._paused = true;
  47602. };
  47603. Animatable.prototype.restart = function () {
  47604. this._paused = false;
  47605. };
  47606. Animatable.prototype.stop = function (animationName) {
  47607. if (animationName) {
  47608. var idx = this._scene._activeAnimatables.indexOf(this);
  47609. if (idx > -1) {
  47610. var runtimeAnimations = this._runtimeAnimations;
  47611. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47612. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47613. continue;
  47614. }
  47615. runtimeAnimations[index].dispose();
  47616. runtimeAnimations.splice(index, 1);
  47617. }
  47618. if (runtimeAnimations.length == 0) {
  47619. this._scene._activeAnimatables.splice(idx, 1);
  47620. if (this.onAnimationEnd) {
  47621. this.onAnimationEnd();
  47622. }
  47623. }
  47624. }
  47625. }
  47626. else {
  47627. var index = this._scene._activeAnimatables.indexOf(this);
  47628. if (index > -1) {
  47629. this._scene._activeAnimatables.splice(index, 1);
  47630. var runtimeAnimations = this._runtimeAnimations;
  47631. for (var index = 0; index < runtimeAnimations.length; index++) {
  47632. runtimeAnimations[index].dispose();
  47633. }
  47634. if (this.onAnimationEnd) {
  47635. this.onAnimationEnd();
  47636. }
  47637. }
  47638. }
  47639. };
  47640. Animatable.prototype._animate = function (delay) {
  47641. if (this._paused) {
  47642. this.animationStarted = false;
  47643. if (this._pausedDelay === null) {
  47644. this._pausedDelay = delay;
  47645. }
  47646. return true;
  47647. }
  47648. if (this._localDelayOffset === null) {
  47649. this._localDelayOffset = delay;
  47650. this._pausedDelay = null;
  47651. }
  47652. else if (this._pausedDelay !== null) {
  47653. this._localDelayOffset += delay - this._pausedDelay;
  47654. this._pausedDelay = null;
  47655. }
  47656. // Animating
  47657. var running = false;
  47658. var runtimeAnimations = this._runtimeAnimations;
  47659. var index;
  47660. for (index = 0; index < runtimeAnimations.length; index++) {
  47661. var animation = runtimeAnimations[index];
  47662. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47663. running = running || isRunning;
  47664. }
  47665. this.animationStarted = running;
  47666. if (!running) {
  47667. // Remove from active animatables
  47668. index = this._scene._activeAnimatables.indexOf(this);
  47669. this._scene._activeAnimatables.splice(index, 1);
  47670. // Dispose all runtime animations
  47671. for (index = 0; index < runtimeAnimations.length; index++) {
  47672. runtimeAnimations[index].dispose();
  47673. }
  47674. }
  47675. if (!running && this.onAnimationEnd) {
  47676. this.onAnimationEnd();
  47677. this.onAnimationEnd = null;
  47678. }
  47679. return running;
  47680. };
  47681. return Animatable;
  47682. }());
  47683. BABYLON.Animatable = Animatable;
  47684. })(BABYLON || (BABYLON = {}));
  47685. //# sourceMappingURL=babylon.animatable.js.map
  47686. var BABYLON;
  47687. (function (BABYLON) {
  47688. var EasingFunction = /** @class */ (function () {
  47689. function EasingFunction() {
  47690. // Properties
  47691. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47692. }
  47693. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47694. get: function () {
  47695. return EasingFunction._EASINGMODE_EASEIN;
  47696. },
  47697. enumerable: true,
  47698. configurable: true
  47699. });
  47700. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47701. get: function () {
  47702. return EasingFunction._EASINGMODE_EASEOUT;
  47703. },
  47704. enumerable: true,
  47705. configurable: true
  47706. });
  47707. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47708. get: function () {
  47709. return EasingFunction._EASINGMODE_EASEINOUT;
  47710. },
  47711. enumerable: true,
  47712. configurable: true
  47713. });
  47714. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47715. var n = Math.min(Math.max(easingMode, 0), 2);
  47716. this._easingMode = n;
  47717. };
  47718. EasingFunction.prototype.getEasingMode = function () {
  47719. return this._easingMode;
  47720. };
  47721. EasingFunction.prototype.easeInCore = function (gradient) {
  47722. throw new Error('You must implement this method');
  47723. };
  47724. EasingFunction.prototype.ease = function (gradient) {
  47725. switch (this._easingMode) {
  47726. case EasingFunction.EASINGMODE_EASEIN:
  47727. return this.easeInCore(gradient);
  47728. case EasingFunction.EASINGMODE_EASEOUT:
  47729. return (1 - this.easeInCore(1 - gradient));
  47730. }
  47731. if (gradient >= 0.5) {
  47732. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47733. }
  47734. return (this.easeInCore(gradient * 2) * 0.5);
  47735. };
  47736. //Statics
  47737. EasingFunction._EASINGMODE_EASEIN = 0;
  47738. EasingFunction._EASINGMODE_EASEOUT = 1;
  47739. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47740. return EasingFunction;
  47741. }());
  47742. BABYLON.EasingFunction = EasingFunction;
  47743. var CircleEase = /** @class */ (function (_super) {
  47744. __extends(CircleEase, _super);
  47745. function CircleEase() {
  47746. return _super !== null && _super.apply(this, arguments) || this;
  47747. }
  47748. CircleEase.prototype.easeInCore = function (gradient) {
  47749. gradient = Math.max(0, Math.min(1, gradient));
  47750. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47751. };
  47752. return CircleEase;
  47753. }(EasingFunction));
  47754. BABYLON.CircleEase = CircleEase;
  47755. var BackEase = /** @class */ (function (_super) {
  47756. __extends(BackEase, _super);
  47757. function BackEase(amplitude) {
  47758. if (amplitude === void 0) { amplitude = 1; }
  47759. var _this = _super.call(this) || this;
  47760. _this.amplitude = amplitude;
  47761. return _this;
  47762. }
  47763. BackEase.prototype.easeInCore = function (gradient) {
  47764. var num = Math.max(0, this.amplitude);
  47765. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47766. };
  47767. return BackEase;
  47768. }(EasingFunction));
  47769. BABYLON.BackEase = BackEase;
  47770. var BounceEase = /** @class */ (function (_super) {
  47771. __extends(BounceEase, _super);
  47772. function BounceEase(bounces, bounciness) {
  47773. if (bounces === void 0) { bounces = 3; }
  47774. if (bounciness === void 0) { bounciness = 2; }
  47775. var _this = _super.call(this) || this;
  47776. _this.bounces = bounces;
  47777. _this.bounciness = bounciness;
  47778. return _this;
  47779. }
  47780. BounceEase.prototype.easeInCore = function (gradient) {
  47781. var y = Math.max(0.0, this.bounces);
  47782. var bounciness = this.bounciness;
  47783. if (bounciness <= 1.0) {
  47784. bounciness = 1.001;
  47785. }
  47786. var num9 = Math.pow(bounciness, y);
  47787. var num5 = 1.0 - bounciness;
  47788. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47789. var num15 = gradient * num4;
  47790. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47791. var num3 = Math.floor(num65);
  47792. var num13 = num3 + 1.0;
  47793. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47794. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47795. var num7 = (num8 + num12) * 0.5;
  47796. var num6 = gradient - num7;
  47797. var num2 = num7 - num8;
  47798. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47799. };
  47800. return BounceEase;
  47801. }(EasingFunction));
  47802. BABYLON.BounceEase = BounceEase;
  47803. var CubicEase = /** @class */ (function (_super) {
  47804. __extends(CubicEase, _super);
  47805. function CubicEase() {
  47806. return _super !== null && _super.apply(this, arguments) || this;
  47807. }
  47808. CubicEase.prototype.easeInCore = function (gradient) {
  47809. return (gradient * gradient * gradient);
  47810. };
  47811. return CubicEase;
  47812. }(EasingFunction));
  47813. BABYLON.CubicEase = CubicEase;
  47814. var ElasticEase = /** @class */ (function (_super) {
  47815. __extends(ElasticEase, _super);
  47816. function ElasticEase(oscillations, springiness) {
  47817. if (oscillations === void 0) { oscillations = 3; }
  47818. if (springiness === void 0) { springiness = 3; }
  47819. var _this = _super.call(this) || this;
  47820. _this.oscillations = oscillations;
  47821. _this.springiness = springiness;
  47822. return _this;
  47823. }
  47824. ElasticEase.prototype.easeInCore = function (gradient) {
  47825. var num2;
  47826. var num3 = Math.max(0.0, this.oscillations);
  47827. var num = Math.max(0.0, this.springiness);
  47828. if (num == 0) {
  47829. num2 = gradient;
  47830. }
  47831. else {
  47832. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47833. }
  47834. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47835. };
  47836. return ElasticEase;
  47837. }(EasingFunction));
  47838. BABYLON.ElasticEase = ElasticEase;
  47839. var ExponentialEase = /** @class */ (function (_super) {
  47840. __extends(ExponentialEase, _super);
  47841. function ExponentialEase(exponent) {
  47842. if (exponent === void 0) { exponent = 2; }
  47843. var _this = _super.call(this) || this;
  47844. _this.exponent = exponent;
  47845. return _this;
  47846. }
  47847. ExponentialEase.prototype.easeInCore = function (gradient) {
  47848. if (this.exponent <= 0) {
  47849. return gradient;
  47850. }
  47851. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47852. };
  47853. return ExponentialEase;
  47854. }(EasingFunction));
  47855. BABYLON.ExponentialEase = ExponentialEase;
  47856. var PowerEase = /** @class */ (function (_super) {
  47857. __extends(PowerEase, _super);
  47858. function PowerEase(power) {
  47859. if (power === void 0) { power = 2; }
  47860. var _this = _super.call(this) || this;
  47861. _this.power = power;
  47862. return _this;
  47863. }
  47864. PowerEase.prototype.easeInCore = function (gradient) {
  47865. var y = Math.max(0.0, this.power);
  47866. return Math.pow(gradient, y);
  47867. };
  47868. return PowerEase;
  47869. }(EasingFunction));
  47870. BABYLON.PowerEase = PowerEase;
  47871. var QuadraticEase = /** @class */ (function (_super) {
  47872. __extends(QuadraticEase, _super);
  47873. function QuadraticEase() {
  47874. return _super !== null && _super.apply(this, arguments) || this;
  47875. }
  47876. QuadraticEase.prototype.easeInCore = function (gradient) {
  47877. return (gradient * gradient);
  47878. };
  47879. return QuadraticEase;
  47880. }(EasingFunction));
  47881. BABYLON.QuadraticEase = QuadraticEase;
  47882. var QuarticEase = /** @class */ (function (_super) {
  47883. __extends(QuarticEase, _super);
  47884. function QuarticEase() {
  47885. return _super !== null && _super.apply(this, arguments) || this;
  47886. }
  47887. QuarticEase.prototype.easeInCore = function (gradient) {
  47888. return (gradient * gradient * gradient * gradient);
  47889. };
  47890. return QuarticEase;
  47891. }(EasingFunction));
  47892. BABYLON.QuarticEase = QuarticEase;
  47893. var QuinticEase = /** @class */ (function (_super) {
  47894. __extends(QuinticEase, _super);
  47895. function QuinticEase() {
  47896. return _super !== null && _super.apply(this, arguments) || this;
  47897. }
  47898. QuinticEase.prototype.easeInCore = function (gradient) {
  47899. return (gradient * gradient * gradient * gradient * gradient);
  47900. };
  47901. return QuinticEase;
  47902. }(EasingFunction));
  47903. BABYLON.QuinticEase = QuinticEase;
  47904. var SineEase = /** @class */ (function (_super) {
  47905. __extends(SineEase, _super);
  47906. function SineEase() {
  47907. return _super !== null && _super.apply(this, arguments) || this;
  47908. }
  47909. SineEase.prototype.easeInCore = function (gradient) {
  47910. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47911. };
  47912. return SineEase;
  47913. }(EasingFunction));
  47914. BABYLON.SineEase = SineEase;
  47915. var BezierCurveEase = /** @class */ (function (_super) {
  47916. __extends(BezierCurveEase, _super);
  47917. function BezierCurveEase(x1, y1, x2, y2) {
  47918. if (x1 === void 0) { x1 = 0; }
  47919. if (y1 === void 0) { y1 = 0; }
  47920. if (x2 === void 0) { x2 = 1; }
  47921. if (y2 === void 0) { y2 = 1; }
  47922. var _this = _super.call(this) || this;
  47923. _this.x1 = x1;
  47924. _this.y1 = y1;
  47925. _this.x2 = x2;
  47926. _this.y2 = y2;
  47927. return _this;
  47928. }
  47929. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47930. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47931. };
  47932. return BezierCurveEase;
  47933. }(EasingFunction));
  47934. BABYLON.BezierCurveEase = BezierCurveEase;
  47935. })(BABYLON || (BABYLON = {}));
  47936. //# sourceMappingURL=babylon.easing.js.map
  47937. var BABYLON;
  47938. (function (BABYLON) {
  47939. var Condition = /** @class */ (function () {
  47940. function Condition(actionManager) {
  47941. this._actionManager = actionManager;
  47942. }
  47943. Condition.prototype.isValid = function () {
  47944. return true;
  47945. };
  47946. Condition.prototype._getProperty = function (propertyPath) {
  47947. return this._actionManager._getProperty(propertyPath);
  47948. };
  47949. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47950. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47951. };
  47952. Condition.prototype.serialize = function () {
  47953. };
  47954. Condition.prototype._serialize = function (serializedCondition) {
  47955. return {
  47956. type: 2,
  47957. children: [],
  47958. name: serializedCondition.name,
  47959. properties: serializedCondition.properties
  47960. };
  47961. };
  47962. return Condition;
  47963. }());
  47964. BABYLON.Condition = Condition;
  47965. var ValueCondition = /** @class */ (function (_super) {
  47966. __extends(ValueCondition, _super);
  47967. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47968. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47969. var _this = _super.call(this, actionManager) || this;
  47970. _this.propertyPath = propertyPath;
  47971. _this.value = value;
  47972. _this.operator = operator;
  47973. _this._target = target;
  47974. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47975. _this._property = _this._getProperty(_this.propertyPath);
  47976. return _this;
  47977. }
  47978. Object.defineProperty(ValueCondition, "IsEqual", {
  47979. get: function () {
  47980. return ValueCondition._IsEqual;
  47981. },
  47982. enumerable: true,
  47983. configurable: true
  47984. });
  47985. Object.defineProperty(ValueCondition, "IsDifferent", {
  47986. get: function () {
  47987. return ValueCondition._IsDifferent;
  47988. },
  47989. enumerable: true,
  47990. configurable: true
  47991. });
  47992. Object.defineProperty(ValueCondition, "IsGreater", {
  47993. get: function () {
  47994. return ValueCondition._IsGreater;
  47995. },
  47996. enumerable: true,
  47997. configurable: true
  47998. });
  47999. Object.defineProperty(ValueCondition, "IsLesser", {
  48000. get: function () {
  48001. return ValueCondition._IsLesser;
  48002. },
  48003. enumerable: true,
  48004. configurable: true
  48005. });
  48006. // Methods
  48007. ValueCondition.prototype.isValid = function () {
  48008. switch (this.operator) {
  48009. case ValueCondition.IsGreater:
  48010. return this._effectiveTarget[this._property] > this.value;
  48011. case ValueCondition.IsLesser:
  48012. return this._effectiveTarget[this._property] < this.value;
  48013. case ValueCondition.IsEqual:
  48014. case ValueCondition.IsDifferent:
  48015. var check;
  48016. if (this.value.equals) {
  48017. check = this.value.equals(this._effectiveTarget[this._property]);
  48018. }
  48019. else {
  48020. check = this.value === this._effectiveTarget[this._property];
  48021. }
  48022. return this.operator === ValueCondition.IsEqual ? check : !check;
  48023. }
  48024. return false;
  48025. };
  48026. ValueCondition.prototype.serialize = function () {
  48027. return this._serialize({
  48028. name: "ValueCondition",
  48029. properties: [
  48030. BABYLON.Action._GetTargetProperty(this._target),
  48031. { name: "propertyPath", value: this.propertyPath },
  48032. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48033. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48034. ]
  48035. });
  48036. };
  48037. ValueCondition.GetOperatorName = function (operator) {
  48038. switch (operator) {
  48039. case ValueCondition._IsEqual: return "IsEqual";
  48040. case ValueCondition._IsDifferent: return "IsDifferent";
  48041. case ValueCondition._IsGreater: return "IsGreater";
  48042. case ValueCondition._IsLesser: return "IsLesser";
  48043. default: return "";
  48044. }
  48045. };
  48046. // Statics
  48047. ValueCondition._IsEqual = 0;
  48048. ValueCondition._IsDifferent = 1;
  48049. ValueCondition._IsGreater = 2;
  48050. ValueCondition._IsLesser = 3;
  48051. return ValueCondition;
  48052. }(Condition));
  48053. BABYLON.ValueCondition = ValueCondition;
  48054. var PredicateCondition = /** @class */ (function (_super) {
  48055. __extends(PredicateCondition, _super);
  48056. function PredicateCondition(actionManager, predicate) {
  48057. var _this = _super.call(this, actionManager) || this;
  48058. _this.predicate = predicate;
  48059. return _this;
  48060. }
  48061. PredicateCondition.prototype.isValid = function () {
  48062. return this.predicate();
  48063. };
  48064. return PredicateCondition;
  48065. }(Condition));
  48066. BABYLON.PredicateCondition = PredicateCondition;
  48067. var StateCondition = /** @class */ (function (_super) {
  48068. __extends(StateCondition, _super);
  48069. function StateCondition(actionManager, target, value) {
  48070. var _this = _super.call(this, actionManager) || this;
  48071. _this.value = value;
  48072. _this._target = target;
  48073. return _this;
  48074. }
  48075. // Methods
  48076. StateCondition.prototype.isValid = function () {
  48077. return this._target.state === this.value;
  48078. };
  48079. StateCondition.prototype.serialize = function () {
  48080. return this._serialize({
  48081. name: "StateCondition",
  48082. properties: [
  48083. BABYLON.Action._GetTargetProperty(this._target),
  48084. { name: "value", value: this.value }
  48085. ]
  48086. });
  48087. };
  48088. return StateCondition;
  48089. }(Condition));
  48090. BABYLON.StateCondition = StateCondition;
  48091. })(BABYLON || (BABYLON = {}));
  48092. //# sourceMappingURL=babylon.condition.js.map
  48093. var BABYLON;
  48094. (function (BABYLON) {
  48095. var Action = /** @class */ (function () {
  48096. function Action(triggerOptions, condition) {
  48097. this.triggerOptions = triggerOptions;
  48098. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48099. if (triggerOptions.parameter) {
  48100. this.trigger = triggerOptions.trigger;
  48101. this._triggerParameter = triggerOptions.parameter;
  48102. }
  48103. else {
  48104. this.trigger = triggerOptions;
  48105. }
  48106. this._nextActiveAction = this;
  48107. this._condition = condition;
  48108. }
  48109. // Methods
  48110. Action.prototype._prepare = function () {
  48111. };
  48112. Action.prototype.getTriggerParameter = function () {
  48113. return this._triggerParameter;
  48114. };
  48115. Action.prototype._executeCurrent = function (evt) {
  48116. if (this._nextActiveAction._condition) {
  48117. var condition = this._nextActiveAction._condition;
  48118. var currentRenderId = this._actionManager.getScene().getRenderId();
  48119. // We cache the current evaluation for the current frame
  48120. if (condition._evaluationId === currentRenderId) {
  48121. if (!condition._currentResult) {
  48122. return;
  48123. }
  48124. }
  48125. else {
  48126. condition._evaluationId = currentRenderId;
  48127. if (!condition.isValid()) {
  48128. condition._currentResult = false;
  48129. return;
  48130. }
  48131. condition._currentResult = true;
  48132. }
  48133. }
  48134. this.onBeforeExecuteObservable.notifyObservers(this);
  48135. this._nextActiveAction.execute(evt);
  48136. this.skipToNextActiveAction();
  48137. };
  48138. Action.prototype.execute = function (evt) {
  48139. };
  48140. Action.prototype.skipToNextActiveAction = function () {
  48141. if (this._nextActiveAction._child) {
  48142. if (!this._nextActiveAction._child._actionManager) {
  48143. this._nextActiveAction._child._actionManager = this._actionManager;
  48144. }
  48145. this._nextActiveAction = this._nextActiveAction._child;
  48146. }
  48147. else {
  48148. this._nextActiveAction = this;
  48149. }
  48150. };
  48151. Action.prototype.then = function (action) {
  48152. this._child = action;
  48153. action._actionManager = this._actionManager;
  48154. action._prepare();
  48155. return action;
  48156. };
  48157. Action.prototype._getProperty = function (propertyPath) {
  48158. return this._actionManager._getProperty(propertyPath);
  48159. };
  48160. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48161. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48162. };
  48163. Action.prototype.serialize = function (parent) {
  48164. };
  48165. // Called by BABYLON.Action objects in serialize(...). Internal use
  48166. Action.prototype._serialize = function (serializedAction, parent) {
  48167. var serializationObject = {
  48168. type: 1,
  48169. children: [],
  48170. name: serializedAction.name,
  48171. properties: serializedAction.properties || []
  48172. };
  48173. // Serialize child
  48174. if (this._child) {
  48175. this._child.serialize(serializationObject);
  48176. }
  48177. // Check if "this" has a condition
  48178. if (this._condition) {
  48179. var serializedCondition = this._condition.serialize();
  48180. serializedCondition.children.push(serializationObject);
  48181. if (parent) {
  48182. parent.children.push(serializedCondition);
  48183. }
  48184. return serializedCondition;
  48185. }
  48186. if (parent) {
  48187. parent.children.push(serializationObject);
  48188. }
  48189. return serializationObject;
  48190. };
  48191. Action._SerializeValueAsString = function (value) {
  48192. if (typeof value === "number") {
  48193. return value.toString();
  48194. }
  48195. if (typeof value === "boolean") {
  48196. return value ? "true" : "false";
  48197. }
  48198. if (value instanceof BABYLON.Vector2) {
  48199. return value.x + ", " + value.y;
  48200. }
  48201. if (value instanceof BABYLON.Vector3) {
  48202. return value.x + ", " + value.y + ", " + value.z;
  48203. }
  48204. if (value instanceof BABYLON.Color3) {
  48205. return value.r + ", " + value.g + ", " + value.b;
  48206. }
  48207. if (value instanceof BABYLON.Color4) {
  48208. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48209. }
  48210. return value; // string
  48211. };
  48212. Action._GetTargetProperty = function (target) {
  48213. return {
  48214. name: "target",
  48215. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48216. : target instanceof BABYLON.Light ? "LightProperties"
  48217. : target instanceof BABYLON.Camera ? "CameraProperties"
  48218. : "SceneProperties",
  48219. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48220. };
  48221. };
  48222. return Action;
  48223. }());
  48224. BABYLON.Action = Action;
  48225. })(BABYLON || (BABYLON = {}));
  48226. //# sourceMappingURL=babylon.action.js.map
  48227. var BABYLON;
  48228. (function (BABYLON) {
  48229. /**
  48230. * ActionEvent is the event beint sent when an action is triggered.
  48231. */
  48232. var ActionEvent = /** @class */ (function () {
  48233. /**
  48234. * @param source The mesh or sprite that triggered the action.
  48235. * @param pointerX The X mouse cursor position at the time of the event
  48236. * @param pointerY The Y mouse cursor position at the time of the event
  48237. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48238. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48239. */
  48240. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48241. this.source = source;
  48242. this.pointerX = pointerX;
  48243. this.pointerY = pointerY;
  48244. this.meshUnderPointer = meshUnderPointer;
  48245. this.sourceEvent = sourceEvent;
  48246. this.additionalData = additionalData;
  48247. }
  48248. /**
  48249. * Helper function to auto-create an ActionEvent from a source mesh.
  48250. * @param source The source mesh that triggered the event
  48251. * @param evt {Event} The original (browser) event
  48252. */
  48253. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48254. var scene = source.getScene();
  48255. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48256. };
  48257. /**
  48258. * Helper function to auto-create an ActionEvent from a source mesh.
  48259. * @param source The source sprite that triggered the event
  48260. * @param scene Scene associated with the sprite
  48261. * @param evt {Event} The original (browser) event
  48262. */
  48263. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48264. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48265. };
  48266. /**
  48267. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48268. * @param scene the scene where the event occurred
  48269. * @param evt {Event} The original (browser) event
  48270. */
  48271. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48272. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48273. };
  48274. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48275. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48276. };
  48277. return ActionEvent;
  48278. }());
  48279. BABYLON.ActionEvent = ActionEvent;
  48280. /**
  48281. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48282. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48283. */
  48284. var ActionManager = /** @class */ (function () {
  48285. function ActionManager(scene) {
  48286. // Members
  48287. this.actions = new Array();
  48288. this.hoverCursor = '';
  48289. this._scene = scene;
  48290. scene._actionManagers.push(this);
  48291. }
  48292. Object.defineProperty(ActionManager, "NothingTrigger", {
  48293. get: function () {
  48294. return ActionManager._NothingTrigger;
  48295. },
  48296. enumerable: true,
  48297. configurable: true
  48298. });
  48299. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48300. get: function () {
  48301. return ActionManager._OnPickTrigger;
  48302. },
  48303. enumerable: true,
  48304. configurable: true
  48305. });
  48306. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48307. get: function () {
  48308. return ActionManager._OnLeftPickTrigger;
  48309. },
  48310. enumerable: true,
  48311. configurable: true
  48312. });
  48313. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48314. get: function () {
  48315. return ActionManager._OnRightPickTrigger;
  48316. },
  48317. enumerable: true,
  48318. configurable: true
  48319. });
  48320. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48321. get: function () {
  48322. return ActionManager._OnCenterPickTrigger;
  48323. },
  48324. enumerable: true,
  48325. configurable: true
  48326. });
  48327. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48328. get: function () {
  48329. return ActionManager._OnPickDownTrigger;
  48330. },
  48331. enumerable: true,
  48332. configurable: true
  48333. });
  48334. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48335. get: function () {
  48336. return ActionManager._OnDoublePickTrigger;
  48337. },
  48338. enumerable: true,
  48339. configurable: true
  48340. });
  48341. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48342. get: function () {
  48343. return ActionManager._OnPickUpTrigger;
  48344. },
  48345. enumerable: true,
  48346. configurable: true
  48347. });
  48348. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48349. /// This trigger will only be raised if you also declared a OnPickDown
  48350. get: function () {
  48351. return ActionManager._OnPickOutTrigger;
  48352. },
  48353. enumerable: true,
  48354. configurable: true
  48355. });
  48356. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48357. get: function () {
  48358. return ActionManager._OnLongPressTrigger;
  48359. },
  48360. enumerable: true,
  48361. configurable: true
  48362. });
  48363. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48364. get: function () {
  48365. return ActionManager._OnPointerOverTrigger;
  48366. },
  48367. enumerable: true,
  48368. configurable: true
  48369. });
  48370. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48371. get: function () {
  48372. return ActionManager._OnPointerOutTrigger;
  48373. },
  48374. enumerable: true,
  48375. configurable: true
  48376. });
  48377. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48378. get: function () {
  48379. return ActionManager._OnEveryFrameTrigger;
  48380. },
  48381. enumerable: true,
  48382. configurable: true
  48383. });
  48384. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48385. get: function () {
  48386. return ActionManager._OnIntersectionEnterTrigger;
  48387. },
  48388. enumerable: true,
  48389. configurable: true
  48390. });
  48391. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48392. get: function () {
  48393. return ActionManager._OnIntersectionExitTrigger;
  48394. },
  48395. enumerable: true,
  48396. configurable: true
  48397. });
  48398. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48399. get: function () {
  48400. return ActionManager._OnKeyDownTrigger;
  48401. },
  48402. enumerable: true,
  48403. configurable: true
  48404. });
  48405. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48406. get: function () {
  48407. return ActionManager._OnKeyUpTrigger;
  48408. },
  48409. enumerable: true,
  48410. configurable: true
  48411. });
  48412. // Methods
  48413. ActionManager.prototype.dispose = function () {
  48414. var index = this._scene._actionManagers.indexOf(this);
  48415. for (var i = 0; i < this.actions.length; i++) {
  48416. var action = this.actions[i];
  48417. ActionManager.Triggers[action.trigger]--;
  48418. if (ActionManager.Triggers[action.trigger] === 0) {
  48419. delete ActionManager.Triggers[action.trigger];
  48420. }
  48421. }
  48422. if (index > -1) {
  48423. this._scene._actionManagers.splice(index, 1);
  48424. }
  48425. };
  48426. ActionManager.prototype.getScene = function () {
  48427. return this._scene;
  48428. };
  48429. /**
  48430. * Does this action manager handles actions of any of the given triggers
  48431. * @param {number[]} triggers - the triggers to be tested
  48432. * @return {boolean} whether one (or more) of the triggers is handeled
  48433. */
  48434. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48435. for (var index = 0; index < this.actions.length; index++) {
  48436. var action = this.actions[index];
  48437. if (triggers.indexOf(action.trigger) > -1) {
  48438. return true;
  48439. }
  48440. }
  48441. return false;
  48442. };
  48443. /**
  48444. * Does this action manager handles actions of a given trigger
  48445. * @param {number} trigger - the trigger to be tested
  48446. * @return {boolean} whether the trigger is handeled
  48447. */
  48448. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48449. for (var index = 0; index < this.actions.length; index++) {
  48450. var action = this.actions[index];
  48451. if (action.trigger === trigger) {
  48452. return true;
  48453. }
  48454. }
  48455. return false;
  48456. };
  48457. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48458. /**
  48459. * Does this action manager has pointer triggers
  48460. * @return {boolean} whether or not it has pointer triggers
  48461. */
  48462. get: function () {
  48463. for (var index = 0; index < this.actions.length; index++) {
  48464. var action = this.actions[index];
  48465. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48466. return true;
  48467. }
  48468. }
  48469. return false;
  48470. },
  48471. enumerable: true,
  48472. configurable: true
  48473. });
  48474. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48475. /**
  48476. * Does this action manager has pick triggers
  48477. * @return {boolean} whether or not it has pick triggers
  48478. */
  48479. get: function () {
  48480. for (var index = 0; index < this.actions.length; index++) {
  48481. var action = this.actions[index];
  48482. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48483. return true;
  48484. }
  48485. }
  48486. return false;
  48487. },
  48488. enumerable: true,
  48489. configurable: true
  48490. });
  48491. Object.defineProperty(ActionManager, "HasTriggers", {
  48492. /**
  48493. * Does exist one action manager with at least one trigger
  48494. * @return {boolean} whether or not it exists one action manager with one trigger
  48495. **/
  48496. get: function () {
  48497. for (var t in ActionManager.Triggers) {
  48498. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48499. return true;
  48500. }
  48501. }
  48502. return false;
  48503. },
  48504. enumerable: true,
  48505. configurable: true
  48506. });
  48507. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48508. /**
  48509. * Does exist one action manager with at least one pick trigger
  48510. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48511. **/
  48512. get: function () {
  48513. for (var t in ActionManager.Triggers) {
  48514. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48515. var t_int = parseInt(t);
  48516. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48517. return true;
  48518. }
  48519. }
  48520. }
  48521. return false;
  48522. },
  48523. enumerable: true,
  48524. configurable: true
  48525. });
  48526. /**
  48527. * Does exist one action manager that handles actions of a given trigger
  48528. * @param {number} trigger - the trigger to be tested
  48529. * @return {boolean} whether the trigger is handeled by at least one action manager
  48530. **/
  48531. ActionManager.HasSpecificTrigger = function (trigger) {
  48532. for (var t in ActionManager.Triggers) {
  48533. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48534. var t_int = parseInt(t);
  48535. if (t_int === trigger) {
  48536. return true;
  48537. }
  48538. }
  48539. }
  48540. return false;
  48541. };
  48542. /**
  48543. * Registers an action to this action manager
  48544. * @param {BABYLON.Action} action - the action to be registered
  48545. * @return {BABYLON.Action} the action amended (prepared) after registration
  48546. */
  48547. ActionManager.prototype.registerAction = function (action) {
  48548. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48549. if (this.getScene().actionManager !== this) {
  48550. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48551. return null;
  48552. }
  48553. }
  48554. this.actions.push(action);
  48555. if (ActionManager.Triggers[action.trigger]) {
  48556. ActionManager.Triggers[action.trigger]++;
  48557. }
  48558. else {
  48559. ActionManager.Triggers[action.trigger] = 1;
  48560. }
  48561. action._actionManager = this;
  48562. action._prepare();
  48563. return action;
  48564. };
  48565. /**
  48566. * Unregisters an action to this action manager
  48567. * @param action The action to be unregistered
  48568. * @return whether the action has been unregistered
  48569. */
  48570. ActionManager.prototype.unregisterAction = function (action) {
  48571. var index = this.actions.indexOf(action);
  48572. if (index !== -1) {
  48573. this.actions.splice(index, 1);
  48574. ActionManager.Triggers[action.trigger] -= 1;
  48575. if (ActionManager.Triggers[action.trigger] === 0) {
  48576. delete ActionManager.Triggers[action.trigger];
  48577. }
  48578. delete action._actionManager;
  48579. return true;
  48580. }
  48581. return false;
  48582. };
  48583. /**
  48584. * Process a specific trigger
  48585. * @param {number} trigger - the trigger to process
  48586. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48587. */
  48588. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48589. for (var index = 0; index < this.actions.length; index++) {
  48590. var action = this.actions[index];
  48591. if (action.trigger === trigger) {
  48592. if (evt) {
  48593. if (trigger === ActionManager.OnKeyUpTrigger
  48594. || trigger === ActionManager.OnKeyDownTrigger) {
  48595. var parameter = action.getTriggerParameter();
  48596. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48597. if (!parameter.toLowerCase) {
  48598. continue;
  48599. }
  48600. var lowerCase = parameter.toLowerCase();
  48601. if (lowerCase !== evt.sourceEvent.key) {
  48602. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48603. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48604. if (actualkey !== lowerCase) {
  48605. continue;
  48606. }
  48607. }
  48608. }
  48609. }
  48610. }
  48611. action._executeCurrent(evt);
  48612. }
  48613. }
  48614. };
  48615. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48616. var properties = propertyPath.split(".");
  48617. for (var index = 0; index < properties.length - 1; index++) {
  48618. target = target[properties[index]];
  48619. }
  48620. return target;
  48621. };
  48622. ActionManager.prototype._getProperty = function (propertyPath) {
  48623. var properties = propertyPath.split(".");
  48624. return properties[properties.length - 1];
  48625. };
  48626. ActionManager.prototype.serialize = function (name) {
  48627. var root = {
  48628. children: new Array(),
  48629. name: name,
  48630. type: 3,
  48631. properties: new Array() // Empty for root but required
  48632. };
  48633. for (var i = 0; i < this.actions.length; i++) {
  48634. var triggerObject = {
  48635. type: 0,
  48636. children: new Array(),
  48637. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48638. properties: new Array()
  48639. };
  48640. var triggerOptions = this.actions[i].triggerOptions;
  48641. if (triggerOptions && typeof triggerOptions !== "number") {
  48642. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48643. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48644. }
  48645. else {
  48646. var parameter = {};
  48647. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48648. if (triggerOptions.parameter.mesh) {
  48649. parameter._meshId = triggerOptions.parameter.mesh.id;
  48650. }
  48651. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48652. }
  48653. }
  48654. // Serialize child action, recursively
  48655. this.actions[i].serialize(triggerObject);
  48656. // Add serialized trigger
  48657. root.children.push(triggerObject);
  48658. }
  48659. return root;
  48660. };
  48661. ActionManager.Parse = function (parsedActions, object, scene) {
  48662. var actionManager = new ActionManager(scene);
  48663. if (object === null)
  48664. scene.actionManager = actionManager;
  48665. else
  48666. object.actionManager = actionManager;
  48667. // instanciate a new object
  48668. var instanciate = function (name, params) {
  48669. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48670. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48671. newInstance.constructor.apply(newInstance, params);
  48672. return newInstance;
  48673. };
  48674. var parseParameter = function (name, value, target, propertyPath) {
  48675. if (propertyPath === null) {
  48676. // String, boolean or float
  48677. var floatValue = parseFloat(value);
  48678. if (value === "true" || value === "false")
  48679. return value === "true";
  48680. else
  48681. return isNaN(floatValue) ? value : floatValue;
  48682. }
  48683. var effectiveTarget = propertyPath.split(".");
  48684. var values = value.split(",");
  48685. // Get effective Target
  48686. for (var i = 0; i < effectiveTarget.length; i++) {
  48687. target = target[effectiveTarget[i]];
  48688. }
  48689. // Return appropriate value with its type
  48690. if (typeof (target) === "boolean")
  48691. return values[0] === "true";
  48692. if (typeof (target) === "string")
  48693. return values[0];
  48694. // Parameters with multiple values such as Vector3 etc.
  48695. var split = new Array();
  48696. for (var i = 0; i < values.length; i++)
  48697. split.push(parseFloat(values[i]));
  48698. if (target instanceof BABYLON.Vector3)
  48699. return BABYLON.Vector3.FromArray(split);
  48700. if (target instanceof BABYLON.Vector4)
  48701. return BABYLON.Vector4.FromArray(split);
  48702. if (target instanceof BABYLON.Color3)
  48703. return BABYLON.Color3.FromArray(split);
  48704. if (target instanceof BABYLON.Color4)
  48705. return BABYLON.Color4.FromArray(split);
  48706. return parseFloat(values[0]);
  48707. };
  48708. // traverse graph per trigger
  48709. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48710. if (combineArray === void 0) { combineArray = null; }
  48711. if (parsedAction.detached)
  48712. return;
  48713. var parameters = new Array();
  48714. var target = null;
  48715. var propertyPath = null;
  48716. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48717. // Parameters
  48718. if (parsedAction.type === 2)
  48719. parameters.push(actionManager);
  48720. else
  48721. parameters.push(trigger);
  48722. if (combine) {
  48723. var actions = new Array();
  48724. for (var j = 0; j < parsedAction.combine.length; j++) {
  48725. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48726. }
  48727. parameters.push(actions);
  48728. }
  48729. else {
  48730. for (var i = 0; i < parsedAction.properties.length; i++) {
  48731. var value = parsedAction.properties[i].value;
  48732. var name = parsedAction.properties[i].name;
  48733. var targetType = parsedAction.properties[i].targetType;
  48734. if (name === "target")
  48735. if (targetType !== null && targetType === "SceneProperties")
  48736. value = target = scene;
  48737. else
  48738. value = target = scene.getNodeByName(value);
  48739. else if (name === "parent")
  48740. value = scene.getNodeByName(value);
  48741. else if (name === "sound")
  48742. value = scene.getSoundByName(value);
  48743. else if (name !== "propertyPath") {
  48744. if (parsedAction.type === 2 && name === "operator")
  48745. value = BABYLON.ValueCondition[value];
  48746. else
  48747. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48748. }
  48749. else {
  48750. propertyPath = value;
  48751. }
  48752. parameters.push(value);
  48753. }
  48754. }
  48755. if (combineArray === null) {
  48756. parameters.push(condition);
  48757. }
  48758. else {
  48759. parameters.push(null);
  48760. }
  48761. // If interpolate value action
  48762. if (parsedAction.name === "InterpolateValueAction") {
  48763. var param = parameters[parameters.length - 2];
  48764. parameters[parameters.length - 1] = param;
  48765. parameters[parameters.length - 2] = condition;
  48766. }
  48767. // Action or condition(s) and not CombineAction
  48768. var newAction = instanciate(parsedAction.name, parameters);
  48769. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48770. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48771. if (action)
  48772. action.then(nothing);
  48773. else
  48774. actionManager.registerAction(nothing);
  48775. action = nothing;
  48776. }
  48777. if (combineArray === null) {
  48778. if (newAction instanceof BABYLON.Condition) {
  48779. condition = newAction;
  48780. newAction = action;
  48781. }
  48782. else {
  48783. condition = null;
  48784. if (action)
  48785. action.then(newAction);
  48786. else
  48787. actionManager.registerAction(newAction);
  48788. }
  48789. }
  48790. else {
  48791. combineArray.push(newAction);
  48792. }
  48793. for (var i = 0; i < parsedAction.children.length; i++)
  48794. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48795. };
  48796. // triggers
  48797. for (var i = 0; i < parsedActions.children.length; i++) {
  48798. var triggerParams;
  48799. var trigger = parsedActions.children[i];
  48800. if (trigger.properties.length > 0) {
  48801. var param = trigger.properties[0].value;
  48802. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48803. if (value._meshId) {
  48804. value.mesh = scene.getMeshByID(value._meshId);
  48805. }
  48806. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48807. }
  48808. else
  48809. triggerParams = ActionManager[trigger.name];
  48810. for (var j = 0; j < trigger.children.length; j++) {
  48811. if (!trigger.detached)
  48812. traverse(trigger.children[j], triggerParams, null, null);
  48813. }
  48814. }
  48815. };
  48816. ActionManager.GetTriggerName = function (trigger) {
  48817. switch (trigger) {
  48818. case 0: return "NothingTrigger";
  48819. case 1: return "OnPickTrigger";
  48820. case 2: return "OnLeftPickTrigger";
  48821. case 3: return "OnRightPickTrigger";
  48822. case 4: return "OnCenterPickTrigger";
  48823. case 5: return "OnPickDownTrigger";
  48824. case 6: return "OnPickUpTrigger";
  48825. case 7: return "OnLongPressTrigger";
  48826. case 8: return "OnPointerOverTrigger";
  48827. case 9: return "OnPointerOutTrigger";
  48828. case 10: return "OnEveryFrameTrigger";
  48829. case 11: return "OnIntersectionEnterTrigger";
  48830. case 12: return "OnIntersectionExitTrigger";
  48831. case 13: return "OnKeyDownTrigger";
  48832. case 14: return "OnKeyUpTrigger";
  48833. case 15: return "OnPickOutTrigger";
  48834. default: return "";
  48835. }
  48836. };
  48837. // Statics
  48838. ActionManager._NothingTrigger = 0;
  48839. ActionManager._OnPickTrigger = 1;
  48840. ActionManager._OnLeftPickTrigger = 2;
  48841. ActionManager._OnRightPickTrigger = 3;
  48842. ActionManager._OnCenterPickTrigger = 4;
  48843. ActionManager._OnPickDownTrigger = 5;
  48844. ActionManager._OnDoublePickTrigger = 6;
  48845. ActionManager._OnPickUpTrigger = 7;
  48846. ActionManager._OnLongPressTrigger = 8;
  48847. ActionManager._OnPointerOverTrigger = 9;
  48848. ActionManager._OnPointerOutTrigger = 10;
  48849. ActionManager._OnEveryFrameTrigger = 11;
  48850. ActionManager._OnIntersectionEnterTrigger = 12;
  48851. ActionManager._OnIntersectionExitTrigger = 13;
  48852. ActionManager._OnKeyDownTrigger = 14;
  48853. ActionManager._OnKeyUpTrigger = 15;
  48854. ActionManager._OnPickOutTrigger = 16;
  48855. ActionManager.Triggers = {};
  48856. return ActionManager;
  48857. }());
  48858. BABYLON.ActionManager = ActionManager;
  48859. })(BABYLON || (BABYLON = {}));
  48860. //# sourceMappingURL=babylon.actionManager.js.map
  48861. var BABYLON;
  48862. (function (BABYLON) {
  48863. var InterpolateValueAction = /** @class */ (function (_super) {
  48864. __extends(InterpolateValueAction, _super);
  48865. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48866. if (duration === void 0) { duration = 1000; }
  48867. var _this = _super.call(this, triggerOptions, condition) || this;
  48868. _this.propertyPath = propertyPath;
  48869. _this.value = value;
  48870. _this.duration = duration;
  48871. _this.stopOtherAnimations = stopOtherAnimations;
  48872. _this.onInterpolationDone = onInterpolationDone;
  48873. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48874. _this._target = _this._effectiveTarget = target;
  48875. return _this;
  48876. }
  48877. InterpolateValueAction.prototype._prepare = function () {
  48878. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48879. this._property = this._getProperty(this.propertyPath);
  48880. };
  48881. InterpolateValueAction.prototype.execute = function () {
  48882. var _this = this;
  48883. var scene = this._actionManager.getScene();
  48884. var keys = [
  48885. {
  48886. frame: 0,
  48887. value: this._effectiveTarget[this._property]
  48888. }, {
  48889. frame: 100,
  48890. value: this.value
  48891. }
  48892. ];
  48893. var dataType;
  48894. if (typeof this.value === "number") {
  48895. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48896. }
  48897. else if (this.value instanceof BABYLON.Color3) {
  48898. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48899. }
  48900. else if (this.value instanceof BABYLON.Vector3) {
  48901. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48902. }
  48903. else if (this.value instanceof BABYLON.Matrix) {
  48904. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48905. }
  48906. else if (this.value instanceof BABYLON.Quaternion) {
  48907. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48908. }
  48909. else {
  48910. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48911. return;
  48912. }
  48913. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48914. animation.setKeys(keys);
  48915. if (this.stopOtherAnimations) {
  48916. scene.stopAnimation(this._effectiveTarget);
  48917. }
  48918. var wrapper = function () {
  48919. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48920. if (_this.onInterpolationDone) {
  48921. _this.onInterpolationDone();
  48922. }
  48923. };
  48924. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48925. };
  48926. InterpolateValueAction.prototype.serialize = function (parent) {
  48927. return _super.prototype._serialize.call(this, {
  48928. name: "InterpolateValueAction",
  48929. properties: [
  48930. BABYLON.Action._GetTargetProperty(this._target),
  48931. { name: "propertyPath", value: this.propertyPath },
  48932. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48933. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48934. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48935. ]
  48936. }, parent);
  48937. };
  48938. return InterpolateValueAction;
  48939. }(BABYLON.Action));
  48940. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48941. })(BABYLON || (BABYLON = {}));
  48942. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48943. var BABYLON;
  48944. (function (BABYLON) {
  48945. var SwitchBooleanAction = /** @class */ (function (_super) {
  48946. __extends(SwitchBooleanAction, _super);
  48947. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48948. var _this = _super.call(this, triggerOptions, condition) || this;
  48949. _this.propertyPath = propertyPath;
  48950. _this._target = _this._effectiveTarget = target;
  48951. return _this;
  48952. }
  48953. SwitchBooleanAction.prototype._prepare = function () {
  48954. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48955. this._property = this._getProperty(this.propertyPath);
  48956. };
  48957. SwitchBooleanAction.prototype.execute = function () {
  48958. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48959. };
  48960. SwitchBooleanAction.prototype.serialize = function (parent) {
  48961. return _super.prototype._serialize.call(this, {
  48962. name: "SwitchBooleanAction",
  48963. properties: [
  48964. BABYLON.Action._GetTargetProperty(this._target),
  48965. { name: "propertyPath", value: this.propertyPath }
  48966. ]
  48967. }, parent);
  48968. };
  48969. return SwitchBooleanAction;
  48970. }(BABYLON.Action));
  48971. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48972. var SetStateAction = /** @class */ (function (_super) {
  48973. __extends(SetStateAction, _super);
  48974. function SetStateAction(triggerOptions, target, value, condition) {
  48975. var _this = _super.call(this, triggerOptions, condition) || this;
  48976. _this.value = value;
  48977. _this._target = target;
  48978. return _this;
  48979. }
  48980. SetStateAction.prototype.execute = function () {
  48981. this._target.state = this.value;
  48982. };
  48983. SetStateAction.prototype.serialize = function (parent) {
  48984. return _super.prototype._serialize.call(this, {
  48985. name: "SetStateAction",
  48986. properties: [
  48987. BABYLON.Action._GetTargetProperty(this._target),
  48988. { name: "value", value: this.value }
  48989. ]
  48990. }, parent);
  48991. };
  48992. return SetStateAction;
  48993. }(BABYLON.Action));
  48994. BABYLON.SetStateAction = SetStateAction;
  48995. var SetValueAction = /** @class */ (function (_super) {
  48996. __extends(SetValueAction, _super);
  48997. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48998. var _this = _super.call(this, triggerOptions, condition) || this;
  48999. _this.propertyPath = propertyPath;
  49000. _this.value = value;
  49001. _this._target = _this._effectiveTarget = target;
  49002. return _this;
  49003. }
  49004. SetValueAction.prototype._prepare = function () {
  49005. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49006. this._property = this._getProperty(this.propertyPath);
  49007. };
  49008. SetValueAction.prototype.execute = function () {
  49009. this._effectiveTarget[this._property] = this.value;
  49010. if (this._target.markAsDirty) {
  49011. this._target.markAsDirty(this._property);
  49012. }
  49013. };
  49014. SetValueAction.prototype.serialize = function (parent) {
  49015. return _super.prototype._serialize.call(this, {
  49016. name: "SetValueAction",
  49017. properties: [
  49018. BABYLON.Action._GetTargetProperty(this._target),
  49019. { name: "propertyPath", value: this.propertyPath },
  49020. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49021. ]
  49022. }, parent);
  49023. };
  49024. return SetValueAction;
  49025. }(BABYLON.Action));
  49026. BABYLON.SetValueAction = SetValueAction;
  49027. var IncrementValueAction = /** @class */ (function (_super) {
  49028. __extends(IncrementValueAction, _super);
  49029. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49030. var _this = _super.call(this, triggerOptions, condition) || this;
  49031. _this.propertyPath = propertyPath;
  49032. _this.value = value;
  49033. _this._target = _this._effectiveTarget = target;
  49034. return _this;
  49035. }
  49036. IncrementValueAction.prototype._prepare = function () {
  49037. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49038. this._property = this._getProperty(this.propertyPath);
  49039. if (typeof this._effectiveTarget[this._property] !== "number") {
  49040. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49041. }
  49042. };
  49043. IncrementValueAction.prototype.execute = function () {
  49044. this._effectiveTarget[this._property] += this.value;
  49045. if (this._target.markAsDirty) {
  49046. this._target.markAsDirty(this._property);
  49047. }
  49048. };
  49049. IncrementValueAction.prototype.serialize = function (parent) {
  49050. return _super.prototype._serialize.call(this, {
  49051. name: "IncrementValueAction",
  49052. properties: [
  49053. BABYLON.Action._GetTargetProperty(this._target),
  49054. { name: "propertyPath", value: this.propertyPath },
  49055. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49056. ]
  49057. }, parent);
  49058. };
  49059. return IncrementValueAction;
  49060. }(BABYLON.Action));
  49061. BABYLON.IncrementValueAction = IncrementValueAction;
  49062. var PlayAnimationAction = /** @class */ (function (_super) {
  49063. __extends(PlayAnimationAction, _super);
  49064. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49065. var _this = _super.call(this, triggerOptions, condition) || this;
  49066. _this.from = from;
  49067. _this.to = to;
  49068. _this.loop = loop;
  49069. _this._target = target;
  49070. return _this;
  49071. }
  49072. PlayAnimationAction.prototype._prepare = function () {
  49073. };
  49074. PlayAnimationAction.prototype.execute = function () {
  49075. var scene = this._actionManager.getScene();
  49076. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49077. };
  49078. PlayAnimationAction.prototype.serialize = function (parent) {
  49079. return _super.prototype._serialize.call(this, {
  49080. name: "PlayAnimationAction",
  49081. properties: [
  49082. BABYLON.Action._GetTargetProperty(this._target),
  49083. { name: "from", value: String(this.from) },
  49084. { name: "to", value: String(this.to) },
  49085. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49086. ]
  49087. }, parent);
  49088. };
  49089. return PlayAnimationAction;
  49090. }(BABYLON.Action));
  49091. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49092. var StopAnimationAction = /** @class */ (function (_super) {
  49093. __extends(StopAnimationAction, _super);
  49094. function StopAnimationAction(triggerOptions, target, condition) {
  49095. var _this = _super.call(this, triggerOptions, condition) || this;
  49096. _this._target = target;
  49097. return _this;
  49098. }
  49099. StopAnimationAction.prototype._prepare = function () {
  49100. };
  49101. StopAnimationAction.prototype.execute = function () {
  49102. var scene = this._actionManager.getScene();
  49103. scene.stopAnimation(this._target);
  49104. };
  49105. StopAnimationAction.prototype.serialize = function (parent) {
  49106. return _super.prototype._serialize.call(this, {
  49107. name: "StopAnimationAction",
  49108. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49109. }, parent);
  49110. };
  49111. return StopAnimationAction;
  49112. }(BABYLON.Action));
  49113. BABYLON.StopAnimationAction = StopAnimationAction;
  49114. var DoNothingAction = /** @class */ (function (_super) {
  49115. __extends(DoNothingAction, _super);
  49116. function DoNothingAction(triggerOptions, condition) {
  49117. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49118. return _super.call(this, triggerOptions, condition) || this;
  49119. }
  49120. DoNothingAction.prototype.execute = function () {
  49121. };
  49122. DoNothingAction.prototype.serialize = function (parent) {
  49123. return _super.prototype._serialize.call(this, {
  49124. name: "DoNothingAction",
  49125. properties: []
  49126. }, parent);
  49127. };
  49128. return DoNothingAction;
  49129. }(BABYLON.Action));
  49130. BABYLON.DoNothingAction = DoNothingAction;
  49131. var CombineAction = /** @class */ (function (_super) {
  49132. __extends(CombineAction, _super);
  49133. function CombineAction(triggerOptions, children, condition) {
  49134. var _this = _super.call(this, triggerOptions, condition) || this;
  49135. _this.children = children;
  49136. return _this;
  49137. }
  49138. CombineAction.prototype._prepare = function () {
  49139. for (var index = 0; index < this.children.length; index++) {
  49140. this.children[index]._actionManager = this._actionManager;
  49141. this.children[index]._prepare();
  49142. }
  49143. };
  49144. CombineAction.prototype.execute = function (evt) {
  49145. for (var index = 0; index < this.children.length; index++) {
  49146. this.children[index].execute(evt);
  49147. }
  49148. };
  49149. CombineAction.prototype.serialize = function (parent) {
  49150. var serializationObject = _super.prototype._serialize.call(this, {
  49151. name: "CombineAction",
  49152. properties: [],
  49153. combine: []
  49154. }, parent);
  49155. for (var i = 0; i < this.children.length; i++) {
  49156. serializationObject.combine.push(this.children[i].serialize(null));
  49157. }
  49158. return serializationObject;
  49159. };
  49160. return CombineAction;
  49161. }(BABYLON.Action));
  49162. BABYLON.CombineAction = CombineAction;
  49163. var ExecuteCodeAction = /** @class */ (function (_super) {
  49164. __extends(ExecuteCodeAction, _super);
  49165. function ExecuteCodeAction(triggerOptions, func, condition) {
  49166. var _this = _super.call(this, triggerOptions, condition) || this;
  49167. _this.func = func;
  49168. return _this;
  49169. }
  49170. ExecuteCodeAction.prototype.execute = function (evt) {
  49171. this.func(evt);
  49172. };
  49173. return ExecuteCodeAction;
  49174. }(BABYLON.Action));
  49175. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49176. var SetParentAction = /** @class */ (function (_super) {
  49177. __extends(SetParentAction, _super);
  49178. function SetParentAction(triggerOptions, target, parent, condition) {
  49179. var _this = _super.call(this, triggerOptions, condition) || this;
  49180. _this._target = target;
  49181. _this._parent = parent;
  49182. return _this;
  49183. }
  49184. SetParentAction.prototype._prepare = function () {
  49185. };
  49186. SetParentAction.prototype.execute = function () {
  49187. if (this._target.parent === this._parent) {
  49188. return;
  49189. }
  49190. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49191. invertParentWorldMatrix.invert();
  49192. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49193. this._target.parent = this._parent;
  49194. };
  49195. SetParentAction.prototype.serialize = function (parent) {
  49196. return _super.prototype._serialize.call(this, {
  49197. name: "SetParentAction",
  49198. properties: [
  49199. BABYLON.Action._GetTargetProperty(this._target),
  49200. BABYLON.Action._GetTargetProperty(this._parent),
  49201. ]
  49202. }, parent);
  49203. };
  49204. return SetParentAction;
  49205. }(BABYLON.Action));
  49206. BABYLON.SetParentAction = SetParentAction;
  49207. var PlaySoundAction = /** @class */ (function (_super) {
  49208. __extends(PlaySoundAction, _super);
  49209. function PlaySoundAction(triggerOptions, sound, condition) {
  49210. var _this = _super.call(this, triggerOptions, condition) || this;
  49211. _this._sound = sound;
  49212. return _this;
  49213. }
  49214. PlaySoundAction.prototype._prepare = function () {
  49215. };
  49216. PlaySoundAction.prototype.execute = function () {
  49217. if (this._sound !== undefined)
  49218. this._sound.play();
  49219. };
  49220. PlaySoundAction.prototype.serialize = function (parent) {
  49221. return _super.prototype._serialize.call(this, {
  49222. name: "PlaySoundAction",
  49223. properties: [{ name: "sound", value: this._sound.name }]
  49224. }, parent);
  49225. };
  49226. return PlaySoundAction;
  49227. }(BABYLON.Action));
  49228. BABYLON.PlaySoundAction = PlaySoundAction;
  49229. var StopSoundAction = /** @class */ (function (_super) {
  49230. __extends(StopSoundAction, _super);
  49231. function StopSoundAction(triggerOptions, sound, condition) {
  49232. var _this = _super.call(this, triggerOptions, condition) || this;
  49233. _this._sound = sound;
  49234. return _this;
  49235. }
  49236. StopSoundAction.prototype._prepare = function () {
  49237. };
  49238. StopSoundAction.prototype.execute = function () {
  49239. if (this._sound !== undefined)
  49240. this._sound.stop();
  49241. };
  49242. StopSoundAction.prototype.serialize = function (parent) {
  49243. return _super.prototype._serialize.call(this, {
  49244. name: "StopSoundAction",
  49245. properties: [{ name: "sound", value: this._sound.name }]
  49246. }, parent);
  49247. };
  49248. return StopSoundAction;
  49249. }(BABYLON.Action));
  49250. BABYLON.StopSoundAction = StopSoundAction;
  49251. })(BABYLON || (BABYLON = {}));
  49252. //# sourceMappingURL=babylon.directActions.js.map
  49253. var BABYLON;
  49254. (function (BABYLON) {
  49255. var SpriteManager = /** @class */ (function () {
  49256. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49257. if (epsilon === void 0) { epsilon = 0.01; }
  49258. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49259. this.name = name;
  49260. this.sprites = new Array();
  49261. this.renderingGroupId = 0;
  49262. this.layerMask = 0x0FFFFFFF;
  49263. this.fogEnabled = true;
  49264. this.isPickable = false;
  49265. /**
  49266. * An event triggered when the manager is disposed.
  49267. * @type {BABYLON.Observable}
  49268. */
  49269. this.onDisposeObservable = new BABYLON.Observable();
  49270. this._vertexBuffers = {};
  49271. this._capacity = capacity;
  49272. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49273. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49274. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49275. if (cellSize.width && cellSize.height) {
  49276. this.cellWidth = cellSize.width;
  49277. this.cellHeight = cellSize.height;
  49278. }
  49279. else if (cellSize !== undefined) {
  49280. this.cellWidth = cellSize;
  49281. this.cellHeight = cellSize;
  49282. }
  49283. else {
  49284. return;
  49285. }
  49286. this._epsilon = epsilon;
  49287. this._scene = scene;
  49288. this._scene.spriteManagers.push(this);
  49289. var indices = [];
  49290. var index = 0;
  49291. for (var count = 0; count < capacity; count++) {
  49292. indices.push(index);
  49293. indices.push(index + 1);
  49294. indices.push(index + 2);
  49295. indices.push(index);
  49296. indices.push(index + 2);
  49297. indices.push(index + 3);
  49298. index += 4;
  49299. }
  49300. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49301. // VBO
  49302. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49303. this._vertexData = new Float32Array(capacity * 16 * 4);
  49304. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49305. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49306. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49307. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49308. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49309. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49310. this._vertexBuffers["options"] = options;
  49311. this._vertexBuffers["cellInfo"] = cellInfo;
  49312. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49313. // Effects
  49314. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49315. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49316. }
  49317. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49318. set: function (callback) {
  49319. if (this._onDisposeObserver) {
  49320. this.onDisposeObservable.remove(this._onDisposeObserver);
  49321. }
  49322. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49323. },
  49324. enumerable: true,
  49325. configurable: true
  49326. });
  49327. Object.defineProperty(SpriteManager.prototype, "texture", {
  49328. get: function () {
  49329. return this._spriteTexture;
  49330. },
  49331. set: function (value) {
  49332. this._spriteTexture = value;
  49333. },
  49334. enumerable: true,
  49335. configurable: true
  49336. });
  49337. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49338. var arrayOffset = index * 16;
  49339. if (offsetX === 0)
  49340. offsetX = this._epsilon;
  49341. else if (offsetX === 1)
  49342. offsetX = 1 - this._epsilon;
  49343. if (offsetY === 0)
  49344. offsetY = this._epsilon;
  49345. else if (offsetY === 1)
  49346. offsetY = 1 - this._epsilon;
  49347. this._vertexData[arrayOffset] = sprite.position.x;
  49348. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49349. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49350. this._vertexData[arrayOffset + 3] = sprite.angle;
  49351. this._vertexData[arrayOffset + 4] = sprite.width;
  49352. this._vertexData[arrayOffset + 5] = sprite.height;
  49353. this._vertexData[arrayOffset + 6] = offsetX;
  49354. this._vertexData[arrayOffset + 7] = offsetY;
  49355. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49356. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49357. var offset = (sprite.cellIndex / rowSize) >> 0;
  49358. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49359. this._vertexData[arrayOffset + 11] = offset;
  49360. // Color
  49361. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49362. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49363. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49364. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49365. };
  49366. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49367. var count = Math.min(this._capacity, this.sprites.length);
  49368. var min = BABYLON.Vector3.Zero();
  49369. var max = BABYLON.Vector3.Zero();
  49370. var distance = Number.MAX_VALUE;
  49371. var currentSprite = null;
  49372. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49373. var cameraView = camera.getViewMatrix();
  49374. for (var index = 0; index < count; index++) {
  49375. var sprite = this.sprites[index];
  49376. if (!sprite) {
  49377. continue;
  49378. }
  49379. if (predicate) {
  49380. if (!predicate(sprite)) {
  49381. continue;
  49382. }
  49383. }
  49384. else if (!sprite.isPickable) {
  49385. continue;
  49386. }
  49387. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49388. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49389. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49390. if (ray.intersectsBoxMinMax(min, max)) {
  49391. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49392. if (distance > currentDistance) {
  49393. distance = currentDistance;
  49394. currentSprite = sprite;
  49395. if (fastCheck) {
  49396. break;
  49397. }
  49398. }
  49399. }
  49400. }
  49401. if (currentSprite) {
  49402. var result = new BABYLON.PickingInfo();
  49403. result.hit = true;
  49404. result.pickedSprite = currentSprite;
  49405. result.distance = distance;
  49406. return result;
  49407. }
  49408. return null;
  49409. };
  49410. SpriteManager.prototype.render = function () {
  49411. // Check
  49412. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49413. return;
  49414. var engine = this._scene.getEngine();
  49415. var baseSize = this._spriteTexture.getBaseSize();
  49416. // Sprites
  49417. var deltaTime = engine.getDeltaTime();
  49418. var max = Math.min(this._capacity, this.sprites.length);
  49419. var rowSize = baseSize.width / this.cellWidth;
  49420. var offset = 0;
  49421. for (var index = 0; index < max; index++) {
  49422. var sprite = this.sprites[index];
  49423. if (!sprite) {
  49424. continue;
  49425. }
  49426. sprite._animate(deltaTime);
  49427. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49428. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49429. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49430. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49431. }
  49432. this._buffer.update(this._vertexData);
  49433. // Render
  49434. var effect = this._effectBase;
  49435. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49436. effect = this._effectFog;
  49437. }
  49438. engine.enableEffect(effect);
  49439. var viewMatrix = this._scene.getViewMatrix();
  49440. effect.setTexture("diffuseSampler", this._spriteTexture);
  49441. effect.setMatrix("view", viewMatrix);
  49442. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49443. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49444. // Fog
  49445. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49446. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49447. effect.setColor3("vFogColor", this._scene.fogColor);
  49448. }
  49449. // VBOs
  49450. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49451. // Draw order
  49452. engine.setDepthFunctionToLessOrEqual();
  49453. effect.setBool("alphaTest", true);
  49454. engine.setColorWrite(false);
  49455. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49456. engine.setColorWrite(true);
  49457. effect.setBool("alphaTest", false);
  49458. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49459. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49460. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49461. };
  49462. SpriteManager.prototype.dispose = function () {
  49463. if (this._buffer) {
  49464. this._buffer.dispose();
  49465. this._buffer = null;
  49466. }
  49467. if (this._indexBuffer) {
  49468. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49469. this._indexBuffer = null;
  49470. }
  49471. if (this._spriteTexture) {
  49472. this._spriteTexture.dispose();
  49473. this._spriteTexture = null;
  49474. }
  49475. // Remove from scene
  49476. var index = this._scene.spriteManagers.indexOf(this);
  49477. this._scene.spriteManagers.splice(index, 1);
  49478. // Callback
  49479. this.onDisposeObservable.notifyObservers(this);
  49480. this.onDisposeObservable.clear();
  49481. };
  49482. return SpriteManager;
  49483. }());
  49484. BABYLON.SpriteManager = SpriteManager;
  49485. })(BABYLON || (BABYLON = {}));
  49486. //# sourceMappingURL=babylon.spriteManager.js.map
  49487. var BABYLON;
  49488. (function (BABYLON) {
  49489. var Sprite = /** @class */ (function () {
  49490. function Sprite(name, manager) {
  49491. this.name = name;
  49492. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49493. this.width = 1.0;
  49494. this.height = 1.0;
  49495. this.angle = 0;
  49496. this.cellIndex = 0;
  49497. this.invertU = 0;
  49498. this.invertV = 0;
  49499. this.animations = new Array();
  49500. this.isPickable = false;
  49501. this._animationStarted = false;
  49502. this._loopAnimation = false;
  49503. this._fromIndex = 0;
  49504. this._toIndex = 0;
  49505. this._delay = 0;
  49506. this._direction = 1;
  49507. this._time = 0;
  49508. this._manager = manager;
  49509. this._manager.sprites.push(this);
  49510. this.position = BABYLON.Vector3.Zero();
  49511. }
  49512. Object.defineProperty(Sprite.prototype, "size", {
  49513. get: function () {
  49514. return this.width;
  49515. },
  49516. set: function (value) {
  49517. this.width = value;
  49518. this.height = value;
  49519. },
  49520. enumerable: true,
  49521. configurable: true
  49522. });
  49523. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49524. this._fromIndex = from;
  49525. this._toIndex = to;
  49526. this._loopAnimation = loop;
  49527. this._delay = delay;
  49528. this._animationStarted = true;
  49529. this._direction = from < to ? 1 : -1;
  49530. this.cellIndex = from;
  49531. this._time = 0;
  49532. this._onAnimationEnd = onAnimationEnd;
  49533. };
  49534. Sprite.prototype.stopAnimation = function () {
  49535. this._animationStarted = false;
  49536. };
  49537. Sprite.prototype._animate = function (deltaTime) {
  49538. if (!this._animationStarted)
  49539. return;
  49540. this._time += deltaTime;
  49541. if (this._time > this._delay) {
  49542. this._time = this._time % this._delay;
  49543. this.cellIndex += this._direction;
  49544. if (this.cellIndex > this._toIndex) {
  49545. if (this._loopAnimation) {
  49546. this.cellIndex = this._fromIndex;
  49547. }
  49548. else {
  49549. this.cellIndex = this._toIndex;
  49550. this._animationStarted = false;
  49551. if (this._onAnimationEnd) {
  49552. this._onAnimationEnd();
  49553. }
  49554. if (this.disposeWhenFinishedAnimating) {
  49555. this.dispose();
  49556. }
  49557. }
  49558. }
  49559. }
  49560. };
  49561. Sprite.prototype.dispose = function () {
  49562. for (var i = 0; i < this._manager.sprites.length; i++) {
  49563. if (this._manager.sprites[i] == this) {
  49564. this._manager.sprites.splice(i, 1);
  49565. }
  49566. }
  49567. };
  49568. return Sprite;
  49569. }());
  49570. BABYLON.Sprite = Sprite;
  49571. })(BABYLON || (BABYLON = {}));
  49572. //# sourceMappingURL=babylon.sprite.js.map
  49573. var BABYLON;
  49574. (function (BABYLON) {
  49575. var IntersectionInfo = /** @class */ (function () {
  49576. function IntersectionInfo(bu, bv, distance) {
  49577. this.bu = bu;
  49578. this.bv = bv;
  49579. this.distance = distance;
  49580. this.faceId = 0;
  49581. this.subMeshId = 0;
  49582. }
  49583. return IntersectionInfo;
  49584. }());
  49585. BABYLON.IntersectionInfo = IntersectionInfo;
  49586. var PickingInfo = /** @class */ (function () {
  49587. function PickingInfo() {
  49588. this.hit = false;
  49589. this.distance = 0;
  49590. this.pickedPoint = null;
  49591. this.pickedMesh = null;
  49592. this.bu = 0;
  49593. this.bv = 0;
  49594. this.faceId = -1;
  49595. this.subMeshId = 0;
  49596. this.pickedSprite = null;
  49597. }
  49598. // Methods
  49599. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49600. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49601. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49602. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49603. return null;
  49604. }
  49605. var indices = this.pickedMesh.getIndices();
  49606. if (!indices) {
  49607. return null;
  49608. }
  49609. var result;
  49610. if (useVerticesNormals) {
  49611. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49612. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49613. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49614. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49615. normal0 = normal0.scale(this.bu);
  49616. normal1 = normal1.scale(this.bv);
  49617. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49618. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49619. }
  49620. else {
  49621. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49622. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49623. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49624. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49625. var p1p2 = vertex1.subtract(vertex2);
  49626. var p3p2 = vertex3.subtract(vertex2);
  49627. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49628. }
  49629. if (useWorldCoordinates) {
  49630. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49631. }
  49632. return BABYLON.Vector3.Normalize(result);
  49633. };
  49634. PickingInfo.prototype.getTextureCoordinates = function () {
  49635. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49636. return null;
  49637. }
  49638. var indices = this.pickedMesh.getIndices();
  49639. if (!indices) {
  49640. return null;
  49641. }
  49642. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49643. if (!uvs) {
  49644. return null;
  49645. }
  49646. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49647. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49648. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49649. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49650. uv1 = uv1.scale(this.bu);
  49651. uv2 = uv2.scale(this.bv);
  49652. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49653. };
  49654. return PickingInfo;
  49655. }());
  49656. BABYLON.PickingInfo = PickingInfo;
  49657. })(BABYLON || (BABYLON = {}));
  49658. //# sourceMappingURL=babylon.pickingInfo.js.map
  49659. var BABYLON;
  49660. (function (BABYLON) {
  49661. var Ray = /** @class */ (function () {
  49662. function Ray(origin, direction, length) {
  49663. if (length === void 0) { length = Number.MAX_VALUE; }
  49664. this.origin = origin;
  49665. this.direction = direction;
  49666. this.length = length;
  49667. }
  49668. // Methods
  49669. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49670. var d = 0.0;
  49671. var maxValue = Number.MAX_VALUE;
  49672. var inv;
  49673. var min;
  49674. var max;
  49675. var temp;
  49676. if (Math.abs(this.direction.x) < 0.0000001) {
  49677. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49678. return false;
  49679. }
  49680. }
  49681. else {
  49682. inv = 1.0 / this.direction.x;
  49683. min = (minimum.x - this.origin.x) * inv;
  49684. max = (maximum.x - this.origin.x) * inv;
  49685. if (max === -Infinity) {
  49686. max = Infinity;
  49687. }
  49688. if (min > max) {
  49689. temp = min;
  49690. min = max;
  49691. max = temp;
  49692. }
  49693. d = Math.max(min, d);
  49694. maxValue = Math.min(max, maxValue);
  49695. if (d > maxValue) {
  49696. return false;
  49697. }
  49698. }
  49699. if (Math.abs(this.direction.y) < 0.0000001) {
  49700. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49701. return false;
  49702. }
  49703. }
  49704. else {
  49705. inv = 1.0 / this.direction.y;
  49706. min = (minimum.y - this.origin.y) * inv;
  49707. max = (maximum.y - this.origin.y) * inv;
  49708. if (max === -Infinity) {
  49709. max = Infinity;
  49710. }
  49711. if (min > max) {
  49712. temp = min;
  49713. min = max;
  49714. max = temp;
  49715. }
  49716. d = Math.max(min, d);
  49717. maxValue = Math.min(max, maxValue);
  49718. if (d > maxValue) {
  49719. return false;
  49720. }
  49721. }
  49722. if (Math.abs(this.direction.z) < 0.0000001) {
  49723. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49724. return false;
  49725. }
  49726. }
  49727. else {
  49728. inv = 1.0 / this.direction.z;
  49729. min = (minimum.z - this.origin.z) * inv;
  49730. max = (maximum.z - this.origin.z) * inv;
  49731. if (max === -Infinity) {
  49732. max = Infinity;
  49733. }
  49734. if (min > max) {
  49735. temp = min;
  49736. min = max;
  49737. max = temp;
  49738. }
  49739. d = Math.max(min, d);
  49740. maxValue = Math.min(max, maxValue);
  49741. if (d > maxValue) {
  49742. return false;
  49743. }
  49744. }
  49745. return true;
  49746. };
  49747. Ray.prototype.intersectsBox = function (box) {
  49748. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49749. };
  49750. Ray.prototype.intersectsSphere = function (sphere) {
  49751. var x = sphere.center.x - this.origin.x;
  49752. var y = sphere.center.y - this.origin.y;
  49753. var z = sphere.center.z - this.origin.z;
  49754. var pyth = (x * x) + (y * y) + (z * z);
  49755. var rr = sphere.radius * sphere.radius;
  49756. if (pyth <= rr) {
  49757. return true;
  49758. }
  49759. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49760. if (dot < 0.0) {
  49761. return false;
  49762. }
  49763. var temp = pyth - (dot * dot);
  49764. return temp <= rr;
  49765. };
  49766. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49767. if (!this._edge1) {
  49768. this._edge1 = BABYLON.Vector3.Zero();
  49769. this._edge2 = BABYLON.Vector3.Zero();
  49770. this._pvec = BABYLON.Vector3.Zero();
  49771. this._tvec = BABYLON.Vector3.Zero();
  49772. this._qvec = BABYLON.Vector3.Zero();
  49773. }
  49774. vertex1.subtractToRef(vertex0, this._edge1);
  49775. vertex2.subtractToRef(vertex0, this._edge2);
  49776. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49777. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49778. if (det === 0) {
  49779. return null;
  49780. }
  49781. var invdet = 1 / det;
  49782. this.origin.subtractToRef(vertex0, this._tvec);
  49783. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49784. if (bu < 0 || bu > 1.0) {
  49785. return null;
  49786. }
  49787. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49788. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49789. if (bv < 0 || bu + bv > 1.0) {
  49790. return null;
  49791. }
  49792. //check if the distance is longer than the predefined length.
  49793. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49794. if (distance > this.length) {
  49795. return null;
  49796. }
  49797. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49798. };
  49799. Ray.prototype.intersectsPlane = function (plane) {
  49800. var distance;
  49801. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49802. if (Math.abs(result1) < 9.99999997475243E-07) {
  49803. return null;
  49804. }
  49805. else {
  49806. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49807. distance = (-plane.d - result2) / result1;
  49808. if (distance < 0.0) {
  49809. if (distance < -9.99999997475243E-07) {
  49810. return null;
  49811. }
  49812. else {
  49813. return 0;
  49814. }
  49815. }
  49816. return distance;
  49817. }
  49818. };
  49819. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49820. var tm = BABYLON.Tmp.Matrix[0];
  49821. mesh.getWorldMatrix().invertToRef(tm);
  49822. if (this._tmpRay) {
  49823. Ray.TransformToRef(this, tm, this._tmpRay);
  49824. }
  49825. else {
  49826. this._tmpRay = Ray.Transform(this, tm);
  49827. }
  49828. return mesh.intersects(this._tmpRay, fastCheck);
  49829. };
  49830. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49831. if (results) {
  49832. results.length = 0;
  49833. }
  49834. else {
  49835. results = [];
  49836. }
  49837. for (var i = 0; i < meshes.length; i++) {
  49838. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49839. if (pickInfo.hit) {
  49840. results.push(pickInfo);
  49841. }
  49842. }
  49843. results.sort(this._comparePickingInfo);
  49844. return results;
  49845. };
  49846. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49847. if (pickingInfoA.distance < pickingInfoB.distance) {
  49848. return -1;
  49849. }
  49850. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49851. return 1;
  49852. }
  49853. else {
  49854. return 0;
  49855. }
  49856. };
  49857. /**
  49858. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49859. * @param sega the first point of the segment to test the intersection against
  49860. * @param segb the second point of the segment to test the intersection against
  49861. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49862. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49863. */
  49864. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49865. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49866. var u = segb.subtract(sega);
  49867. var v = rsegb.subtract(this.origin);
  49868. var w = sega.subtract(this.origin);
  49869. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49870. var b = BABYLON.Vector3.Dot(u, v);
  49871. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49872. var d = BABYLON.Vector3.Dot(u, w);
  49873. var e = BABYLON.Vector3.Dot(v, w);
  49874. var D = a * c - b * b; // always >= 0
  49875. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49876. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49877. // compute the line parameters of the two closest points
  49878. if (D < Ray.smallnum) {
  49879. sN = 0.0; // force using point P0 on segment S1
  49880. sD = 1.0; // to prevent possible division by 0.0 later
  49881. tN = e;
  49882. tD = c;
  49883. }
  49884. else {
  49885. sN = (b * e - c * d);
  49886. tN = (a * e - b * d);
  49887. if (sN < 0.0) {
  49888. sN = 0.0;
  49889. tN = e;
  49890. tD = c;
  49891. }
  49892. else if (sN > sD) {
  49893. sN = sD;
  49894. tN = e + b;
  49895. tD = c;
  49896. }
  49897. }
  49898. if (tN < 0.0) {
  49899. tN = 0.0;
  49900. // recompute sc for this edge
  49901. if (-d < 0.0) {
  49902. sN = 0.0;
  49903. }
  49904. else if (-d > a)
  49905. sN = sD;
  49906. else {
  49907. sN = -d;
  49908. sD = a;
  49909. }
  49910. }
  49911. else if (tN > tD) {
  49912. tN = tD;
  49913. // recompute sc for this edge
  49914. if ((-d + b) < 0.0) {
  49915. sN = 0;
  49916. }
  49917. else if ((-d + b) > a) {
  49918. sN = sD;
  49919. }
  49920. else {
  49921. sN = (-d + b);
  49922. sD = a;
  49923. }
  49924. }
  49925. // finally do the division to get sc and tc
  49926. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49927. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49928. // get the difference of the two closest points
  49929. var qtc = v.multiplyByFloats(tc, tc, tc);
  49930. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49931. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49932. if (isIntersected) {
  49933. return qtc.length();
  49934. }
  49935. return -1;
  49936. };
  49937. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49938. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49939. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49940. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49941. this.direction.normalize();
  49942. return this;
  49943. };
  49944. // Statics
  49945. Ray.Zero = function () {
  49946. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49947. };
  49948. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49949. var result = Ray.Zero();
  49950. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49951. };
  49952. /**
  49953. * 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
  49954. * transformed to the given world matrix.
  49955. * @param origin The origin point
  49956. * @param end The end point
  49957. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49958. */
  49959. Ray.CreateNewFromTo = function (origin, end, world) {
  49960. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49961. var direction = end.subtract(origin);
  49962. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49963. direction.normalize();
  49964. return Ray.Transform(new Ray(origin, direction, length), world);
  49965. };
  49966. Ray.Transform = function (ray, matrix) {
  49967. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49968. Ray.TransformToRef(ray, matrix, result);
  49969. return result;
  49970. };
  49971. Ray.TransformToRef = function (ray, matrix, result) {
  49972. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49973. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49974. result.length = ray.length;
  49975. var dir = result.direction;
  49976. var len = dir.length();
  49977. if (!(len === 0 || len === 1)) {
  49978. var num = 1.0 / len;
  49979. dir.x *= num;
  49980. dir.y *= num;
  49981. dir.z *= num;
  49982. result.length *= len;
  49983. }
  49984. };
  49985. Ray.smallnum = 0.00000001;
  49986. Ray.rayl = 10e8;
  49987. return Ray;
  49988. }());
  49989. BABYLON.Ray = Ray;
  49990. })(BABYLON || (BABYLON = {}));
  49991. //# sourceMappingURL=babylon.ray.js.map
  49992. var BABYLON;
  49993. (function (BABYLON) {
  49994. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49995. if (boxMin.x > sphereCenter.x + sphereRadius)
  49996. return false;
  49997. if (sphereCenter.x - sphereRadius > boxMax.x)
  49998. return false;
  49999. if (boxMin.y > sphereCenter.y + sphereRadius)
  50000. return false;
  50001. if (sphereCenter.y - sphereRadius > boxMax.y)
  50002. return false;
  50003. if (boxMin.z > sphereCenter.z + sphereRadius)
  50004. return false;
  50005. if (sphereCenter.z - sphereRadius > boxMax.z)
  50006. return false;
  50007. return true;
  50008. };
  50009. var getLowestRoot = (function () {
  50010. var result = { root: 0, found: false };
  50011. return function (a, b, c, maxR) {
  50012. result.root = 0;
  50013. result.found = false;
  50014. var determinant = b * b - 4.0 * a * c;
  50015. if (determinant < 0)
  50016. return result;
  50017. var sqrtD = Math.sqrt(determinant);
  50018. var r1 = (-b - sqrtD) / (2.0 * a);
  50019. var r2 = (-b + sqrtD) / (2.0 * a);
  50020. if (r1 > r2) {
  50021. var temp = r2;
  50022. r2 = r1;
  50023. r1 = temp;
  50024. }
  50025. if (r1 > 0 && r1 < maxR) {
  50026. result.root = r1;
  50027. result.found = true;
  50028. return result;
  50029. }
  50030. if (r2 > 0 && r2 < maxR) {
  50031. result.root = r2;
  50032. result.found = true;
  50033. return result;
  50034. }
  50035. return result;
  50036. };
  50037. })();
  50038. var Collider = /** @class */ (function () {
  50039. function Collider() {
  50040. this._collisionPoint = BABYLON.Vector3.Zero();
  50041. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50042. this._tempVector = BABYLON.Vector3.Zero();
  50043. this._tempVector2 = BABYLON.Vector3.Zero();
  50044. this._tempVector3 = BABYLON.Vector3.Zero();
  50045. this._tempVector4 = BABYLON.Vector3.Zero();
  50046. this._edge = BABYLON.Vector3.Zero();
  50047. this._baseToVertex = BABYLON.Vector3.Zero();
  50048. this._destinationPoint = BABYLON.Vector3.Zero();
  50049. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50050. this._displacementVector = BABYLON.Vector3.Zero();
  50051. this._radius = BABYLON.Vector3.One();
  50052. this._retry = 0;
  50053. this._basePointWorld = BABYLON.Vector3.Zero();
  50054. this._velocityWorld = BABYLON.Vector3.Zero();
  50055. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50056. this._collisionMask = -1;
  50057. }
  50058. Object.defineProperty(Collider.prototype, "collisionMask", {
  50059. get: function () {
  50060. return this._collisionMask;
  50061. },
  50062. set: function (mask) {
  50063. this._collisionMask = !isNaN(mask) ? mask : -1;
  50064. },
  50065. enumerable: true,
  50066. configurable: true
  50067. });
  50068. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50069. /**
  50070. * Gets the plane normal used to compute the sliding response (in local space)
  50071. */
  50072. get: function () {
  50073. return this._slidePlaneNormal;
  50074. },
  50075. enumerable: true,
  50076. configurable: true
  50077. });
  50078. // Methods
  50079. Collider.prototype._initialize = function (source, dir, e) {
  50080. this._velocity = dir;
  50081. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50082. this._basePoint = source;
  50083. source.multiplyToRef(this._radius, this._basePointWorld);
  50084. dir.multiplyToRef(this._radius, this._velocityWorld);
  50085. this._velocityWorldLength = this._velocityWorld.length();
  50086. this._epsilon = e;
  50087. this.collisionFound = false;
  50088. };
  50089. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50090. pa.subtractToRef(point, this._tempVector);
  50091. pb.subtractToRef(point, this._tempVector2);
  50092. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50093. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50094. if (d < 0)
  50095. return false;
  50096. pc.subtractToRef(point, this._tempVector3);
  50097. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50098. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50099. if (d < 0)
  50100. return false;
  50101. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50102. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50103. return d >= 0;
  50104. };
  50105. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50106. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50107. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50108. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50109. return false;
  50110. }
  50111. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50112. return false;
  50113. return true;
  50114. };
  50115. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50116. var t0;
  50117. var embeddedInPlane = false;
  50118. //defensive programming, actually not needed.
  50119. if (!trianglePlaneArray) {
  50120. trianglePlaneArray = [];
  50121. }
  50122. if (!trianglePlaneArray[faceIndex]) {
  50123. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50124. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50125. }
  50126. var trianglePlane = trianglePlaneArray[faceIndex];
  50127. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50128. return;
  50129. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50130. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50131. if (normalDotVelocity == 0) {
  50132. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50133. return;
  50134. embeddedInPlane = true;
  50135. t0 = 0;
  50136. }
  50137. else {
  50138. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50139. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50140. if (t0 > t1) {
  50141. var temp = t1;
  50142. t1 = t0;
  50143. t0 = temp;
  50144. }
  50145. if (t0 > 1.0 || t1 < 0.0)
  50146. return;
  50147. if (t0 < 0)
  50148. t0 = 0;
  50149. if (t0 > 1.0)
  50150. t0 = 1.0;
  50151. }
  50152. this._collisionPoint.copyFromFloats(0, 0, 0);
  50153. var found = false;
  50154. var t = 1.0;
  50155. if (!embeddedInPlane) {
  50156. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50157. this._velocity.scaleToRef(t0, this._tempVector);
  50158. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50159. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50160. found = true;
  50161. t = t0;
  50162. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50163. }
  50164. }
  50165. if (!found) {
  50166. var velocitySquaredLength = this._velocity.lengthSquared();
  50167. var a = velocitySquaredLength;
  50168. this._basePoint.subtractToRef(p1, this._tempVector);
  50169. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50170. var c = this._tempVector.lengthSquared() - 1.0;
  50171. var lowestRoot = getLowestRoot(a, b, c, t);
  50172. if (lowestRoot.found) {
  50173. t = lowestRoot.root;
  50174. found = true;
  50175. this._collisionPoint.copyFrom(p1);
  50176. }
  50177. this._basePoint.subtractToRef(p2, this._tempVector);
  50178. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50179. c = this._tempVector.lengthSquared() - 1.0;
  50180. lowestRoot = getLowestRoot(a, b, c, t);
  50181. if (lowestRoot.found) {
  50182. t = lowestRoot.root;
  50183. found = true;
  50184. this._collisionPoint.copyFrom(p2);
  50185. }
  50186. this._basePoint.subtractToRef(p3, this._tempVector);
  50187. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50188. c = this._tempVector.lengthSquared() - 1.0;
  50189. lowestRoot = getLowestRoot(a, b, c, t);
  50190. if (lowestRoot.found) {
  50191. t = lowestRoot.root;
  50192. found = true;
  50193. this._collisionPoint.copyFrom(p3);
  50194. }
  50195. p2.subtractToRef(p1, this._edge);
  50196. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50197. var edgeSquaredLength = this._edge.lengthSquared();
  50198. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50199. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50200. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50201. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50202. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50203. lowestRoot = getLowestRoot(a, b, c, t);
  50204. if (lowestRoot.found) {
  50205. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50206. if (f >= 0.0 && f <= 1.0) {
  50207. t = lowestRoot.root;
  50208. found = true;
  50209. this._edge.scaleInPlace(f);
  50210. p1.addToRef(this._edge, this._collisionPoint);
  50211. }
  50212. }
  50213. p3.subtractToRef(p2, this._edge);
  50214. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50215. edgeSquaredLength = this._edge.lengthSquared();
  50216. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50217. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50218. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50219. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50220. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50221. lowestRoot = getLowestRoot(a, b, c, t);
  50222. if (lowestRoot.found) {
  50223. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50224. if (f >= 0.0 && f <= 1.0) {
  50225. t = lowestRoot.root;
  50226. found = true;
  50227. this._edge.scaleInPlace(f);
  50228. p2.addToRef(this._edge, this._collisionPoint);
  50229. }
  50230. }
  50231. p1.subtractToRef(p3, this._edge);
  50232. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50233. edgeSquaredLength = this._edge.lengthSquared();
  50234. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50235. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50236. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50237. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50238. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50239. lowestRoot = getLowestRoot(a, b, c, t);
  50240. if (lowestRoot.found) {
  50241. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50242. if (f >= 0.0 && f <= 1.0) {
  50243. t = lowestRoot.root;
  50244. found = true;
  50245. this._edge.scaleInPlace(f);
  50246. p3.addToRef(this._edge, this._collisionPoint);
  50247. }
  50248. }
  50249. }
  50250. if (found) {
  50251. var distToCollision = t * this._velocity.length();
  50252. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50253. if (!this.intersectionPoint) {
  50254. this.intersectionPoint = this._collisionPoint.clone();
  50255. }
  50256. else {
  50257. this.intersectionPoint.copyFrom(this._collisionPoint);
  50258. }
  50259. this._nearestDistance = distToCollision;
  50260. this.collisionFound = true;
  50261. }
  50262. }
  50263. };
  50264. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50265. for (var i = indexStart; i < indexEnd; i += 3) {
  50266. var p1 = pts[indices[i] - decal];
  50267. var p2 = pts[indices[i + 1] - decal];
  50268. var p3 = pts[indices[i + 2] - decal];
  50269. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50270. }
  50271. };
  50272. Collider.prototype._getResponse = function (pos, vel) {
  50273. pos.addToRef(vel, this._destinationPoint);
  50274. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50275. this._basePoint.addToRef(vel, pos);
  50276. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50277. this._slidePlaneNormal.normalize();
  50278. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50279. pos.addInPlace(this._displacementVector);
  50280. this.intersectionPoint.addInPlace(this._displacementVector);
  50281. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50282. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50283. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50284. };
  50285. return Collider;
  50286. }());
  50287. BABYLON.Collider = Collider;
  50288. })(BABYLON || (BABYLON = {}));
  50289. //# sourceMappingURL=babylon.collider.js.map
  50290. var BABYLON;
  50291. (function (BABYLON) {
  50292. //WebWorker code will be inserted to this variable.
  50293. BABYLON.CollisionWorker = "";
  50294. var WorkerTaskType;
  50295. (function (WorkerTaskType) {
  50296. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50297. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50298. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50299. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50300. var WorkerReplyType;
  50301. (function (WorkerReplyType) {
  50302. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50303. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50304. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50305. var CollisionCoordinatorWorker = /** @class */ (function () {
  50306. function CollisionCoordinatorWorker() {
  50307. var _this = this;
  50308. this._scaledPosition = BABYLON.Vector3.Zero();
  50309. this._scaledVelocity = BABYLON.Vector3.Zero();
  50310. this.onMeshUpdated = function (transformNode) {
  50311. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50312. };
  50313. this.onGeometryUpdated = function (geometry) {
  50314. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50315. };
  50316. this._afterRender = function () {
  50317. if (!_this._init)
  50318. return;
  50319. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50320. return;
  50321. }
  50322. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50323. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50324. if (_this._runningUpdated > 4) {
  50325. return;
  50326. }
  50327. ++_this._runningUpdated;
  50328. var payload = {
  50329. updatedMeshes: _this._addUpdateMeshesList,
  50330. updatedGeometries: _this._addUpdateGeometriesList,
  50331. removedGeometries: _this._toRemoveGeometryArray,
  50332. removedMeshes: _this._toRemoveMeshesArray
  50333. };
  50334. var message = {
  50335. payload: payload,
  50336. taskType: WorkerTaskType.UPDATE
  50337. };
  50338. var serializable = [];
  50339. for (var id in payload.updatedGeometries) {
  50340. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50341. //prepare transferables
  50342. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50343. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50344. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50345. }
  50346. }
  50347. _this._worker.postMessage(message, serializable);
  50348. _this._addUpdateMeshesList = {};
  50349. _this._addUpdateGeometriesList = {};
  50350. _this._toRemoveGeometryArray = [];
  50351. _this._toRemoveMeshesArray = [];
  50352. };
  50353. this._onMessageFromWorker = function (e) {
  50354. var returnData = e.data;
  50355. if (returnData.error != WorkerReplyType.SUCCESS) {
  50356. //TODO what errors can be returned from the worker?
  50357. BABYLON.Tools.Warn("error returned from worker!");
  50358. return;
  50359. }
  50360. switch (returnData.taskType) {
  50361. case WorkerTaskType.INIT:
  50362. _this._init = true;
  50363. //Update the worked with ALL of the scene's current state
  50364. _this._scene.meshes.forEach(function (mesh) {
  50365. _this.onMeshAdded(mesh);
  50366. });
  50367. _this._scene.getGeometries().forEach(function (geometry) {
  50368. _this.onGeometryAdded(geometry);
  50369. });
  50370. break;
  50371. case WorkerTaskType.UPDATE:
  50372. _this._runningUpdated--;
  50373. break;
  50374. case WorkerTaskType.COLLIDE:
  50375. var returnPayload = returnData.payload;
  50376. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50377. return;
  50378. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50379. if (callback) {
  50380. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50381. if (mesh) {
  50382. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50383. }
  50384. }
  50385. //cleanup
  50386. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50387. break;
  50388. }
  50389. };
  50390. this._collisionsCallbackArray = [];
  50391. this._init = false;
  50392. this._runningUpdated = 0;
  50393. this._addUpdateMeshesList = {};
  50394. this._addUpdateGeometriesList = {};
  50395. this._toRemoveGeometryArray = [];
  50396. this._toRemoveMeshesArray = [];
  50397. }
  50398. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50399. if (!this._init)
  50400. return;
  50401. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50402. return;
  50403. position.divideToRef(collider._radius, this._scaledPosition);
  50404. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50405. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50406. var payload = {
  50407. collider: {
  50408. position: this._scaledPosition.asArray(),
  50409. velocity: this._scaledVelocity.asArray(),
  50410. radius: collider._radius.asArray()
  50411. },
  50412. collisionId: collisionIndex,
  50413. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50414. maximumRetry: maximumRetry
  50415. };
  50416. var message = {
  50417. payload: payload,
  50418. taskType: WorkerTaskType.COLLIDE
  50419. };
  50420. this._worker.postMessage(message);
  50421. };
  50422. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50423. this._scene = scene;
  50424. this._scene.registerAfterRender(this._afterRender);
  50425. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50426. this._worker = new Worker(workerUrl);
  50427. this._worker.onmessage = this._onMessageFromWorker;
  50428. var message = {
  50429. payload: {},
  50430. taskType: WorkerTaskType.INIT
  50431. };
  50432. this._worker.postMessage(message);
  50433. };
  50434. CollisionCoordinatorWorker.prototype.destroy = function () {
  50435. this._scene.unregisterAfterRender(this._afterRender);
  50436. this._worker.terminate();
  50437. };
  50438. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50439. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50440. this.onMeshUpdated(mesh);
  50441. };
  50442. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50443. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50444. };
  50445. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50446. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50447. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50448. this.onGeometryUpdated(geometry);
  50449. };
  50450. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50451. this._toRemoveGeometryArray.push(geometry.id);
  50452. };
  50453. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50454. var submeshes = [];
  50455. if (mesh.subMeshes) {
  50456. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50457. var boundingInfo = sm.getBoundingInfo();
  50458. return {
  50459. position: idx,
  50460. verticesStart: sm.verticesStart,
  50461. verticesCount: sm.verticesCount,
  50462. indexStart: sm.indexStart,
  50463. indexCount: sm.indexCount,
  50464. hasMaterial: !!sm.getMaterial(),
  50465. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50466. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50467. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50468. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50469. };
  50470. });
  50471. }
  50472. var geometryId = null;
  50473. if (mesh instanceof BABYLON.Mesh) {
  50474. var geometry = mesh.geometry;
  50475. geometryId = geometry ? geometry.id : null;
  50476. }
  50477. else if (mesh instanceof BABYLON.InstancedMesh) {
  50478. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50479. geometryId = geometry ? geometry.id : null;
  50480. }
  50481. var boundingInfo = mesh.getBoundingInfo();
  50482. return {
  50483. uniqueId: mesh.uniqueId,
  50484. id: mesh.id,
  50485. name: mesh.name,
  50486. geometryId: geometryId,
  50487. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50488. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50489. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50490. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50491. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50492. subMeshes: submeshes,
  50493. checkCollisions: mesh.checkCollisions
  50494. };
  50495. };
  50496. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50497. return {
  50498. id: geometry.id,
  50499. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50500. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50501. indices: new Uint32Array(geometry.getIndices() || []),
  50502. };
  50503. };
  50504. return CollisionCoordinatorWorker;
  50505. }());
  50506. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50507. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50508. function CollisionCoordinatorLegacy() {
  50509. this._scaledPosition = BABYLON.Vector3.Zero();
  50510. this._scaledVelocity = BABYLON.Vector3.Zero();
  50511. this._finalPosition = BABYLON.Vector3.Zero();
  50512. }
  50513. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50514. position.divideToRef(collider._radius, this._scaledPosition);
  50515. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50516. collider.collidedMesh = null;
  50517. collider._retry = 0;
  50518. collider._initialVelocity = this._scaledVelocity;
  50519. collider._initialPosition = this._scaledPosition;
  50520. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50521. this._finalPosition.multiplyInPlace(collider._radius);
  50522. //run the callback
  50523. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50524. };
  50525. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50526. this._scene = scene;
  50527. };
  50528. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50529. //Legacy need no destruction method.
  50530. };
  50531. //No update in legacy mode
  50532. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50533. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50534. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50535. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50536. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50537. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50538. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50539. if (excludedMesh === void 0) { excludedMesh = null; }
  50540. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50541. if (collider._retry >= maximumRetry) {
  50542. finalPosition.copyFrom(position);
  50543. return;
  50544. }
  50545. // Check if this is a mesh else camera or -1
  50546. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50547. collider._initialize(position, velocity, closeDistance);
  50548. // Check all meshes
  50549. for (var index = 0; index < this._scene.meshes.length; index++) {
  50550. var mesh = this._scene.meshes[index];
  50551. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50552. mesh._checkCollision(collider);
  50553. }
  50554. }
  50555. if (!collider.collisionFound) {
  50556. position.addToRef(velocity, finalPosition);
  50557. return;
  50558. }
  50559. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50560. collider._getResponse(position, velocity);
  50561. }
  50562. if (velocity.length() <= closeDistance) {
  50563. finalPosition.copyFrom(position);
  50564. return;
  50565. }
  50566. collider._retry++;
  50567. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50568. };
  50569. return CollisionCoordinatorLegacy;
  50570. }());
  50571. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50572. })(BABYLON || (BABYLON = {}));
  50573. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50574. var BABYLON;
  50575. (function (BABYLON) {
  50576. /**
  50577. * A particle represents one of the element emitted by a particle system.
  50578. * This is mainly define by its coordinates, direction, velocity and age.
  50579. */
  50580. var Particle = /** @class */ (function () {
  50581. /**
  50582. * Creates a new instance of @see Particle
  50583. * @param particleSystem the particle system the particle belongs to
  50584. */
  50585. function Particle(particleSystem) {
  50586. this.particleSystem = particleSystem;
  50587. /**
  50588. * The world position of the particle in the scene.
  50589. */
  50590. this.position = BABYLON.Vector3.Zero();
  50591. /**
  50592. * The world direction of the particle in the scene.
  50593. */
  50594. this.direction = BABYLON.Vector3.Zero();
  50595. /**
  50596. * The color of the particle.
  50597. */
  50598. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50599. /**
  50600. * The color change of the particle per step.
  50601. */
  50602. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50603. /**
  50604. * Defines how long will the life of the particle be.
  50605. */
  50606. this.lifeTime = 1.0;
  50607. /**
  50608. * The current age of the particle.
  50609. */
  50610. this.age = 0;
  50611. /**
  50612. * The current size of the particle.
  50613. */
  50614. this.size = 0;
  50615. /**
  50616. * The current angle of the particle.
  50617. */
  50618. this.angle = 0;
  50619. /**
  50620. * Defines how fast is the angle changing.
  50621. */
  50622. this.angularSpeed = 0;
  50623. /**
  50624. * Defines the cell index used by the particle to be rendered from a sprite.
  50625. */
  50626. this.cellIndex = 0;
  50627. this._currentFrameCounter = 0;
  50628. if (!this.particleSystem.isAnimationSheetEnabled) {
  50629. return;
  50630. }
  50631. this.cellIndex = this.particleSystem.startSpriteCellID;
  50632. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50633. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50634. }
  50635. else {
  50636. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50637. }
  50638. }
  50639. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50640. // (ageOffset / scaledUpdateSpeed) / available cells
  50641. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50642. this._currentFrameCounter += scaledUpdateSpeed;
  50643. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50644. this._currentFrameCounter = 0;
  50645. this.cellIndex++;
  50646. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50647. this.cellIndex = this.particleSystem.endSpriteCellID;
  50648. }
  50649. }
  50650. };
  50651. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50652. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50653. this.cellIndex++;
  50654. this._currentFrameCounter = 0;
  50655. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50656. if (this.particleSystem.spriteCellLoop) {
  50657. this.cellIndex = this.particleSystem.startSpriteCellID;
  50658. }
  50659. else {
  50660. this.cellIndex = this.particleSystem.endSpriteCellID;
  50661. }
  50662. }
  50663. }
  50664. else {
  50665. this._currentFrameCounter++;
  50666. }
  50667. };
  50668. /**
  50669. * Copy the properties of particle to another one.
  50670. * @param other the particle to copy the information to.
  50671. */
  50672. Particle.prototype.copyTo = function (other) {
  50673. other.position.copyFrom(this.position);
  50674. other.direction.copyFrom(this.direction);
  50675. other.color.copyFrom(this.color);
  50676. other.colorStep.copyFrom(this.colorStep);
  50677. other.lifeTime = this.lifeTime;
  50678. other.age = this.age;
  50679. other.size = this.size;
  50680. other.angle = this.angle;
  50681. other.angularSpeed = this.angularSpeed;
  50682. other.particleSystem = this.particleSystem;
  50683. other.cellIndex = this.cellIndex;
  50684. };
  50685. return Particle;
  50686. }());
  50687. BABYLON.Particle = Particle;
  50688. })(BABYLON || (BABYLON = {}));
  50689. //# sourceMappingURL=babylon.particle.js.map
  50690. var BABYLON;
  50691. (function (BABYLON) {
  50692. /**
  50693. * This represents a particle system in Babylon.
  50694. * 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.
  50695. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50696. * @example https://doc.babylonjs.com/babylon101/particles
  50697. */
  50698. var ParticleSystem = /** @class */ (function () {
  50699. /**
  50700. * Instantiates a particle system.
  50701. * 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.
  50702. * @param name The name of the particle system
  50703. * @param capacity The max number of particles alive at the same time
  50704. * @param scene The scene the particle system belongs to
  50705. * @param customEffect a custom effect used to change the way particles are rendered by default
  50706. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50707. * @param epsilon Offset used to render the particles
  50708. */
  50709. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50710. if (customEffect === void 0) { customEffect = null; }
  50711. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50712. if (epsilon === void 0) { epsilon = 0.01; }
  50713. var _this = this;
  50714. /**
  50715. * List of animations used by the particle system.
  50716. */
  50717. this.animations = [];
  50718. /**
  50719. * The rendering group used by the Particle system to chose when to render.
  50720. */
  50721. this.renderingGroupId = 0;
  50722. /**
  50723. * The emitter represents the Mesh or position we are attaching the particle system to.
  50724. */
  50725. this.emitter = null;
  50726. /**
  50727. * The maximum number of particles to emit per frame
  50728. */
  50729. this.emitRate = 10;
  50730. /**
  50731. * If you want to launch only a few particles at once, that can be done, as well.
  50732. */
  50733. this.manualEmitCount = -1;
  50734. /**
  50735. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50736. */
  50737. this.updateSpeed = 0.01;
  50738. /**
  50739. * The amount of time the particle system is running (depends of the overall update speed).
  50740. */
  50741. this.targetStopDuration = 0;
  50742. /**
  50743. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50744. */
  50745. this.disposeOnStop = false;
  50746. /**
  50747. * Minimum power of emitting particles.
  50748. */
  50749. this.minEmitPower = 1;
  50750. /**
  50751. * Maximum power of emitting particles.
  50752. */
  50753. this.maxEmitPower = 1;
  50754. /**
  50755. * Minimum life time of emitting particles.
  50756. */
  50757. this.minLifeTime = 1;
  50758. /**
  50759. * Maximum life time of emitting particles.
  50760. */
  50761. this.maxLifeTime = 1;
  50762. /**
  50763. * Minimum Size of emitting particles.
  50764. */
  50765. this.minSize = 1;
  50766. /**
  50767. * Maximum Size of emitting particles.
  50768. */
  50769. this.maxSize = 1;
  50770. /**
  50771. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50772. */
  50773. this.minAngularSpeed = 0;
  50774. /**
  50775. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50776. */
  50777. this.maxAngularSpeed = 0;
  50778. /**
  50779. * The layer mask we are rendering the particles through.
  50780. */
  50781. this.layerMask = 0x0FFFFFFF;
  50782. /**
  50783. * This can help using your own shader to render the particle system.
  50784. * The according effect will be created
  50785. */
  50786. this.customShader = null;
  50787. /**
  50788. * By default particle system starts as soon as they are created. This prevents the
  50789. * automatic start to happen and let you decide when to start emitting particles.
  50790. */
  50791. this.preventAutoStart = false;
  50792. /**
  50793. * Callback triggered when the particle animation is ending.
  50794. */
  50795. this.onAnimationEnd = null;
  50796. /**
  50797. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50798. */
  50799. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50800. /**
  50801. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50802. * to override the particles.
  50803. */
  50804. this.forceDepthWrite = false;
  50805. /**
  50806. * You can use gravity if you want to give an orientation to your particles.
  50807. */
  50808. this.gravity = BABYLON.Vector3.Zero();
  50809. /**
  50810. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50811. */
  50812. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50813. /**
  50814. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50815. */
  50816. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50817. /**
  50818. * Color the particle will have at the end of its lifetime.
  50819. */
  50820. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50821. /**
  50822. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50823. */
  50824. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50825. /**
  50826. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50827. */
  50828. this.spriteCellLoop = true;
  50829. /**
  50830. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50831. */
  50832. this.spriteCellChangeSpeed = 0;
  50833. /**
  50834. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50835. */
  50836. this.startSpriteCellID = 0;
  50837. /**
  50838. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50839. */
  50840. this.endSpriteCellID = 0;
  50841. /**
  50842. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50843. */
  50844. this.spriteCellWidth = 0;
  50845. /**
  50846. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50847. */
  50848. this.spriteCellHeight = 0;
  50849. /**
  50850. * An event triggered when the system is disposed.
  50851. */
  50852. this.onDisposeObservable = new BABYLON.Observable();
  50853. this._particles = new Array();
  50854. this._stockParticles = new Array();
  50855. this._newPartsExcess = 0;
  50856. this._vertexBuffers = {};
  50857. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50858. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50859. this._scaledDirection = BABYLON.Vector3.Zero();
  50860. this._scaledGravity = BABYLON.Vector3.Zero();
  50861. this._currentRenderId = -1;
  50862. this._started = false;
  50863. this._stopped = false;
  50864. this._actualFrame = 0;
  50865. this._vertexBufferSize = 11;
  50866. this._appendParticleVertexes = null;
  50867. this.id = name;
  50868. this.name = name;
  50869. this._capacity = capacity;
  50870. this._epsilon = epsilon;
  50871. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50872. if (isAnimationSheetEnabled) {
  50873. this._vertexBufferSize = 12;
  50874. }
  50875. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50876. this._customEffect = customEffect;
  50877. scene.particleSystems.push(this);
  50878. this._createIndexBuffer();
  50879. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50880. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50881. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50882. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50883. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50884. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50885. if (this._isAnimationSheetEnabled) {
  50886. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50887. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50888. }
  50889. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50890. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50891. this._vertexBuffers["options"] = options;
  50892. // Default emitter type
  50893. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50894. this.updateFunction = function (particles) {
  50895. for (var index = 0; index < particles.length; index++) {
  50896. var particle = particles[index];
  50897. particle.age += _this._scaledUpdateSpeed;
  50898. if (particle.age >= particle.lifeTime) {
  50899. _this.recycleParticle(particle);
  50900. index--;
  50901. continue;
  50902. }
  50903. else {
  50904. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50905. particle.color.addInPlace(_this._scaledColorStep);
  50906. if (particle.color.a < 0)
  50907. particle.color.a = 0;
  50908. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50909. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50910. particle.position.addInPlace(_this._scaledDirection);
  50911. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50912. particle.direction.addInPlace(_this._scaledGravity);
  50913. if (_this._isAnimationSheetEnabled) {
  50914. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50915. }
  50916. }
  50917. }
  50918. };
  50919. }
  50920. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50921. /**
  50922. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50923. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50924. */
  50925. get: function () {
  50926. if (this.particleEmitterType.direction1) {
  50927. return this.particleEmitterType.direction1;
  50928. }
  50929. return BABYLON.Vector3.Zero();
  50930. },
  50931. set: function (value) {
  50932. if (this.particleEmitterType.direction1) {
  50933. this.particleEmitterType.direction1 = value;
  50934. }
  50935. },
  50936. enumerable: true,
  50937. configurable: true
  50938. });
  50939. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50940. /**
  50941. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50942. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50943. */
  50944. get: function () {
  50945. if (this.particleEmitterType.direction2) {
  50946. return this.particleEmitterType.direction2;
  50947. }
  50948. return BABYLON.Vector3.Zero();
  50949. },
  50950. set: function (value) {
  50951. if (this.particleEmitterType.direction2) {
  50952. this.particleEmitterType.direction2 = value;
  50953. }
  50954. },
  50955. enumerable: true,
  50956. configurable: true
  50957. });
  50958. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50959. /**
  50960. * 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.
  50961. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50962. */
  50963. get: function () {
  50964. if (this.particleEmitterType.minEmitBox) {
  50965. return this.particleEmitterType.minEmitBox;
  50966. }
  50967. return BABYLON.Vector3.Zero();
  50968. },
  50969. set: function (value) {
  50970. if (this.particleEmitterType.minEmitBox) {
  50971. this.particleEmitterType.minEmitBox = value;
  50972. }
  50973. },
  50974. enumerable: true,
  50975. configurable: true
  50976. });
  50977. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50978. /**
  50979. * 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.
  50980. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50981. */
  50982. get: function () {
  50983. if (this.particleEmitterType.maxEmitBox) {
  50984. return this.particleEmitterType.maxEmitBox;
  50985. }
  50986. return BABYLON.Vector3.Zero();
  50987. },
  50988. set: function (value) {
  50989. if (this.particleEmitterType.maxEmitBox) {
  50990. this.particleEmitterType.maxEmitBox = value;
  50991. }
  50992. },
  50993. enumerable: true,
  50994. configurable: true
  50995. });
  50996. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50997. /**
  50998. * Sets a callback that will be triggered when the system is disposed.
  50999. */
  51000. set: function (callback) {
  51001. if (this._onDisposeObserver) {
  51002. this.onDisposeObservable.remove(this._onDisposeObserver);
  51003. }
  51004. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51005. },
  51006. enumerable: true,
  51007. configurable: true
  51008. });
  51009. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51010. /**
  51011. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51012. */
  51013. get: function () {
  51014. return this._isAnimationSheetEnabled;
  51015. },
  51016. enumerable: true,
  51017. configurable: true
  51018. });
  51019. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51020. /**
  51021. * Gets the current list of active particles
  51022. */
  51023. get: function () {
  51024. return this._particles;
  51025. },
  51026. enumerable: true,
  51027. configurable: true
  51028. });
  51029. /**
  51030. * Returns the string "ParticleSystem"
  51031. * @returns a string containing the class name
  51032. */
  51033. ParticleSystem.prototype.getClassName = function () {
  51034. return "ParticleSystem";
  51035. };
  51036. ParticleSystem.prototype._createIndexBuffer = function () {
  51037. var indices = [];
  51038. var index = 0;
  51039. for (var count = 0; count < this._capacity; count++) {
  51040. indices.push(index);
  51041. indices.push(index + 1);
  51042. indices.push(index + 2);
  51043. indices.push(index);
  51044. indices.push(index + 2);
  51045. indices.push(index + 3);
  51046. index += 4;
  51047. }
  51048. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51049. };
  51050. /**
  51051. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51052. * Its lifetime will start back at 0.
  51053. * @param particle The particle to recycle
  51054. */
  51055. ParticleSystem.prototype.recycleParticle = function (particle) {
  51056. var lastParticle = this._particles.pop();
  51057. if (lastParticle !== particle) {
  51058. lastParticle.copyTo(particle);
  51059. this._stockParticles.push(lastParticle);
  51060. }
  51061. };
  51062. /**
  51063. * Gets the maximum number of particles active at the same time.
  51064. * @returns The max number of active particles.
  51065. */
  51066. ParticleSystem.prototype.getCapacity = function () {
  51067. return this._capacity;
  51068. };
  51069. /**
  51070. * Gets Wether there are still active particles in the system.
  51071. * @returns True if it is alive, otherwise false.
  51072. */
  51073. ParticleSystem.prototype.isAlive = function () {
  51074. return this._alive;
  51075. };
  51076. /**
  51077. * Gets Wether the system has been started.
  51078. * @returns True if it has been started, otherwise false.
  51079. */
  51080. ParticleSystem.prototype.isStarted = function () {
  51081. return this._started;
  51082. };
  51083. /**
  51084. * Starts the particle system and begins to emit.
  51085. */
  51086. ParticleSystem.prototype.start = function () {
  51087. this._started = true;
  51088. this._stopped = false;
  51089. this._actualFrame = 0;
  51090. };
  51091. /**
  51092. * Stops the particle system.
  51093. */
  51094. ParticleSystem.prototype.stop = function () {
  51095. this._stopped = true;
  51096. };
  51097. /**
  51098. * Remove all active particles
  51099. */
  51100. ParticleSystem.prototype.reset = function () {
  51101. this._stockParticles = [];
  51102. this._particles = [];
  51103. };
  51104. /**
  51105. * @ignore (for internal use only)
  51106. */
  51107. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51108. var offset = index * this._vertexBufferSize;
  51109. this._vertexData[offset] = particle.position.x;
  51110. this._vertexData[offset + 1] = particle.position.y;
  51111. this._vertexData[offset + 2] = particle.position.z;
  51112. this._vertexData[offset + 3] = particle.color.r;
  51113. this._vertexData[offset + 4] = particle.color.g;
  51114. this._vertexData[offset + 5] = particle.color.b;
  51115. this._vertexData[offset + 6] = particle.color.a;
  51116. this._vertexData[offset + 7] = particle.angle;
  51117. this._vertexData[offset + 8] = particle.size;
  51118. this._vertexData[offset + 9] = offsetX;
  51119. this._vertexData[offset + 10] = offsetY;
  51120. };
  51121. /**
  51122. * @ignore (for internal use only)
  51123. */
  51124. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51125. if (offsetX === 0)
  51126. offsetX = this._epsilon;
  51127. else if (offsetX === 1)
  51128. offsetX = 1 - this._epsilon;
  51129. if (offsetY === 0)
  51130. offsetY = this._epsilon;
  51131. else if (offsetY === 1)
  51132. offsetY = 1 - this._epsilon;
  51133. var offset = index * this._vertexBufferSize;
  51134. this._vertexData[offset] = particle.position.x;
  51135. this._vertexData[offset + 1] = particle.position.y;
  51136. this._vertexData[offset + 2] = particle.position.z;
  51137. this._vertexData[offset + 3] = particle.color.r;
  51138. this._vertexData[offset + 4] = particle.color.g;
  51139. this._vertexData[offset + 5] = particle.color.b;
  51140. this._vertexData[offset + 6] = particle.color.a;
  51141. this._vertexData[offset + 7] = particle.angle;
  51142. this._vertexData[offset + 8] = particle.size;
  51143. this._vertexData[offset + 9] = offsetX;
  51144. this._vertexData[offset + 10] = offsetY;
  51145. this._vertexData[offset + 11] = particle.cellIndex;
  51146. };
  51147. ParticleSystem.prototype._update = function (newParticles) {
  51148. // Update current
  51149. this._alive = this._particles.length > 0;
  51150. this.updateFunction(this._particles);
  51151. // Add new ones
  51152. var worldMatrix;
  51153. if (this.emitter.position) {
  51154. var emitterMesh = this.emitter;
  51155. worldMatrix = emitterMesh.getWorldMatrix();
  51156. }
  51157. else {
  51158. var emitterPosition = this.emitter;
  51159. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51160. }
  51161. var particle;
  51162. for (var index = 0; index < newParticles; index++) {
  51163. if (this._particles.length === this._capacity) {
  51164. break;
  51165. }
  51166. if (this._stockParticles.length !== 0) {
  51167. particle = this._stockParticles.pop();
  51168. particle.age = 0;
  51169. particle.cellIndex = this.startSpriteCellID;
  51170. }
  51171. else {
  51172. particle = new BABYLON.Particle(this);
  51173. }
  51174. this._particles.push(particle);
  51175. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51176. if (this.startPositionFunction) {
  51177. this.startPositionFunction(worldMatrix, particle.position, particle);
  51178. }
  51179. else {
  51180. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51181. }
  51182. if (this.startDirectionFunction) {
  51183. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51184. }
  51185. else {
  51186. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51187. }
  51188. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51189. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51190. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51191. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51192. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51193. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51194. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51195. }
  51196. };
  51197. ParticleSystem.prototype._getEffect = function () {
  51198. if (this._customEffect) {
  51199. return this._customEffect;
  51200. }
  51201. ;
  51202. var defines = [];
  51203. if (this._scene.clipPlane) {
  51204. defines.push("#define CLIPPLANE");
  51205. }
  51206. if (this._isAnimationSheetEnabled) {
  51207. defines.push("#define ANIMATESHEET");
  51208. }
  51209. // Effect
  51210. var join = defines.join("\n");
  51211. if (this._cachedDefines !== join) {
  51212. this._cachedDefines = join;
  51213. var attributesNamesOrOptions;
  51214. var effectCreationOption;
  51215. if (this._isAnimationSheetEnabled) {
  51216. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51217. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51218. }
  51219. else {
  51220. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51221. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51222. }
  51223. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51224. }
  51225. return this._effect;
  51226. };
  51227. /**
  51228. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51229. */
  51230. ParticleSystem.prototype.animate = function () {
  51231. if (!this._started)
  51232. return;
  51233. var effect = this._getEffect();
  51234. // Check
  51235. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51236. return;
  51237. if (this._currentRenderId === this._scene.getRenderId()) {
  51238. return;
  51239. }
  51240. this._currentRenderId = this._scene.getRenderId();
  51241. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51242. // determine the number of particles we need to create
  51243. var newParticles;
  51244. if (this.manualEmitCount > -1) {
  51245. newParticles = this.manualEmitCount;
  51246. this._newPartsExcess = 0;
  51247. this.manualEmitCount = 0;
  51248. }
  51249. else {
  51250. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51251. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51252. }
  51253. if (this._newPartsExcess > 1.0) {
  51254. newParticles += this._newPartsExcess >> 0;
  51255. this._newPartsExcess -= this._newPartsExcess >> 0;
  51256. }
  51257. this._alive = false;
  51258. if (!this._stopped) {
  51259. this._actualFrame += this._scaledUpdateSpeed;
  51260. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51261. this.stop();
  51262. }
  51263. else {
  51264. newParticles = 0;
  51265. }
  51266. this._update(newParticles);
  51267. // Stopped?
  51268. if (this._stopped) {
  51269. if (!this._alive) {
  51270. this._started = false;
  51271. if (this.onAnimationEnd) {
  51272. this.onAnimationEnd();
  51273. }
  51274. if (this.disposeOnStop) {
  51275. this._scene._toBeDisposed.push(this);
  51276. }
  51277. }
  51278. }
  51279. // Animation sheet
  51280. if (this._isAnimationSheetEnabled) {
  51281. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51282. }
  51283. else {
  51284. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51285. }
  51286. // Update VBO
  51287. var offset = 0;
  51288. for (var index = 0; index < this._particles.length; index++) {
  51289. var particle = this._particles[index];
  51290. this._appendParticleVertexes(offset, particle);
  51291. offset += 4;
  51292. }
  51293. if (this._vertexBuffer) {
  51294. this._vertexBuffer.update(this._vertexData);
  51295. }
  51296. };
  51297. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51298. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51299. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51300. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51301. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51302. };
  51303. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51304. this._appendParticleVertex(offset++, particle, 0, 0);
  51305. this._appendParticleVertex(offset++, particle, 1, 0);
  51306. this._appendParticleVertex(offset++, particle, 1, 1);
  51307. this._appendParticleVertex(offset++, particle, 0, 1);
  51308. };
  51309. /**
  51310. * Rebuilds the particle system.
  51311. */
  51312. ParticleSystem.prototype.rebuild = function () {
  51313. this._createIndexBuffer();
  51314. if (this._vertexBuffer) {
  51315. this._vertexBuffer._rebuild();
  51316. }
  51317. };
  51318. /**
  51319. * Renders the particle system in its current state.
  51320. * @returns the current number of particles
  51321. */
  51322. ParticleSystem.prototype.render = function () {
  51323. var effect = this._getEffect();
  51324. // Check
  51325. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51326. return 0;
  51327. }
  51328. var engine = this._scene.getEngine();
  51329. // Render
  51330. engine.enableEffect(effect);
  51331. engine.setState(false);
  51332. var viewMatrix = this._scene.getViewMatrix();
  51333. effect.setTexture("diffuseSampler", this.particleTexture);
  51334. effect.setMatrix("view", viewMatrix);
  51335. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51336. if (this._isAnimationSheetEnabled) {
  51337. var baseSize = this.particleTexture.getBaseSize();
  51338. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51339. }
  51340. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51341. if (this._scene.clipPlane) {
  51342. var clipPlane = this._scene.clipPlane;
  51343. var invView = viewMatrix.clone();
  51344. invView.invert();
  51345. effect.setMatrix("invView", invView);
  51346. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51347. }
  51348. // VBOs
  51349. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51350. // Draw order
  51351. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51352. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51353. }
  51354. else {
  51355. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51356. }
  51357. if (this.forceDepthWrite) {
  51358. engine.setDepthWrite(true);
  51359. }
  51360. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51361. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51362. return this._particles.length;
  51363. };
  51364. /**
  51365. * Disposes the particle system and free the associated resources
  51366. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51367. */
  51368. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51369. if (disposeTexture === void 0) { disposeTexture = true; }
  51370. if (this._vertexBuffer) {
  51371. this._vertexBuffer.dispose();
  51372. this._vertexBuffer = null;
  51373. }
  51374. if (this._indexBuffer) {
  51375. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51376. this._indexBuffer = null;
  51377. }
  51378. if (disposeTexture && this.particleTexture) {
  51379. this.particleTexture.dispose();
  51380. this.particleTexture = null;
  51381. }
  51382. // Remove from scene
  51383. var index = this._scene.particleSystems.indexOf(this);
  51384. if (index > -1) {
  51385. this._scene.particleSystems.splice(index, 1);
  51386. }
  51387. // Callback
  51388. this.onDisposeObservable.notifyObservers(this);
  51389. this.onDisposeObservable.clear();
  51390. };
  51391. /**
  51392. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51393. * @param radius The radius of the sphere to emit from
  51394. * @returns the emitter
  51395. */
  51396. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51397. if (radius === void 0) { radius = 1; }
  51398. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51399. this.particleEmitterType = particleEmitter;
  51400. return particleEmitter;
  51401. };
  51402. /**
  51403. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51404. * @param radius The radius of the sphere to emit from
  51405. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51406. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51407. * @returns the emitter
  51408. */
  51409. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51410. if (radius === void 0) { radius = 1; }
  51411. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51412. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51413. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51414. this.particleEmitterType = particleEmitter;
  51415. return particleEmitter;
  51416. };
  51417. /**
  51418. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51419. * @param radius The radius of the cone to emit from
  51420. * @param angle The base angle of the cone
  51421. * @returns the emitter
  51422. */
  51423. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51424. if (radius === void 0) { radius = 1; }
  51425. if (angle === void 0) { angle = Math.PI / 4; }
  51426. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51427. this.particleEmitterType = particleEmitter;
  51428. return particleEmitter;
  51429. };
  51430. // 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.
  51431. /**
  51432. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51433. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51434. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51435. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51436. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51437. * @returns the emitter
  51438. */
  51439. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51440. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51441. this.direction1 = direction1;
  51442. this.direction2 = direction2;
  51443. this.minEmitBox = minEmitBox;
  51444. this.maxEmitBox = maxEmitBox;
  51445. this.particleEmitterType = particleEmitter;
  51446. return particleEmitter;
  51447. };
  51448. /**
  51449. * Clones the particle system.
  51450. * @param name The name of the cloned object
  51451. * @param newEmitter The new emitter to use
  51452. * @returns the cloned particle system
  51453. */
  51454. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51455. var custom = null;
  51456. var program = null;
  51457. if (this.customShader != null) {
  51458. program = this.customShader;
  51459. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51460. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51461. }
  51462. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51463. result.customShader = program;
  51464. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51465. if (newEmitter === undefined) {
  51466. newEmitter = this.emitter;
  51467. }
  51468. result.emitter = newEmitter;
  51469. if (this.particleTexture) {
  51470. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51471. }
  51472. if (!this.preventAutoStart) {
  51473. result.start();
  51474. }
  51475. return result;
  51476. };
  51477. /**
  51478. * Serializes the particle system to a JSON object.
  51479. * @returns the JSON object
  51480. */
  51481. ParticleSystem.prototype.serialize = function () {
  51482. var serializationObject = {};
  51483. serializationObject.name = this.name;
  51484. serializationObject.id = this.id;
  51485. // Emitter
  51486. if (this.emitter.position) {
  51487. var emitterMesh = this.emitter;
  51488. serializationObject.emitterId = emitterMesh.id;
  51489. }
  51490. else {
  51491. var emitterPosition = this.emitter;
  51492. serializationObject.emitter = emitterPosition.asArray();
  51493. }
  51494. serializationObject.capacity = this.getCapacity();
  51495. if (this.particleTexture) {
  51496. serializationObject.textureName = this.particleTexture.name;
  51497. }
  51498. // Animations
  51499. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51500. // Particle system
  51501. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51502. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51503. serializationObject.minSize = this.minSize;
  51504. serializationObject.maxSize = this.maxSize;
  51505. serializationObject.minEmitPower = this.minEmitPower;
  51506. serializationObject.maxEmitPower = this.maxEmitPower;
  51507. serializationObject.minLifeTime = this.minLifeTime;
  51508. serializationObject.maxLifeTime = this.maxLifeTime;
  51509. serializationObject.emitRate = this.emitRate;
  51510. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51511. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51512. serializationObject.gravity = this.gravity.asArray();
  51513. serializationObject.direction1 = this.direction1.asArray();
  51514. serializationObject.direction2 = this.direction2.asArray();
  51515. serializationObject.color1 = this.color1.asArray();
  51516. serializationObject.color2 = this.color2.asArray();
  51517. serializationObject.colorDead = this.colorDead.asArray();
  51518. serializationObject.updateSpeed = this.updateSpeed;
  51519. serializationObject.targetStopDuration = this.targetStopDuration;
  51520. serializationObject.textureMask = this.textureMask.asArray();
  51521. serializationObject.blendMode = this.blendMode;
  51522. serializationObject.customShader = this.customShader;
  51523. serializationObject.preventAutoStart = this.preventAutoStart;
  51524. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51525. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51526. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51527. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51528. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51529. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51530. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51531. // Emitter
  51532. if (this.particleEmitterType) {
  51533. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51534. }
  51535. return serializationObject;
  51536. };
  51537. /**
  51538. * Parses a JSON object to create a particle system.
  51539. * @param parsedParticleSystem The JSON object to parse
  51540. * @param scene The scene to create the particle system in
  51541. * @param rootUrl The root url to use to load external dependencies like texture
  51542. * @returns the Parsed particle system
  51543. */
  51544. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51545. var name = parsedParticleSystem.name;
  51546. var custom = null;
  51547. var program = null;
  51548. if (parsedParticleSystem.customShader) {
  51549. program = parsedParticleSystem.customShader;
  51550. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51551. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51552. }
  51553. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51554. particleSystem.customShader = program;
  51555. if (parsedParticleSystem.id) {
  51556. particleSystem.id = parsedParticleSystem.id;
  51557. }
  51558. // Auto start
  51559. if (parsedParticleSystem.preventAutoStart) {
  51560. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51561. }
  51562. // Texture
  51563. if (parsedParticleSystem.textureName) {
  51564. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51565. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51566. }
  51567. // Emitter
  51568. if (parsedParticleSystem.emitterId) {
  51569. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51570. }
  51571. else {
  51572. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51573. }
  51574. // Animations
  51575. if (parsedParticleSystem.animations) {
  51576. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51577. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51578. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51579. }
  51580. }
  51581. if (parsedParticleSystem.autoAnimate) {
  51582. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51583. }
  51584. // Particle system
  51585. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51586. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51587. particleSystem.minSize = parsedParticleSystem.minSize;
  51588. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51589. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51590. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51591. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51592. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51593. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51594. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51595. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51596. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51597. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51598. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51599. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51600. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51601. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51602. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51603. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51604. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51605. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51606. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51607. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51608. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51609. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51610. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51611. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51612. if (!particleSystem.preventAutoStart) {
  51613. particleSystem.start();
  51614. }
  51615. return particleSystem;
  51616. };
  51617. /**
  51618. * Source color is added to the destination color without alpha affecting the result.
  51619. */
  51620. ParticleSystem.BLENDMODE_ONEONE = 0;
  51621. /**
  51622. * Blend current color and particle color using particle’s alpha.
  51623. */
  51624. ParticleSystem.BLENDMODE_STANDARD = 1;
  51625. return ParticleSystem;
  51626. }());
  51627. BABYLON.ParticleSystem = ParticleSystem;
  51628. })(BABYLON || (BABYLON = {}));
  51629. //# sourceMappingURL=babylon.particleSystem.js.map
  51630. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51631. var BABYLON;
  51632. (function (BABYLON) {
  51633. /**
  51634. * Particle emitter emitting particles from the inside of a box.
  51635. * It emits the particles randomly between 2 given directions.
  51636. */
  51637. var BoxParticleEmitter = /** @class */ (function () {
  51638. /**
  51639. * Creates a new instance of @see BoxParticleEmitter
  51640. */
  51641. function BoxParticleEmitter() {
  51642. /**
  51643. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51644. */
  51645. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51646. /**
  51647. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51648. */
  51649. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51650. /**
  51651. * 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.
  51652. */
  51653. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51654. /**
  51655. * 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.
  51656. */
  51657. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51658. }
  51659. /**
  51660. * Called by the particle System when the direction is computed for the created particle.
  51661. * @param emitPower is the power of the particle (speed)
  51662. * @param worldMatrix is the world matrix of the particle system
  51663. * @param directionToUpdate is the direction vector to update with the result
  51664. * @param particle is the particle we are computed the direction for
  51665. */
  51666. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51667. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51668. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51669. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51670. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51671. };
  51672. /**
  51673. * Called by the particle System when the position is computed for the created particle.
  51674. * @param worldMatrix is the world matrix of the particle system
  51675. * @param positionToUpdate is the position vector to update with the result
  51676. * @param particle is the particle we are computed the position for
  51677. */
  51678. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51679. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51680. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51681. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51682. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51683. };
  51684. /**
  51685. * Clones the current emitter and returns a copy of it
  51686. * @returns the new emitter
  51687. */
  51688. BoxParticleEmitter.prototype.clone = function () {
  51689. var newOne = new BoxParticleEmitter();
  51690. BABYLON.Tools.DeepCopy(this, newOne);
  51691. return newOne;
  51692. };
  51693. /**
  51694. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51695. * @param effect defines the update shader
  51696. */
  51697. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51698. effect.setVector3("direction1", this.direction1);
  51699. effect.setVector3("direction2", this.direction2);
  51700. effect.setVector3("minEmitBox", this.minEmitBox);
  51701. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51702. };
  51703. /**
  51704. * Returns a string to use to update the GPU particles update shader
  51705. * @returns a string containng the defines string
  51706. */
  51707. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51708. return "#define BOXEMITTER";
  51709. };
  51710. /**
  51711. * Returns the string "BoxEmitter"
  51712. * @returns a string containing the class name
  51713. */
  51714. BoxParticleEmitter.prototype.getClassName = function () {
  51715. return "BoxEmitter";
  51716. };
  51717. /**
  51718. * Serializes the particle system to a JSON object.
  51719. * @returns the JSON object
  51720. */
  51721. BoxParticleEmitter.prototype.serialize = function () {
  51722. var serializationObject = {};
  51723. serializationObject.type = this.getClassName();
  51724. serializationObject.direction1 = this.direction1.asArray();
  51725. ;
  51726. serializationObject.direction2 = this.direction2.asArray();
  51727. ;
  51728. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51729. ;
  51730. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51731. ;
  51732. return serializationObject;
  51733. };
  51734. /**
  51735. * Parse properties from a JSON object
  51736. * @param serializationObject defines the JSON object
  51737. */
  51738. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51739. this.direction1.copyFrom(serializationObject.direction1);
  51740. this.direction2.copyFrom(serializationObject.direction2);
  51741. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51742. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51743. };
  51744. return BoxParticleEmitter;
  51745. }());
  51746. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51747. })(BABYLON || (BABYLON = {}));
  51748. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51749. var BABYLON;
  51750. (function (BABYLON) {
  51751. /**
  51752. * Particle emitter emitting particles from the inside of a cone.
  51753. * It emits the particles alongside the cone volume from the base to the particle.
  51754. * The emission direction might be randomized.
  51755. */
  51756. var ConeParticleEmitter = /** @class */ (function () {
  51757. /**
  51758. * Creates a new instance of @see ConeParticleEmitter
  51759. * @param radius the radius of the emission cone (1 by default)
  51760. * @param angles the cone base angle (PI by default)
  51761. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51762. */
  51763. function ConeParticleEmitter(radius,
  51764. /**
  51765. * The radius of the emission cone.
  51766. */
  51767. angle,
  51768. /**
  51769. * The cone base angle.
  51770. */
  51771. directionRandomizer) {
  51772. if (radius === void 0) { radius = 1; }
  51773. if (angle === void 0) { angle = Math.PI; }
  51774. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51775. this.angle = angle;
  51776. this.directionRandomizer = directionRandomizer;
  51777. this.radius = radius;
  51778. }
  51779. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51780. /**
  51781. * Gets the radius of the emission cone.
  51782. */
  51783. get: function () {
  51784. return this._radius;
  51785. },
  51786. /**
  51787. * Sets the radius of the emission cone.
  51788. */
  51789. set: function (value) {
  51790. this._radius = value;
  51791. if (this.angle !== 0) {
  51792. this._height = value / Math.tan(this.angle / 2);
  51793. }
  51794. else {
  51795. this._height = 1;
  51796. }
  51797. },
  51798. enumerable: true,
  51799. configurable: true
  51800. });
  51801. /**
  51802. * Called by the particle System when the direction is computed for the created particle.
  51803. * @param emitPower is the power of the particle (speed)
  51804. * @param worldMatrix is the world matrix of the particle system
  51805. * @param directionToUpdate is the direction vector to update with the result
  51806. * @param particle is the particle we are computed the direction for
  51807. */
  51808. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51809. if (this.angle === 0) {
  51810. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51811. }
  51812. else {
  51813. // measure the direction Vector from the emitter to the particle.
  51814. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51815. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51816. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51817. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51818. direction.x += randX;
  51819. direction.y += randY;
  51820. direction.z += randZ;
  51821. direction.normalize();
  51822. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51823. }
  51824. };
  51825. /**
  51826. * Called by the particle System when the position is computed for the created particle.
  51827. * @param worldMatrix is the world matrix of the particle system
  51828. * @param positionToUpdate is the position vector to update with the result
  51829. * @param particle is the particle we are computed the position for
  51830. */
  51831. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51832. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51833. var h = BABYLON.Scalar.RandomRange(0, 1);
  51834. // Better distribution in a cone at normal angles.
  51835. h = 1 - h * h;
  51836. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51837. radius = radius * h / this._height;
  51838. var randX = radius * Math.sin(s);
  51839. var randZ = radius * Math.cos(s);
  51840. var randY = h * this._height;
  51841. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51842. };
  51843. /**
  51844. * Clones the current emitter and returns a copy of it
  51845. * @returns the new emitter
  51846. */
  51847. ConeParticleEmitter.prototype.clone = function () {
  51848. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51849. BABYLON.Tools.DeepCopy(this, newOne);
  51850. return newOne;
  51851. };
  51852. /**
  51853. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51854. * @param effect defines the update shader
  51855. */
  51856. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51857. effect.setFloat("radius", this.radius);
  51858. effect.setFloat("angle", this.angle);
  51859. effect.setFloat("height", this._height);
  51860. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51861. };
  51862. /**
  51863. * Returns a string to use to update the GPU particles update shader
  51864. * @returns a string containng the defines string
  51865. */
  51866. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51867. return "#define CONEEMITTER";
  51868. };
  51869. /**
  51870. * Returns the string "BoxEmitter"
  51871. * @returns a string containing the class name
  51872. */
  51873. ConeParticleEmitter.prototype.getClassName = function () {
  51874. return "ConeEmitter";
  51875. };
  51876. /**
  51877. * Serializes the particle system to a JSON object.
  51878. * @returns the JSON object
  51879. */
  51880. ConeParticleEmitter.prototype.serialize = function () {
  51881. var serializationObject = {};
  51882. serializationObject.type = this.getClassName();
  51883. serializationObject.radius = this.radius;
  51884. serializationObject.angle = this.angle;
  51885. serializationObject.directionRandomizer = this.directionRandomizer;
  51886. return serializationObject;
  51887. };
  51888. /**
  51889. * Parse properties from a JSON object
  51890. * @param serializationObject defines the JSON object
  51891. */
  51892. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51893. this.radius = serializationObject.radius;
  51894. this.angle = serializationObject.angle;
  51895. this.directionRandomizer = serializationObject.directionRandomizer;
  51896. };
  51897. return ConeParticleEmitter;
  51898. }());
  51899. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51900. })(BABYLON || (BABYLON = {}));
  51901. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51902. var BABYLON;
  51903. (function (BABYLON) {
  51904. /**
  51905. * Particle emitter emitting particles from the inside of a sphere.
  51906. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51907. */
  51908. var SphereParticleEmitter = /** @class */ (function () {
  51909. /**
  51910. * Creates a new instance of @see SphereParticleEmitter
  51911. * @param radius the radius of the emission sphere (1 by default)
  51912. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51913. */
  51914. function SphereParticleEmitter(
  51915. /**
  51916. * The radius of the emission sphere.
  51917. */
  51918. radius,
  51919. /**
  51920. * How much to randomize the particle direction [0-1].
  51921. */
  51922. directionRandomizer) {
  51923. if (radius === void 0) { radius = 1; }
  51924. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51925. this.radius = radius;
  51926. this.directionRandomizer = directionRandomizer;
  51927. }
  51928. /**
  51929. * Called by the particle System when the direction is computed for the created particle.
  51930. * @param emitPower is the power of the particle (speed)
  51931. * @param worldMatrix is the world matrix of the particle system
  51932. * @param directionToUpdate is the direction vector to update with the result
  51933. * @param particle is the particle we are computed the direction for
  51934. */
  51935. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51936. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51937. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51938. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51939. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51940. direction.x += randX;
  51941. direction.y += randY;
  51942. direction.z += randZ;
  51943. direction.normalize();
  51944. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51945. };
  51946. /**
  51947. * Called by the particle System when the position is computed for the created particle.
  51948. * @param worldMatrix is the world matrix of the particle system
  51949. * @param positionToUpdate is the position vector to update with the result
  51950. * @param particle is the particle we are computed the position for
  51951. */
  51952. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51953. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51954. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51955. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51956. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51957. var randY = randRadius * Math.cos(theta);
  51958. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51959. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51960. };
  51961. /**
  51962. * Clones the current emitter and returns a copy of it
  51963. * @returns the new emitter
  51964. */
  51965. SphereParticleEmitter.prototype.clone = function () {
  51966. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51967. BABYLON.Tools.DeepCopy(this, newOne);
  51968. return newOne;
  51969. };
  51970. /**
  51971. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51972. * @param effect defines the update shader
  51973. */
  51974. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51975. effect.setFloat("radius", this.radius);
  51976. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51977. };
  51978. /**
  51979. * Returns a string to use to update the GPU particles update shader
  51980. * @returns a string containng the defines string
  51981. */
  51982. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51983. return "#define SPHEREEMITTER";
  51984. };
  51985. /**
  51986. * Returns the string "SphereParticleEmitter"
  51987. * @returns a string containing the class name
  51988. */
  51989. SphereParticleEmitter.prototype.getClassName = function () {
  51990. return "SphereParticleEmitter";
  51991. };
  51992. /**
  51993. * Serializes the particle system to a JSON object.
  51994. * @returns the JSON object
  51995. */
  51996. SphereParticleEmitter.prototype.serialize = function () {
  51997. var serializationObject = {};
  51998. serializationObject.type = this.getClassName();
  51999. serializationObject.radius = this.radius;
  52000. serializationObject.directionRandomizer = this.directionRandomizer;
  52001. return serializationObject;
  52002. };
  52003. /**
  52004. * Parse properties from a JSON object
  52005. * @param serializationObject defines the JSON object
  52006. */
  52007. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52008. this.radius = serializationObject.radius;
  52009. this.directionRandomizer = serializationObject.directionRandomizer;
  52010. };
  52011. return SphereParticleEmitter;
  52012. }());
  52013. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52014. /**
  52015. * Particle emitter emitting particles from the inside of a sphere.
  52016. * It emits the particles randomly between two vectors.
  52017. */
  52018. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52019. __extends(SphereDirectedParticleEmitter, _super);
  52020. /**
  52021. * Creates a new instance of @see SphereDirectedParticleEmitter
  52022. * @param radius the radius of the emission sphere (1 by default)
  52023. * @param direction1 the min limit of the emission direction (up vector by default)
  52024. * @param direction2 the max limit of the emission direction (up vector by default)
  52025. */
  52026. function SphereDirectedParticleEmitter(radius,
  52027. /**
  52028. * The min limit of the emission direction.
  52029. */
  52030. direction1,
  52031. /**
  52032. * The max limit of the emission direction.
  52033. */
  52034. direction2) {
  52035. if (radius === void 0) { radius = 1; }
  52036. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52037. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52038. var _this = _super.call(this, radius) || this;
  52039. _this.direction1 = direction1;
  52040. _this.direction2 = direction2;
  52041. return _this;
  52042. }
  52043. /**
  52044. * Called by the particle System when the direction is computed for the created particle.
  52045. * @param emitPower is the power of the particle (speed)
  52046. * @param worldMatrix is the world matrix of the particle system
  52047. * @param directionToUpdate is the direction vector to update with the result
  52048. * @param particle is the particle we are computed the direction for
  52049. */
  52050. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52051. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52052. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52053. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52054. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52055. };
  52056. /**
  52057. * Clones the current emitter and returns a copy of it
  52058. * @returns the new emitter
  52059. */
  52060. SphereDirectedParticleEmitter.prototype.clone = function () {
  52061. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52062. BABYLON.Tools.DeepCopy(this, newOne);
  52063. return newOne;
  52064. };
  52065. /**
  52066. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52067. * @param effect defines the update shader
  52068. */
  52069. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52070. effect.setFloat("radius", this.radius);
  52071. effect.setVector3("direction1", this.direction1);
  52072. effect.setVector3("direction2", this.direction2);
  52073. };
  52074. /**
  52075. * Returns a string to use to update the GPU particles update shader
  52076. * @returns a string containng the defines string
  52077. */
  52078. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52079. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52080. };
  52081. /**
  52082. * Returns the string "SphereDirectedParticleEmitter"
  52083. * @returns a string containing the class name
  52084. */
  52085. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52086. return "SphereDirectedParticleEmitter";
  52087. };
  52088. /**
  52089. * Serializes the particle system to a JSON object.
  52090. * @returns the JSON object
  52091. */
  52092. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52093. var serializationObject = _super.prototype.serialize.call(this);
  52094. ;
  52095. serializationObject.direction1 = this.direction1.asArray();
  52096. ;
  52097. serializationObject.direction2 = this.direction2.asArray();
  52098. ;
  52099. return serializationObject;
  52100. };
  52101. /**
  52102. * Parse properties from a JSON object
  52103. * @param serializationObject defines the JSON object
  52104. */
  52105. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52106. _super.prototype.parse.call(this, serializationObject);
  52107. this.direction1.copyFrom(serializationObject.direction1);
  52108. this.direction2.copyFrom(serializationObject.direction2);
  52109. };
  52110. return SphereDirectedParticleEmitter;
  52111. }(SphereParticleEmitter));
  52112. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52113. })(BABYLON || (BABYLON = {}));
  52114. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52115. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52116. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52117. s = arguments[i];
  52118. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52119. t[p] = s[p];
  52120. }
  52121. return t;
  52122. };
  52123. var BABYLON;
  52124. (function (BABYLON) {
  52125. /**
  52126. * This represents a GPU particle system in Babylon
  52127. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52128. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52129. */
  52130. var GPUParticleSystem = /** @class */ (function () {
  52131. /**
  52132. * Instantiates a GPU particle system.
  52133. * 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.
  52134. * @param name The name of the particle system
  52135. * @param capacity The max number of particles alive at the same time
  52136. * @param scene The scene the particle system belongs to
  52137. */
  52138. function GPUParticleSystem(name, options, scene) {
  52139. /**
  52140. * The emitter represents the Mesh or position we are attaching the particle system to.
  52141. */
  52142. this.emitter = null;
  52143. /**
  52144. * The rendering group used by the Particle system to chose when to render.
  52145. */
  52146. this.renderingGroupId = 0;
  52147. /**
  52148. * The layer mask we are rendering the particles through.
  52149. */
  52150. this.layerMask = 0x0FFFFFFF;
  52151. this._targetIndex = 0;
  52152. this._currentRenderId = -1;
  52153. this._started = false;
  52154. this._stopped = false;
  52155. this._timeDelta = 0;
  52156. this._attributesStrideSize = 14;
  52157. this._actualFrame = 0;
  52158. /**
  52159. * List of animations used by the particle system.
  52160. */
  52161. this.animations = [];
  52162. /**
  52163. * An event triggered when the system is disposed.
  52164. */
  52165. this.onDisposeObservable = new BABYLON.Observable();
  52166. /**
  52167. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52168. */
  52169. this.updateSpeed = 0.01;
  52170. /**
  52171. * The amount of time the particle system is running (depends of the overall update speed).
  52172. */
  52173. this.targetStopDuration = 0;
  52174. /**
  52175. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52176. */
  52177. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52178. /**
  52179. * Minimum life time of emitting particles.
  52180. */
  52181. this.minLifeTime = 1;
  52182. /**
  52183. * Maximum life time of emitting particles.
  52184. */
  52185. this.maxLifeTime = 1;
  52186. /**
  52187. * Minimum Size of emitting particles.
  52188. */
  52189. this.minSize = 1;
  52190. /**
  52191. * Maximum Size of emitting particles.
  52192. */
  52193. this.maxSize = 1;
  52194. /**
  52195. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52196. */
  52197. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52198. /**
  52199. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52200. */
  52201. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52202. /**
  52203. * Color the particle will have at the end of its lifetime.
  52204. */
  52205. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52206. /**
  52207. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52208. */
  52209. this.emitRate = 100;
  52210. /**
  52211. * You can use gravity if you want to give an orientation to your particles.
  52212. */
  52213. this.gravity = BABYLON.Vector3.Zero();
  52214. /**
  52215. * Minimum power of emitting particles.
  52216. */
  52217. this.minEmitPower = 1;
  52218. /**
  52219. * Maximum power of emitting particles.
  52220. */
  52221. this.maxEmitPower = 1;
  52222. this.id = name;
  52223. this.name = name;
  52224. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52225. this._engine = this._scene.getEngine();
  52226. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52227. this._capacity = fullOptions.capacity;
  52228. this._activeCount = fullOptions.capacity;
  52229. this._currentActiveCount = 0;
  52230. this._scene.particleSystems.push(this);
  52231. this._updateEffectOptions = {
  52232. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  52233. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  52234. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle"],
  52235. uniformBuffersNames: [],
  52236. samplers: ["randomSampler"],
  52237. defines: "",
  52238. fallbacks: null,
  52239. onCompiled: null,
  52240. onError: null,
  52241. indexParameters: null,
  52242. maxSimultaneousLights: 0,
  52243. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  52244. };
  52245. // Random data
  52246. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  52247. var d = [];
  52248. for (var i = 0; i < maxTextureSize; ++i) {
  52249. d.push(Math.random());
  52250. d.push(Math.random());
  52251. d.push(Math.random());
  52252. d.push(Math.random());
  52253. }
  52254. 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);
  52255. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52256. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52257. this._randomTextureSize = maxTextureSize;
  52258. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52259. }
  52260. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52261. /**
  52262. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52263. */
  52264. get: function () {
  52265. if (!BABYLON.Engine.LastCreatedEngine) {
  52266. return false;
  52267. }
  52268. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52269. },
  52270. enumerable: true,
  52271. configurable: true
  52272. });
  52273. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52274. /**
  52275. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52276. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52277. */
  52278. get: function () {
  52279. if (this.particleEmitterType.direction1) {
  52280. return this.particleEmitterType.direction1;
  52281. }
  52282. return BABYLON.Vector3.Zero();
  52283. },
  52284. set: function (value) {
  52285. if (this.particleEmitterType.direction1) {
  52286. this.particleEmitterType.direction1 = value;
  52287. }
  52288. },
  52289. enumerable: true,
  52290. configurable: true
  52291. });
  52292. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52293. /**
  52294. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52295. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52296. */
  52297. get: function () {
  52298. if (this.particleEmitterType.direction2) {
  52299. return this.particleEmitterType.direction2;
  52300. }
  52301. return BABYLON.Vector3.Zero();
  52302. },
  52303. set: function (value) {
  52304. if (this.particleEmitterType.direction2) {
  52305. this.particleEmitterType.direction2 = value;
  52306. }
  52307. },
  52308. enumerable: true,
  52309. configurable: true
  52310. });
  52311. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52312. /**
  52313. * 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.
  52314. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52315. */
  52316. get: function () {
  52317. if (this.particleEmitterType.minEmitBox) {
  52318. return this.particleEmitterType.minEmitBox;
  52319. }
  52320. return BABYLON.Vector3.Zero();
  52321. },
  52322. set: function (value) {
  52323. if (this.particleEmitterType.minEmitBox) {
  52324. this.particleEmitterType.minEmitBox = value;
  52325. }
  52326. },
  52327. enumerable: true,
  52328. configurable: true
  52329. });
  52330. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52331. /**
  52332. * 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.
  52333. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52334. */
  52335. get: function () {
  52336. if (this.particleEmitterType.maxEmitBox) {
  52337. return this.particleEmitterType.maxEmitBox;
  52338. }
  52339. return BABYLON.Vector3.Zero();
  52340. },
  52341. set: function (value) {
  52342. if (this.particleEmitterType.maxEmitBox) {
  52343. this.particleEmitterType.maxEmitBox = value;
  52344. }
  52345. },
  52346. enumerable: true,
  52347. configurable: true
  52348. });
  52349. /**
  52350. * Gets the maximum number of particles active at the same time.
  52351. * @returns The max number of active particles.
  52352. */
  52353. GPUParticleSystem.prototype.getCapacity = function () {
  52354. return this._capacity;
  52355. };
  52356. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  52357. /**
  52358. * Gets or set the number of active particles
  52359. */
  52360. get: function () {
  52361. return this._activeCount;
  52362. },
  52363. set: function (value) {
  52364. this._activeCount = Math.min(value, this._capacity);
  52365. },
  52366. enumerable: true,
  52367. configurable: true
  52368. });
  52369. /**
  52370. * Gets Wether the system has been started.
  52371. * @returns True if it has been started, otherwise false.
  52372. */
  52373. GPUParticleSystem.prototype.isStarted = function () {
  52374. return this._started;
  52375. };
  52376. /**
  52377. * Starts the particle system and begins to emit.
  52378. */
  52379. GPUParticleSystem.prototype.start = function () {
  52380. this._started = true;
  52381. this._stopped = false;
  52382. };
  52383. /**
  52384. * Stops the particle system.
  52385. */
  52386. GPUParticleSystem.prototype.stop = function () {
  52387. this._stopped = true;
  52388. };
  52389. /**
  52390. * Remove all active particles
  52391. */
  52392. GPUParticleSystem.prototype.reset = function () {
  52393. this._releaseBuffers();
  52394. this._releaseVAOs();
  52395. this._currentActiveCount = 0;
  52396. this._targetIndex = 0;
  52397. };
  52398. /**
  52399. * Returns the string "GPUParticleSystem"
  52400. * @returns a string containing the class name
  52401. */
  52402. GPUParticleSystem.prototype.getClassName = function () {
  52403. return "GPUParticleSystem";
  52404. };
  52405. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  52406. var updateVertexBuffers = {};
  52407. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  52408. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  52409. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  52410. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  52411. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  52412. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  52413. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  52414. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  52415. this._engine.bindArrayBuffer(null);
  52416. return vao;
  52417. };
  52418. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  52419. var renderVertexBuffers = {};
  52420. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  52421. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  52422. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  52423. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  52424. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  52425. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  52426. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  52427. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  52428. this._engine.bindArrayBuffer(null);
  52429. return vao;
  52430. };
  52431. GPUParticleSystem.prototype._initialize = function (force) {
  52432. if (force === void 0) { force = false; }
  52433. if (this._buffer0 && !force) {
  52434. return;
  52435. }
  52436. var engine = this._scene.getEngine();
  52437. var data = new Array();
  52438. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  52439. // position
  52440. data.push(0.0);
  52441. data.push(0.0);
  52442. data.push(0.0);
  52443. // Age and life
  52444. data.push(0.0); // create the particle as a dead one to create a new one at start
  52445. data.push(0.0);
  52446. // Seed
  52447. data.push(Math.random());
  52448. // Size
  52449. data.push(0.0);
  52450. // color
  52451. data.push(0.0);
  52452. data.push(0.0);
  52453. data.push(0.0);
  52454. data.push(0.0);
  52455. // direction
  52456. data.push(0.0);
  52457. data.push(0.0);
  52458. data.push(0.0);
  52459. }
  52460. // Sprite data
  52461. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  52462. -0.5, 0.5, 0, 1,
  52463. -0.5, -0.5, 0, 0,
  52464. 0.5, -0.5, 1, 0]);
  52465. // Buffers
  52466. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52467. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52468. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  52469. // Update VAO
  52470. this._updateVAO = [];
  52471. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  52472. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  52473. // Render VAO
  52474. this._renderVAO = [];
  52475. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  52476. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  52477. // Links
  52478. this._sourceBuffer = this._buffer0;
  52479. this._targetBuffer = this._buffer1;
  52480. };
  52481. /** @ignore */
  52482. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  52483. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  52484. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  52485. return;
  52486. }
  52487. this._updateEffectOptions.defines = defines;
  52488. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  52489. };
  52490. /** @ignore */
  52491. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  52492. var defines = "";
  52493. if (this._scene.clipPlane) {
  52494. defines = "\n#define CLIPPLANE";
  52495. }
  52496. if (this._renderEffect && this._renderEffect.defines === defines) {
  52497. return;
  52498. }
  52499. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  52500. };
  52501. /**
  52502. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52503. */
  52504. GPUParticleSystem.prototype.animate = function () {
  52505. if (!this._stopped) {
  52506. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  52507. this._actualFrame += this._timeDelta;
  52508. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52509. this.stop();
  52510. }
  52511. else {
  52512. this._timeDelta = 0;
  52513. }
  52514. };
  52515. /**
  52516. * Renders the particle system in its current state.
  52517. * @returns the current number of particles
  52518. */
  52519. GPUParticleSystem.prototype.render = function () {
  52520. if (!this._started) {
  52521. return 0;
  52522. }
  52523. this._recreateUpdateEffect();
  52524. this._recreateRenderEffect();
  52525. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  52526. return 0;
  52527. }
  52528. if (this._currentRenderId === this._scene.getRenderId()) {
  52529. return 0;
  52530. }
  52531. this._currentRenderId = this._scene.getRenderId();
  52532. // Get everything ready to render
  52533. this._initialize();
  52534. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  52535. // Enable update effect
  52536. this._engine.enableEffect(this._updateEffect);
  52537. this._engine.setState(false);
  52538. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  52539. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  52540. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  52541. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  52542. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  52543. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  52544. this._updateEffect.setDirectColor4("color1", this.color1);
  52545. this._updateEffect.setDirectColor4("color2", this.color2);
  52546. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  52547. this._updateEffect.setVector3("gravity", this.gravity);
  52548. if (this.particleEmitterType) {
  52549. this.particleEmitterType.applyToShader(this._updateEffect);
  52550. }
  52551. var emitterWM;
  52552. if (this.emitter.position) {
  52553. var emitterMesh = this.emitter;
  52554. emitterWM = emitterMesh.getWorldMatrix();
  52555. }
  52556. else {
  52557. var emitterPosition = this.emitter;
  52558. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52559. }
  52560. this._updateEffect.setMatrix("emitterWM", emitterWM);
  52561. // Bind source VAO
  52562. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  52563. // Update
  52564. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  52565. this._engine.setRasterizerState(false);
  52566. this._engine.beginTransformFeedback();
  52567. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  52568. this._engine.endTransformFeedback();
  52569. this._engine.setRasterizerState(true);
  52570. this._engine.bindTransformFeedbackBuffer(null);
  52571. // Enable render effect
  52572. this._engine.enableEffect(this._renderEffect);
  52573. var viewMatrix = this._scene.getViewMatrix();
  52574. this._renderEffect.setMatrix("view", viewMatrix);
  52575. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  52576. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  52577. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  52578. if (this._scene.clipPlane) {
  52579. var clipPlane = this._scene.clipPlane;
  52580. var invView = viewMatrix.clone();
  52581. invView.invert();
  52582. this._renderEffect.setMatrix("invView", invView);
  52583. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52584. }
  52585. // Draw order
  52586. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  52587. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52588. }
  52589. else {
  52590. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52591. }
  52592. // Bind source VAO
  52593. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  52594. // Render
  52595. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  52596. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52597. // Switch VAOs
  52598. this._targetIndex++;
  52599. if (this._targetIndex === 2) {
  52600. this._targetIndex = 0;
  52601. }
  52602. // Switch buffers
  52603. var tmpBuffer = this._sourceBuffer;
  52604. this._sourceBuffer = this._targetBuffer;
  52605. this._targetBuffer = tmpBuffer;
  52606. return this._currentActiveCount;
  52607. };
  52608. /**
  52609. * Rebuilds the particle system
  52610. */
  52611. GPUParticleSystem.prototype.rebuild = function () {
  52612. this._initialize(true);
  52613. };
  52614. GPUParticleSystem.prototype._releaseBuffers = function () {
  52615. if (this._buffer0) {
  52616. this._buffer0.dispose();
  52617. this._buffer0 = null;
  52618. }
  52619. if (this._buffer1) {
  52620. this._buffer1.dispose();
  52621. this._buffer1 = null;
  52622. }
  52623. if (this._spriteBuffer) {
  52624. this._spriteBuffer.dispose();
  52625. this._spriteBuffer = null;
  52626. }
  52627. };
  52628. GPUParticleSystem.prototype._releaseVAOs = function () {
  52629. for (var index = 0; index < this._updateVAO.length; index++) {
  52630. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52631. }
  52632. this._updateVAO = [];
  52633. for (var index = 0; index < this._renderVAO.length; index++) {
  52634. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52635. }
  52636. this._renderVAO = [];
  52637. };
  52638. /**
  52639. * Disposes the particle system and free the associated resources
  52640. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52641. */
  52642. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  52643. if (disposeTexture === void 0) { disposeTexture = true; }
  52644. var index = this._scene.particleSystems.indexOf(this);
  52645. if (index > -1) {
  52646. this._scene.particleSystems.splice(index, 1);
  52647. }
  52648. this._releaseBuffers();
  52649. this._releaseVAOs();
  52650. if (this._randomTexture) {
  52651. this._randomTexture.dispose();
  52652. this._randomTexture = null;
  52653. }
  52654. if (disposeTexture && this.particleTexture) {
  52655. this.particleTexture.dispose();
  52656. this.particleTexture = null;
  52657. }
  52658. // Callback
  52659. this.onDisposeObservable.notifyObservers(this);
  52660. this.onDisposeObservable.clear();
  52661. };
  52662. /**
  52663. * Clones the particle system.
  52664. * @param name The name of the cloned object
  52665. * @param newEmitter The new emitter to use
  52666. * @returns the cloned particle system
  52667. */
  52668. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52669. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  52670. BABYLON.Tools.DeepCopy(this, result);
  52671. if (newEmitter === undefined) {
  52672. newEmitter = this.emitter;
  52673. }
  52674. result.emitter = newEmitter;
  52675. if (this.particleTexture) {
  52676. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52677. }
  52678. return result;
  52679. };
  52680. /**
  52681. * Serializes the particle system to a JSON object.
  52682. * @returns the JSON object
  52683. */
  52684. GPUParticleSystem.prototype.serialize = function () {
  52685. var serializationObject = {};
  52686. serializationObject.name = this.name;
  52687. serializationObject.id = this.id;
  52688. // Emitter
  52689. if (this.emitter.position) {
  52690. var emitterMesh = this.emitter;
  52691. serializationObject.emitterId = emitterMesh.id;
  52692. }
  52693. else {
  52694. var emitterPosition = this.emitter;
  52695. serializationObject.emitter = emitterPosition.asArray();
  52696. }
  52697. serializationObject.capacity = this.getCapacity();
  52698. if (this.particleTexture) {
  52699. serializationObject.textureName = this.particleTexture.name;
  52700. }
  52701. // Animations
  52702. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52703. // Particle system
  52704. serializationObject.activeParticleCount = this.activeParticleCount;
  52705. serializationObject.randomTextureSize = this._randomTextureSize;
  52706. serializationObject.minSize = this.minSize;
  52707. serializationObject.maxSize = this.maxSize;
  52708. serializationObject.minEmitPower = this.minEmitPower;
  52709. serializationObject.maxEmitPower = this.maxEmitPower;
  52710. serializationObject.minLifeTime = this.minLifeTime;
  52711. serializationObject.maxLifeTime = this.maxLifeTime;
  52712. serializationObject.emitRate = this.emitRate;
  52713. serializationObject.gravity = this.gravity.asArray();
  52714. serializationObject.color1 = this.color1.asArray();
  52715. serializationObject.color2 = this.color2.asArray();
  52716. serializationObject.colorDead = this.colorDead.asArray();
  52717. serializationObject.updateSpeed = this.updateSpeed;
  52718. serializationObject.targetStopDuration = this.targetStopDuration;
  52719. serializationObject.blendMode = this.blendMode;
  52720. // Emitter
  52721. if (this.particleEmitterType) {
  52722. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52723. }
  52724. return serializationObject;
  52725. };
  52726. /**
  52727. * Parses a JSON object to create a GPU particle system.
  52728. * @param parsedParticleSystem The JSON object to parse
  52729. * @param scene The scene to create the particle system in
  52730. * @param rootUrl The root url to use to load external dependencies like texture
  52731. * @returns the parsed GPU particle system
  52732. */
  52733. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52734. var name = parsedParticleSystem.name;
  52735. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  52736. if (parsedParticleSystem.id) {
  52737. particleSystem.id = parsedParticleSystem.id;
  52738. }
  52739. // Texture
  52740. if (parsedParticleSystem.textureName) {
  52741. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52742. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52743. }
  52744. // Emitter
  52745. if (parsedParticleSystem.emitterId) {
  52746. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52747. }
  52748. else {
  52749. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52750. }
  52751. // Animations
  52752. if (parsedParticleSystem.animations) {
  52753. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52754. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52755. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52756. }
  52757. }
  52758. // Particle system
  52759. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  52760. particleSystem.minSize = parsedParticleSystem.minSize;
  52761. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52762. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52763. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52764. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52765. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52766. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52767. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52768. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52769. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52770. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52771. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52772. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52773. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52774. // Emitter
  52775. if (parsedParticleSystem.particleEmitterType) {
  52776. var emitterType = void 0;
  52777. switch (parsedParticleSystem.particleEmitterType.type) {
  52778. case "SphereEmitter":
  52779. emitterType = new BABYLON.SphereParticleEmitter();
  52780. break;
  52781. case "SphereDirectedParticleEmitter":
  52782. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  52783. break;
  52784. case "ConeEmitter":
  52785. emitterType = new BABYLON.ConeParticleEmitter();
  52786. break;
  52787. case "BoxEmitter":
  52788. default:
  52789. emitterType = new BABYLON.BoxParticleEmitter();
  52790. break;
  52791. }
  52792. emitterType.parse(parsedParticleSystem.particleEmitterType);
  52793. particleSystem.particleEmitterType = emitterType;
  52794. }
  52795. return particleSystem;
  52796. };
  52797. return GPUParticleSystem;
  52798. }());
  52799. BABYLON.GPUParticleSystem = GPUParticleSystem;
  52800. })(BABYLON || (BABYLON = {}));
  52801. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  52802. var BABYLON;
  52803. (function (BABYLON) {
  52804. /**
  52805. * Represents one particle of a solid particle system.
  52806. * @see SolidParticleSystem
  52807. */
  52808. var SolidParticle = /** @class */ (function () {
  52809. /**
  52810. * Creates a Solid Particle object.
  52811. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52812. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52813. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52814. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52815. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52816. * @param shapeId (integer) is the model shape identifier in the SPS.
  52817. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52818. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52819. */
  52820. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52821. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52822. /**
  52823. * particle global index
  52824. */
  52825. this.idx = 0;
  52826. /**
  52827. * The color of the particle
  52828. */
  52829. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52830. /**
  52831. * The world space position of the particle.
  52832. */
  52833. this.position = BABYLON.Vector3.Zero();
  52834. /**
  52835. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52836. */
  52837. this.rotation = BABYLON.Vector3.Zero();
  52838. /**
  52839. * The scaling of the particle.
  52840. */
  52841. this.scaling = BABYLON.Vector3.One();
  52842. /**
  52843. * The uvs of the particle.
  52844. */
  52845. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52846. /**
  52847. * The current speed of the particle.
  52848. */
  52849. this.velocity = BABYLON.Vector3.Zero();
  52850. /**
  52851. * The pivot point in the particle local space.
  52852. */
  52853. this.pivot = BABYLON.Vector3.Zero();
  52854. /**
  52855. * Must the particle be translated from its pivot point in its local space ?
  52856. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52857. * Default : false
  52858. */
  52859. this.translateFromPivot = false;
  52860. /**
  52861. * Is the particle active or not ?
  52862. */
  52863. this.alive = true;
  52864. /**
  52865. * Is the particle visible or not ?
  52866. */
  52867. this.isVisible = true;
  52868. /**
  52869. * Index of this particle in the global "positions" array (Internal use)
  52870. */
  52871. this._pos = 0;
  52872. /**
  52873. * Index of this particle in the global "indices" array (Internal use)
  52874. */
  52875. this._ind = 0;
  52876. /**
  52877. * ModelShape id of this particle
  52878. */
  52879. this.shapeId = 0;
  52880. /**
  52881. * Index of the particle in its shape id (Internal use)
  52882. */
  52883. this.idxInShape = 0;
  52884. /**
  52885. * Still set as invisible in order to skip useless computations (Internal use)
  52886. */
  52887. this._stillInvisible = false;
  52888. /**
  52889. * Last computed particle rotation matrix
  52890. */
  52891. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52892. /**
  52893. * Parent particle Id, if any.
  52894. * Default null.
  52895. */
  52896. this.parentId = null;
  52897. /**
  52898. * Internal global position in the SPS.
  52899. */
  52900. this._globalPosition = BABYLON.Vector3.Zero();
  52901. this.idx = particleIndex;
  52902. this._pos = positionIndex;
  52903. this._ind = indiceIndex;
  52904. this._model = model;
  52905. this.shapeId = shapeId;
  52906. this.idxInShape = idxInShape;
  52907. this._sps = sps;
  52908. if (modelBoundingInfo) {
  52909. this._modelBoundingInfo = modelBoundingInfo;
  52910. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52911. }
  52912. }
  52913. Object.defineProperty(SolidParticle.prototype, "scale", {
  52914. /**
  52915. * Legacy support, changed scale to scaling
  52916. */
  52917. get: function () {
  52918. return this.scaling;
  52919. },
  52920. /**
  52921. * Legacy support, changed scale to scaling
  52922. */
  52923. set: function (scale) {
  52924. this.scaling = scale;
  52925. },
  52926. enumerable: true,
  52927. configurable: true
  52928. });
  52929. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52930. /**
  52931. * Legacy support, changed quaternion to rotationQuaternion
  52932. */
  52933. get: function () {
  52934. return this.rotationQuaternion;
  52935. },
  52936. /**
  52937. * Legacy support, changed quaternion to rotationQuaternion
  52938. */
  52939. set: function (q) {
  52940. this.rotationQuaternion = q;
  52941. },
  52942. enumerable: true,
  52943. configurable: true
  52944. });
  52945. /**
  52946. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52947. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52948. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52949. * @returns true if it intersects
  52950. */
  52951. SolidParticle.prototype.intersectsMesh = function (target) {
  52952. if (!this._boundingInfo || !target._boundingInfo) {
  52953. return false;
  52954. }
  52955. if (this._sps._bSphereOnly) {
  52956. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52957. }
  52958. return this._boundingInfo.intersects(target._boundingInfo, false);
  52959. };
  52960. return SolidParticle;
  52961. }());
  52962. BABYLON.SolidParticle = SolidParticle;
  52963. /**
  52964. * Represents the shape of the model used by one particle of a solid particle system.
  52965. * SPS internal tool, don't use it manually.
  52966. * @see SolidParticleSystem
  52967. */
  52968. var ModelShape = /** @class */ (function () {
  52969. /**
  52970. * 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.
  52971. * SPS internal tool, don't use it manually.
  52972. * @ignore
  52973. */
  52974. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52975. /**
  52976. * length of the shape in the model indices array (internal use)
  52977. */
  52978. this._indicesLength = 0;
  52979. this.shapeID = id;
  52980. this._shape = shape;
  52981. this._indicesLength = indicesLength;
  52982. this._shapeUV = shapeUV;
  52983. this._positionFunction = posFunction;
  52984. this._vertexFunction = vtxFunction;
  52985. }
  52986. return ModelShape;
  52987. }());
  52988. BABYLON.ModelShape = ModelShape;
  52989. /**
  52990. * Represents a Depth Sorted Particle in the solid particle system.
  52991. * @see SolidParticleSystem
  52992. */
  52993. var DepthSortedParticle = /** @class */ (function () {
  52994. function DepthSortedParticle() {
  52995. /**
  52996. * Index of the particle in the "indices" array
  52997. */
  52998. this.ind = 0;
  52999. /**
  53000. * Length of the particle shape in the "indices" array
  53001. */
  53002. this.indicesLength = 0;
  53003. /**
  53004. * Squared distance from the particle to the camera
  53005. */
  53006. this.sqDistance = 0.0;
  53007. }
  53008. return DepthSortedParticle;
  53009. }());
  53010. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53011. })(BABYLON || (BABYLON = {}));
  53012. //# sourceMappingURL=babylon.solidParticle.js.map
  53013. var BABYLON;
  53014. (function (BABYLON) {
  53015. /**
  53016. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53017. *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.
  53018. * The SPS is also a particle system. It provides some methods to manage the particles.
  53019. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53020. *
  53021. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53022. */
  53023. var SolidParticleSystem = /** @class */ (function () {
  53024. /**
  53025. * Creates a SPS (Solid Particle System) object.
  53026. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53027. * @param scene (Scene) is the scene in which the SPS is added.
  53028. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53029. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53030. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53031. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53032. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53033. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53034. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53035. */
  53036. function SolidParticleSystem(name, scene, options) {
  53037. /**
  53038. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53039. * Example : var p = SPS.particles[i];
  53040. */
  53041. this.particles = new Array();
  53042. /**
  53043. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53044. */
  53045. this.nbParticles = 0;
  53046. /**
  53047. * If the particles must ever face the camera (default false). Useful for planar particles.
  53048. */
  53049. this.billboard = false;
  53050. /**
  53051. * Recompute normals when adding a shape
  53052. */
  53053. this.recomputeNormals = true;
  53054. /**
  53055. * This a counter ofr your own usage. It's not set by any SPS functions.
  53056. */
  53057. this.counter = 0;
  53058. /**
  53059. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53060. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53061. */
  53062. this.vars = {};
  53063. /**
  53064. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53065. */
  53066. this._bSphereOnly = false;
  53067. /**
  53068. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53069. */
  53070. this._bSphereRadiusFactor = 1.0;
  53071. this._positions = new Array();
  53072. this._indices = new Array();
  53073. this._normals = new Array();
  53074. this._colors = new Array();
  53075. this._uvs = new Array();
  53076. this._index = 0; // indices index
  53077. this._updatable = true;
  53078. this._pickable = false;
  53079. this._isVisibilityBoxLocked = false;
  53080. this._alwaysVisible = false;
  53081. this._depthSort = false;
  53082. this._shapeCounter = 0;
  53083. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53084. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53085. this._computeParticleColor = true;
  53086. this._computeParticleTexture = true;
  53087. this._computeParticleRotation = true;
  53088. this._computeParticleVertex = false;
  53089. this._computeBoundingBox = false;
  53090. this._depthSortParticles = true;
  53091. this._cam_axisZ = BABYLON.Vector3.Zero();
  53092. this._cam_axisY = BABYLON.Vector3.Zero();
  53093. this._cam_axisX = BABYLON.Vector3.Zero();
  53094. this._axisZ = BABYLON.Axis.Z;
  53095. this._camDir = BABYLON.Vector3.Zero();
  53096. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53097. this._rotMatrix = new BABYLON.Matrix();
  53098. this._invertMatrix = new BABYLON.Matrix();
  53099. this._rotated = BABYLON.Vector3.Zero();
  53100. this._quaternion = new BABYLON.Quaternion();
  53101. this._vertex = BABYLON.Vector3.Zero();
  53102. this._normal = BABYLON.Vector3.Zero();
  53103. this._yaw = 0.0;
  53104. this._pitch = 0.0;
  53105. this._roll = 0.0;
  53106. this._halfroll = 0.0;
  53107. this._halfpitch = 0.0;
  53108. this._halfyaw = 0.0;
  53109. this._sinRoll = 0.0;
  53110. this._cosRoll = 0.0;
  53111. this._sinPitch = 0.0;
  53112. this._cosPitch = 0.0;
  53113. this._sinYaw = 0.0;
  53114. this._cosYaw = 0.0;
  53115. this._mustUnrotateFixedNormals = false;
  53116. this._minimum = BABYLON.Vector3.Zero();
  53117. this._maximum = BABYLON.Vector3.Zero();
  53118. this._minBbox = BABYLON.Vector3.Zero();
  53119. this._maxBbox = BABYLON.Vector3.Zero();
  53120. this._particlesIntersect = false;
  53121. this._depthSortFunction = function (p1, p2) {
  53122. return (p2.sqDistance - p1.sqDistance);
  53123. };
  53124. this._needs32Bits = false;
  53125. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53126. this._scaledPivot = BABYLON.Vector3.Zero();
  53127. this._particleHasParent = false;
  53128. this.name = name;
  53129. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53130. this._camera = scene.activeCamera;
  53131. this._pickable = options ? options.isPickable : false;
  53132. this._depthSort = options ? options.enableDepthSort : false;
  53133. this._particlesIntersect = options ? options.particleIntersection : false;
  53134. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53135. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53136. if (options && options.updatable) {
  53137. this._updatable = options.updatable;
  53138. }
  53139. else {
  53140. this._updatable = true;
  53141. }
  53142. if (this._pickable) {
  53143. this.pickedParticles = [];
  53144. }
  53145. if (this._depthSort) {
  53146. this.depthSortedParticles = [];
  53147. }
  53148. }
  53149. /**
  53150. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53151. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53152. * @returns the created mesh
  53153. */
  53154. SolidParticleSystem.prototype.buildMesh = function () {
  53155. if (this.nbParticles === 0) {
  53156. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53157. this.addShape(triangle, 1);
  53158. triangle.dispose();
  53159. }
  53160. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53161. this._positions32 = new Float32Array(this._positions);
  53162. this._uvs32 = new Float32Array(this._uvs);
  53163. this._colors32 = new Float32Array(this._colors);
  53164. if (this.recomputeNormals) {
  53165. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53166. }
  53167. this._normals32 = new Float32Array(this._normals);
  53168. this._fixedNormal32 = new Float32Array(this._normals);
  53169. if (this._mustUnrotateFixedNormals) {
  53170. this._unrotateFixedNormals();
  53171. }
  53172. var vertexData = new BABYLON.VertexData();
  53173. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53174. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53175. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53176. if (this._uvs32) {
  53177. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53178. ;
  53179. }
  53180. if (this._colors32) {
  53181. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53182. }
  53183. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53184. vertexData.applyToMesh(mesh, this._updatable);
  53185. this.mesh = mesh;
  53186. this.mesh.isPickable = this._pickable;
  53187. // free memory
  53188. if (!this._depthSort) {
  53189. this._indices = null;
  53190. }
  53191. this._positions = null;
  53192. this._normals = null;
  53193. this._uvs = null;
  53194. this._colors = null;
  53195. if (!this._updatable) {
  53196. this.particles.length = 0;
  53197. }
  53198. return mesh;
  53199. };
  53200. /**
  53201. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53202. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53203. * Thus the particles generated from `digest()` have their property `position` set yet.
  53204. * @param mesh ( Mesh ) is the mesh to be digested
  53205. * @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
  53206. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53207. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53208. * @returns the current SPS
  53209. */
  53210. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53211. var size = (options && options.facetNb) || 1;
  53212. var number = (options && options.number) || 0;
  53213. var delta = (options && options.delta) || 0;
  53214. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53215. var meshInd = mesh.getIndices();
  53216. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53217. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53218. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53219. var f = 0; // facet counter
  53220. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53221. // compute size from number
  53222. if (number) {
  53223. number = (number > totalFacets) ? totalFacets : number;
  53224. size = Math.round(totalFacets / number);
  53225. delta = 0;
  53226. }
  53227. else {
  53228. size = (size > totalFacets) ? totalFacets : size;
  53229. }
  53230. var facetPos = []; // submesh positions
  53231. var facetInd = []; // submesh indices
  53232. var facetUV = []; // submesh UV
  53233. var facetCol = []; // submesh colors
  53234. var barycenter = BABYLON.Vector3.Zero();
  53235. var sizeO = size;
  53236. while (f < totalFacets) {
  53237. size = sizeO + Math.floor((1 + delta) * Math.random());
  53238. if (f > totalFacets - size) {
  53239. size = totalFacets - f;
  53240. }
  53241. // reset temp arrays
  53242. facetPos.length = 0;
  53243. facetInd.length = 0;
  53244. facetUV.length = 0;
  53245. facetCol.length = 0;
  53246. // iterate over "size" facets
  53247. var fi = 0;
  53248. for (var j = f * 3; j < (f + size) * 3; j++) {
  53249. facetInd.push(fi);
  53250. var i = meshInd[j];
  53251. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53252. if (meshUV) {
  53253. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53254. }
  53255. if (meshCol) {
  53256. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53257. }
  53258. fi++;
  53259. }
  53260. // create a model shape for each single particle
  53261. var idx = this.nbParticles;
  53262. var shape = this._posToShape(facetPos);
  53263. var shapeUV = this._uvsToShapeUV(facetUV);
  53264. // compute the barycenter of the shape
  53265. var v;
  53266. for (v = 0; v < shape.length; v++) {
  53267. barycenter.addInPlace(shape[v]);
  53268. }
  53269. barycenter.scaleInPlace(1 / shape.length);
  53270. // shift the shape from its barycenter to the origin
  53271. for (v = 0; v < shape.length; v++) {
  53272. shape[v].subtractInPlace(barycenter);
  53273. }
  53274. var bInfo;
  53275. if (this._particlesIntersect) {
  53276. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53277. }
  53278. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53279. // add the particle in the SPS
  53280. var currentPos = this._positions.length;
  53281. var currentInd = this._indices.length;
  53282. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53283. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53284. // initialize the particle position
  53285. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53286. this._index += shape.length;
  53287. idx++;
  53288. this.nbParticles++;
  53289. this._shapeCounter++;
  53290. f += size;
  53291. }
  53292. return this;
  53293. };
  53294. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53295. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53296. var index = 0;
  53297. var idx = 0;
  53298. for (var p = 0; p < this.particles.length; p++) {
  53299. this._particle = this.particles[p];
  53300. this._shape = this._particle._model._shape;
  53301. if (this._particle.rotationQuaternion) {
  53302. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53303. }
  53304. else {
  53305. this._yaw = this._particle.rotation.y;
  53306. this._pitch = this._particle.rotation.x;
  53307. this._roll = this._particle.rotation.z;
  53308. this._quaternionRotationYPR();
  53309. }
  53310. this._quaternionToRotationMatrix();
  53311. this._rotMatrix.invertToRef(this._invertMatrix);
  53312. for (var pt = 0; pt < this._shape.length; pt++) {
  53313. idx = index + pt * 3;
  53314. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53315. this._fixedNormal32[idx] = this._normal.x;
  53316. this._fixedNormal32[idx + 1] = this._normal.y;
  53317. this._fixedNormal32[idx + 2] = this._normal.z;
  53318. }
  53319. index = idx + 3;
  53320. }
  53321. };
  53322. //reset copy
  53323. SolidParticleSystem.prototype._resetCopy = function () {
  53324. this._copy.position.x = 0;
  53325. this._copy.position.y = 0;
  53326. this._copy.position.z = 0;
  53327. this._copy.rotation.x = 0;
  53328. this._copy.rotation.y = 0;
  53329. this._copy.rotation.z = 0;
  53330. this._copy.rotationQuaternion = null;
  53331. this._copy.scaling.x = 1.0;
  53332. this._copy.scaling.y = 1.0;
  53333. this._copy.scaling.z = 1.0;
  53334. this._copy.uvs.x = 0;
  53335. this._copy.uvs.y = 0;
  53336. this._copy.uvs.z = 1.0;
  53337. this._copy.uvs.w = 1.0;
  53338. this._copy.color = null;
  53339. this._copy.translateFromPivot = false;
  53340. };
  53341. // _meshBuilder : inserts the shape model in the global SPS mesh
  53342. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53343. var i;
  53344. var u = 0;
  53345. var c = 0;
  53346. var n = 0;
  53347. this._resetCopy();
  53348. if (options && options.positionFunction) {
  53349. options.positionFunction(this._copy, idx, idxInShape);
  53350. this._mustUnrotateFixedNormals = true;
  53351. }
  53352. if (this._copy.rotationQuaternion) {
  53353. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53354. }
  53355. else {
  53356. this._yaw = this._copy.rotation.y;
  53357. this._pitch = this._copy.rotation.x;
  53358. this._roll = this._copy.rotation.z;
  53359. this._quaternionRotationYPR();
  53360. }
  53361. this._quaternionToRotationMatrix();
  53362. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53363. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53364. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53365. if (this._copy.translateFromPivot) {
  53366. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53367. }
  53368. else {
  53369. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53370. }
  53371. for (i = 0; i < shape.length; i++) {
  53372. this._vertex.x = shape[i].x;
  53373. this._vertex.y = shape[i].y;
  53374. this._vertex.z = shape[i].z;
  53375. if (options && options.vertexFunction) {
  53376. options.vertexFunction(this._copy, this._vertex, i);
  53377. }
  53378. this._vertex.x *= this._copy.scaling.x;
  53379. this._vertex.y *= this._copy.scaling.y;
  53380. this._vertex.z *= this._copy.scaling.z;
  53381. this._vertex.x -= this._scaledPivot.x;
  53382. this._vertex.y -= this._scaledPivot.y;
  53383. this._vertex.z -= this._scaledPivot.z;
  53384. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53385. this._rotated.addInPlace(this._pivotBackTranslation);
  53386. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53387. if (meshUV) {
  53388. 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);
  53389. u += 2;
  53390. }
  53391. if (this._copy.color) {
  53392. this._color = this._copy.color;
  53393. }
  53394. else if (meshCol && meshCol[c] !== undefined) {
  53395. this._color.r = meshCol[c];
  53396. this._color.g = meshCol[c + 1];
  53397. this._color.b = meshCol[c + 2];
  53398. this._color.a = meshCol[c + 3];
  53399. }
  53400. else {
  53401. this._color.r = 1.0;
  53402. this._color.g = 1.0;
  53403. this._color.b = 1.0;
  53404. this._color.a = 1.0;
  53405. }
  53406. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53407. c += 4;
  53408. if (!this.recomputeNormals && meshNor) {
  53409. this._normal.x = meshNor[n];
  53410. this._normal.y = meshNor[n + 1];
  53411. this._normal.z = meshNor[n + 2];
  53412. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53413. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53414. n += 3;
  53415. }
  53416. }
  53417. for (i = 0; i < meshInd.length; i++) {
  53418. var current_ind = p + meshInd[i];
  53419. indices.push(current_ind);
  53420. if (current_ind > 65535) {
  53421. this._needs32Bits = true;
  53422. }
  53423. }
  53424. if (this._pickable) {
  53425. var nbfaces = meshInd.length / 3;
  53426. for (i = 0; i < nbfaces; i++) {
  53427. this.pickedParticles.push({ idx: idx, faceId: i });
  53428. }
  53429. }
  53430. if (this._depthSort) {
  53431. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53432. }
  53433. return this._copy;
  53434. };
  53435. // returns a shape array from positions array
  53436. SolidParticleSystem.prototype._posToShape = function (positions) {
  53437. var shape = [];
  53438. for (var i = 0; i < positions.length; i += 3) {
  53439. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53440. }
  53441. return shape;
  53442. };
  53443. // returns a shapeUV array from a Vector4 uvs
  53444. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53445. var shapeUV = [];
  53446. if (uvs) {
  53447. for (var i = 0; i < uvs.length; i++)
  53448. shapeUV.push(uvs[i]);
  53449. }
  53450. return shapeUV;
  53451. };
  53452. // adds a new particle object in the particles array
  53453. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53454. if (bInfo === void 0) { bInfo = null; }
  53455. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53456. this.particles.push(sp);
  53457. return sp;
  53458. };
  53459. /**
  53460. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53461. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53462. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53463. * @param nb (positive integer) the number of particles to be created from this model
  53464. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53465. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53466. * @returns the number of shapes in the system
  53467. */
  53468. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53469. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53470. var meshInd = mesh.getIndices();
  53471. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53472. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53473. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53474. var bbInfo;
  53475. if (this._particlesIntersect) {
  53476. bbInfo = mesh.getBoundingInfo();
  53477. }
  53478. var shape = this._posToShape(meshPos);
  53479. var shapeUV = this._uvsToShapeUV(meshUV);
  53480. var posfunc = options ? options.positionFunction : null;
  53481. var vtxfunc = options ? options.vertexFunction : null;
  53482. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53483. // particles
  53484. var sp;
  53485. var currentCopy;
  53486. var idx = this.nbParticles;
  53487. for (var i = 0; i < nb; i++) {
  53488. var currentPos = this._positions.length;
  53489. var currentInd = this._indices.length;
  53490. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53491. if (this._updatable) {
  53492. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53493. sp.position.copyFrom(currentCopy.position);
  53494. sp.rotation.copyFrom(currentCopy.rotation);
  53495. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53496. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53497. }
  53498. if (currentCopy.color && sp.color) {
  53499. sp.color.copyFrom(currentCopy.color);
  53500. }
  53501. sp.scaling.copyFrom(currentCopy.scaling);
  53502. sp.uvs.copyFrom(currentCopy.uvs);
  53503. }
  53504. this._index += shape.length;
  53505. idx++;
  53506. }
  53507. this.nbParticles += nb;
  53508. this._shapeCounter++;
  53509. return this._shapeCounter - 1;
  53510. };
  53511. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53512. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53513. this._resetCopy();
  53514. if (particle._model._positionFunction) {
  53515. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53516. }
  53517. if (this._copy.rotationQuaternion) {
  53518. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53519. }
  53520. else {
  53521. this._yaw = this._copy.rotation.y;
  53522. this._pitch = this._copy.rotation.x;
  53523. this._roll = this._copy.rotation.z;
  53524. this._quaternionRotationYPR();
  53525. }
  53526. this._quaternionToRotationMatrix();
  53527. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53528. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53529. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53530. if (this._copy.translateFromPivot) {
  53531. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53532. }
  53533. else {
  53534. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53535. }
  53536. this._shape = particle._model._shape;
  53537. for (var pt = 0; pt < this._shape.length; pt++) {
  53538. this._vertex.x = this._shape[pt].x;
  53539. this._vertex.y = this._shape[pt].y;
  53540. this._vertex.z = this._shape[pt].z;
  53541. if (particle._model._vertexFunction) {
  53542. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53543. }
  53544. this._vertex.x *= this._copy.scaling.x;
  53545. this._vertex.y *= this._copy.scaling.y;
  53546. this._vertex.z *= this._copy.scaling.z;
  53547. this._vertex.x -= this._scaledPivot.x;
  53548. this._vertex.y -= this._scaledPivot.y;
  53549. this._vertex.z -= this._scaledPivot.z;
  53550. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53551. this._rotated.addInPlace(this._pivotBackTranslation);
  53552. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53553. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53554. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53555. }
  53556. particle.position.x = 0.0;
  53557. particle.position.y = 0.0;
  53558. particle.position.z = 0.0;
  53559. particle.rotation.x = 0.0;
  53560. particle.rotation.y = 0.0;
  53561. particle.rotation.z = 0.0;
  53562. particle.rotationQuaternion = null;
  53563. particle.scaling.x = 1.0;
  53564. particle.scaling.y = 1.0;
  53565. particle.scaling.z = 1.0;
  53566. particle.uvs.x = 0.0;
  53567. particle.uvs.y = 0.0;
  53568. particle.uvs.z = 1.0;
  53569. particle.uvs.w = 1.0;
  53570. particle.pivot.x = 0.0;
  53571. particle.pivot.y = 0.0;
  53572. particle.pivot.z = 0.0;
  53573. particle.translateFromPivot = false;
  53574. particle.parentId = null;
  53575. };
  53576. /**
  53577. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53578. * @returns the SPS.
  53579. */
  53580. SolidParticleSystem.prototype.rebuildMesh = function () {
  53581. for (var p = 0; p < this.particles.length; p++) {
  53582. this._rebuildParticle(this.particles[p]);
  53583. }
  53584. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53585. return this;
  53586. };
  53587. /**
  53588. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53589. * This method calls `updateParticle()` for each particle of the SPS.
  53590. * For an animated SPS, it is usually called within the render loop.
  53591. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53592. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53593. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53594. * @returns the SPS.
  53595. */
  53596. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53597. if (start === void 0) { start = 0; }
  53598. if (end === void 0) { end = this.nbParticles - 1; }
  53599. if (update === void 0) { update = true; }
  53600. if (!this._updatable) {
  53601. return this;
  53602. }
  53603. // custom beforeUpdate
  53604. this.beforeUpdateParticles(start, end, update);
  53605. this._cam_axisX.x = 1.0;
  53606. this._cam_axisX.y = 0.0;
  53607. this._cam_axisX.z = 0.0;
  53608. this._cam_axisY.x = 0.0;
  53609. this._cam_axisY.y = 1.0;
  53610. this._cam_axisY.z = 0.0;
  53611. this._cam_axisZ.x = 0.0;
  53612. this._cam_axisZ.y = 0.0;
  53613. this._cam_axisZ.z = 1.0;
  53614. // cases when the World Matrix is to be computed first
  53615. if (this.billboard || this._depthSort) {
  53616. this.mesh.computeWorldMatrix(true);
  53617. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53618. }
  53619. // if the particles will always face the camera
  53620. if (this.billboard) {
  53621. // compute the camera position and un-rotate it by the current mesh rotation
  53622. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53623. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53624. this._cam_axisZ.normalize();
  53625. // same for camera up vector extracted from the cam view matrix
  53626. var view = this._camera.getViewMatrix(true);
  53627. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53628. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53629. this._cam_axisY.normalize();
  53630. this._cam_axisX.normalize();
  53631. }
  53632. // if depthSort, compute the camera global position in the mesh local system
  53633. if (this._depthSort) {
  53634. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53635. }
  53636. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53637. var idx = 0; // current position index in the global array positions32
  53638. var index = 0; // position start index in the global array positions32 of the current particle
  53639. var colidx = 0; // current color index in the global array colors32
  53640. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53641. var uvidx = 0; // current uv index in the global array uvs32
  53642. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53643. var pt = 0; // current index in the particle model shape
  53644. if (this.mesh.isFacetDataEnabled) {
  53645. this._computeBoundingBox = true;
  53646. }
  53647. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53648. if (this._computeBoundingBox) {
  53649. if (start == 0 && end == this.nbParticles - 1) {
  53650. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53651. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53652. }
  53653. else {
  53654. if (this.mesh._boundingInfo) {
  53655. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53656. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53657. }
  53658. }
  53659. }
  53660. // particle loop
  53661. index = this.particles[start]._pos;
  53662. var vpos = (index / 3) | 0;
  53663. colorIndex = vpos * 4;
  53664. uvIndex = vpos * 2;
  53665. for (var p = start; p <= end; p++) {
  53666. this._particle = this.particles[p];
  53667. this._shape = this._particle._model._shape;
  53668. this._shapeUV = this._particle._model._shapeUV;
  53669. // call to custom user function to update the particle properties
  53670. this.updateParticle(this._particle);
  53671. // camera-particle distance for depth sorting
  53672. if (this._depthSort && this._depthSortParticles) {
  53673. var dsp = this.depthSortedParticles[p];
  53674. dsp.ind = this._particle._ind;
  53675. dsp.indicesLength = this._particle._model._indicesLength;
  53676. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53677. }
  53678. // skip the computations for inactive or already invisible particles
  53679. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53680. // increment indexes for the next particle
  53681. pt = this._shape.length;
  53682. index += pt * 3;
  53683. colorIndex += pt * 4;
  53684. uvIndex += pt * 2;
  53685. continue;
  53686. }
  53687. if (this._particle.isVisible) {
  53688. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53689. this._particleHasParent = (this._particle.parentId !== null);
  53690. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53691. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53692. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53693. // particle rotation matrix
  53694. if (this.billboard) {
  53695. this._particle.rotation.x = 0.0;
  53696. this._particle.rotation.y = 0.0;
  53697. }
  53698. if (this._computeParticleRotation || this.billboard) {
  53699. if (this._particle.rotationQuaternion) {
  53700. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53701. }
  53702. else {
  53703. this._yaw = this._particle.rotation.y;
  53704. this._pitch = this._particle.rotation.x;
  53705. this._roll = this._particle.rotation.z;
  53706. this._quaternionRotationYPR();
  53707. }
  53708. this._quaternionToRotationMatrix();
  53709. }
  53710. if (this._particleHasParent) {
  53711. this._parent = this.particles[this._particle.parentId];
  53712. 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];
  53713. 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];
  53714. 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];
  53715. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53716. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53717. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53718. if (this._computeParticleRotation || this.billboard) {
  53719. 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];
  53720. 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];
  53721. 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];
  53722. 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];
  53723. 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];
  53724. 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];
  53725. 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];
  53726. 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];
  53727. 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];
  53728. }
  53729. }
  53730. else {
  53731. this._particle._globalPosition.x = this._particle.position.x;
  53732. this._particle._globalPosition.y = this._particle.position.y;
  53733. this._particle._globalPosition.z = this._particle.position.z;
  53734. if (this._computeParticleRotation || this.billboard) {
  53735. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53736. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53737. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53738. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53739. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53740. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53741. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53742. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53743. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53744. }
  53745. }
  53746. if (this._particle.translateFromPivot) {
  53747. this._pivotBackTranslation.x = 0.0;
  53748. this._pivotBackTranslation.y = 0.0;
  53749. this._pivotBackTranslation.z = 0.0;
  53750. }
  53751. else {
  53752. this._pivotBackTranslation.x = this._scaledPivot.x;
  53753. this._pivotBackTranslation.y = this._scaledPivot.y;
  53754. this._pivotBackTranslation.z = this._scaledPivot.z;
  53755. }
  53756. // particle vertex loop
  53757. for (pt = 0; pt < this._shape.length; pt++) {
  53758. idx = index + pt * 3;
  53759. colidx = colorIndex + pt * 4;
  53760. uvidx = uvIndex + pt * 2;
  53761. this._vertex.x = this._shape[pt].x;
  53762. this._vertex.y = this._shape[pt].y;
  53763. this._vertex.z = this._shape[pt].z;
  53764. if (this._computeParticleVertex) {
  53765. this.updateParticleVertex(this._particle, this._vertex, pt);
  53766. }
  53767. // positions
  53768. this._vertex.x *= this._particle.scaling.x;
  53769. this._vertex.y *= this._particle.scaling.y;
  53770. this._vertex.z *= this._particle.scaling.z;
  53771. this._vertex.x -= this._scaledPivot.x;
  53772. this._vertex.y -= this._scaledPivot.y;
  53773. this._vertex.z -= this._scaledPivot.z;
  53774. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53775. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53776. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53777. this._rotated.x += this._pivotBackTranslation.x;
  53778. this._rotated.y += this._pivotBackTranslation.y;
  53779. this._rotated.z += this._pivotBackTranslation.z;
  53780. 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;
  53781. 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;
  53782. 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;
  53783. if (this._computeBoundingBox) {
  53784. if (this._positions32[idx] < this._minimum.x) {
  53785. this._minimum.x = this._positions32[idx];
  53786. }
  53787. if (this._positions32[idx] > this._maximum.x) {
  53788. this._maximum.x = this._positions32[idx];
  53789. }
  53790. if (this._positions32[idx + 1] < this._minimum.y) {
  53791. this._minimum.y = this._positions32[idx + 1];
  53792. }
  53793. if (this._positions32[idx + 1] > this._maximum.y) {
  53794. this._maximum.y = this._positions32[idx + 1];
  53795. }
  53796. if (this._positions32[idx + 2] < this._minimum.z) {
  53797. this._minimum.z = this._positions32[idx + 2];
  53798. }
  53799. if (this._positions32[idx + 2] > this._maximum.z) {
  53800. this._maximum.z = this._positions32[idx + 2];
  53801. }
  53802. }
  53803. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53804. if (!this._computeParticleVertex) {
  53805. this._normal.x = this._fixedNormal32[idx];
  53806. this._normal.y = this._fixedNormal32[idx + 1];
  53807. this._normal.z = this._fixedNormal32[idx + 2];
  53808. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53809. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53810. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53811. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53812. 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;
  53813. 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;
  53814. }
  53815. if (this._computeParticleColor && this._particle.color) {
  53816. this._colors32[colidx] = this._particle.color.r;
  53817. this._colors32[colidx + 1] = this._particle.color.g;
  53818. this._colors32[colidx + 2] = this._particle.color.b;
  53819. this._colors32[colidx + 3] = this._particle.color.a;
  53820. }
  53821. if (this._computeParticleTexture) {
  53822. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53823. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53824. }
  53825. }
  53826. }
  53827. else {
  53828. this._particle._stillInvisible = true; // mark the particle as invisible
  53829. for (pt = 0; pt < this._shape.length; pt++) {
  53830. idx = index + pt * 3;
  53831. colidx = colorIndex + pt * 4;
  53832. uvidx = uvIndex + pt * 2;
  53833. this._positions32[idx] = 0.0;
  53834. this._positions32[idx + 1] = 0.0;
  53835. this._positions32[idx + 2] = 0.0;
  53836. this._normals32[idx] = 0.0;
  53837. this._normals32[idx + 1] = 0.0;
  53838. this._normals32[idx + 2] = 0.0;
  53839. if (this._computeParticleColor && this._particle.color) {
  53840. this._colors32[colidx] = this._particle.color.r;
  53841. this._colors32[colidx + 1] = this._particle.color.g;
  53842. this._colors32[colidx + 2] = this._particle.color.b;
  53843. this._colors32[colidx + 3] = this._particle.color.a;
  53844. }
  53845. if (this._computeParticleTexture) {
  53846. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53847. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53848. }
  53849. }
  53850. }
  53851. // if the particle intersections must be computed : update the bbInfo
  53852. if (this._particlesIntersect) {
  53853. var bInfo = this._particle._boundingInfo;
  53854. var bBox = bInfo.boundingBox;
  53855. var bSphere = bInfo.boundingSphere;
  53856. if (!this._bSphereOnly) {
  53857. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53858. for (var b = 0; b < bBox.vectors.length; b++) {
  53859. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53860. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53861. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53862. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53863. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53864. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53865. 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;
  53866. 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;
  53867. 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;
  53868. }
  53869. bBox._update(this.mesh._worldMatrix);
  53870. }
  53871. // place and scale the particle bouding sphere in the SPS local system, then update it
  53872. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53873. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53874. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53875. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53876. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53877. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53878. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53879. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53880. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53881. 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));
  53882. bSphere._update(this.mesh._worldMatrix);
  53883. }
  53884. // increment indexes for the next particle
  53885. index = idx + 3;
  53886. colorIndex = colidx + 4;
  53887. uvIndex = uvidx + 2;
  53888. }
  53889. // if the VBO must be updated
  53890. if (update) {
  53891. if (this._computeParticleColor) {
  53892. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53893. }
  53894. if (this._computeParticleTexture) {
  53895. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53896. }
  53897. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53898. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53899. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53900. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53901. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53902. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53903. for (var i = 0; i < this._normals32.length; i++) {
  53904. this._fixedNormal32[i] = this._normals32[i];
  53905. }
  53906. }
  53907. if (!this.mesh.areNormalsFrozen) {
  53908. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53909. }
  53910. }
  53911. if (this._depthSort && this._depthSortParticles) {
  53912. this.depthSortedParticles.sort(this._depthSortFunction);
  53913. var dspl = this.depthSortedParticles.length;
  53914. var sorted = 0;
  53915. var lind = 0;
  53916. var sind = 0;
  53917. var sid = 0;
  53918. for (sorted = 0; sorted < dspl; sorted++) {
  53919. lind = this.depthSortedParticles[sorted].indicesLength;
  53920. sind = this.depthSortedParticles[sorted].ind;
  53921. for (var i = 0; i < lind; i++) {
  53922. this._indices32[sid] = this._indices[sind + i];
  53923. sid++;
  53924. }
  53925. }
  53926. this.mesh.updateIndices(this._indices32);
  53927. }
  53928. }
  53929. if (this._computeBoundingBox) {
  53930. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53931. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53932. }
  53933. this.afterUpdateParticles(start, end, update);
  53934. return this;
  53935. };
  53936. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53937. this._halfroll = this._roll * 0.5;
  53938. this._halfpitch = this._pitch * 0.5;
  53939. this._halfyaw = this._yaw * 0.5;
  53940. this._sinRoll = Math.sin(this._halfroll);
  53941. this._cosRoll = Math.cos(this._halfroll);
  53942. this._sinPitch = Math.sin(this._halfpitch);
  53943. this._cosPitch = Math.cos(this._halfpitch);
  53944. this._sinYaw = Math.sin(this._halfyaw);
  53945. this._cosYaw = Math.cos(this._halfyaw);
  53946. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53947. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53948. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53949. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53950. };
  53951. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53952. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53953. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53954. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53955. this._rotMatrix.m[3] = 0;
  53956. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53957. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53958. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53959. this._rotMatrix.m[7] = 0;
  53960. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53961. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53962. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53963. this._rotMatrix.m[11] = 0;
  53964. this._rotMatrix.m[12] = 0;
  53965. this._rotMatrix.m[13] = 0;
  53966. this._rotMatrix.m[14] = 0;
  53967. this._rotMatrix.m[15] = 1.0;
  53968. };
  53969. /**
  53970. * Disposes the SPS.
  53971. */
  53972. SolidParticleSystem.prototype.dispose = function () {
  53973. this.mesh.dispose();
  53974. this.vars = null;
  53975. // drop references to internal big arrays for the GC
  53976. this._positions = null;
  53977. this._indices = null;
  53978. this._normals = null;
  53979. this._uvs = null;
  53980. this._colors = null;
  53981. this._indices32 = null;
  53982. this._positions32 = null;
  53983. this._normals32 = null;
  53984. this._fixedNormal32 = null;
  53985. this._uvs32 = null;
  53986. this._colors32 = null;
  53987. this.pickedParticles = null;
  53988. };
  53989. /**
  53990. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53991. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53992. * @returns the SPS.
  53993. */
  53994. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53995. if (!this._isVisibilityBoxLocked) {
  53996. this.mesh.refreshBoundingInfo();
  53997. }
  53998. return this;
  53999. };
  54000. /**
  54001. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54002. * @param size the size (float) of the visibility box
  54003. * note : this doesn't lock the SPS mesh bounding box.
  54004. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54005. */
  54006. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54007. var vis = size / 2;
  54008. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54009. };
  54010. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54011. /**
  54012. * Gets whether the SPS as always visible or not
  54013. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54014. */
  54015. get: function () {
  54016. return this._alwaysVisible;
  54017. },
  54018. /**
  54019. * Sets the SPS as always visible or not
  54020. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54021. */
  54022. set: function (val) {
  54023. this._alwaysVisible = val;
  54024. this.mesh.alwaysSelectAsActiveMesh = val;
  54025. },
  54026. enumerable: true,
  54027. configurable: true
  54028. });
  54029. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54030. /**
  54031. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54032. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54033. */
  54034. get: function () {
  54035. return this._isVisibilityBoxLocked;
  54036. },
  54037. /**
  54038. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54039. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54040. */
  54041. set: function (val) {
  54042. this._isVisibilityBoxLocked = val;
  54043. var boundingInfo = this.mesh.getBoundingInfo();
  54044. boundingInfo.isLocked = val;
  54045. },
  54046. enumerable: true,
  54047. configurable: true
  54048. });
  54049. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54050. /**
  54051. * Gets if `setParticles()` computes the particle rotations or not.
  54052. * Default value : true. The SPS is faster when it's set to false.
  54053. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54054. */
  54055. get: function () {
  54056. return this._computeParticleRotation;
  54057. },
  54058. /**
  54059. * Tells to `setParticles()` to compute the particle rotations or not.
  54060. * Default value : true. The SPS is faster when it's set to false.
  54061. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54062. */
  54063. set: function (val) {
  54064. this._computeParticleRotation = val;
  54065. },
  54066. enumerable: true,
  54067. configurable: true
  54068. });
  54069. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54070. /**
  54071. * Gets if `setParticles()` computes the particle colors or not.
  54072. * Default value : true. The SPS is faster when it's set to false.
  54073. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54074. */
  54075. get: function () {
  54076. return this._computeParticleColor;
  54077. },
  54078. /**
  54079. * Tells to `setParticles()` to compute the particle colors or not.
  54080. * Default value : true. The SPS is faster when it's set to false.
  54081. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54082. */
  54083. set: function (val) {
  54084. this._computeParticleColor = val;
  54085. },
  54086. enumerable: true,
  54087. configurable: true
  54088. });
  54089. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54090. /**
  54091. * Gets if `setParticles()` computes the particle textures or not.
  54092. * Default value : true. The SPS is faster when it's set to false.
  54093. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54094. */
  54095. get: function () {
  54096. return this._computeParticleTexture;
  54097. },
  54098. set: function (val) {
  54099. this._computeParticleTexture = val;
  54100. },
  54101. enumerable: true,
  54102. configurable: true
  54103. });
  54104. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54105. /**
  54106. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54107. * Default value : false. The SPS is faster when it's set to false.
  54108. * Note : the particle custom vertex positions aren't stored values.
  54109. */
  54110. get: function () {
  54111. return this._computeParticleVertex;
  54112. },
  54113. /**
  54114. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54115. * Default value : false. The SPS is faster when it's set to false.
  54116. * Note : the particle custom vertex positions aren't stored values.
  54117. */
  54118. set: function (val) {
  54119. this._computeParticleVertex = val;
  54120. },
  54121. enumerable: true,
  54122. configurable: true
  54123. });
  54124. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54125. /**
  54126. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54127. */
  54128. get: function () {
  54129. return this._computeBoundingBox;
  54130. },
  54131. /**
  54132. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54133. */
  54134. set: function (val) {
  54135. this._computeBoundingBox = val;
  54136. },
  54137. enumerable: true,
  54138. configurable: true
  54139. });
  54140. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54141. /**
  54142. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54143. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54144. * Default : `true`
  54145. */
  54146. get: function () {
  54147. return this._depthSortParticles;
  54148. },
  54149. /**
  54150. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54151. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54152. * Default : `true`
  54153. */
  54154. set: function (val) {
  54155. this._depthSortParticles = val;
  54156. },
  54157. enumerable: true,
  54158. configurable: true
  54159. });
  54160. // =======================================================================
  54161. // Particle behavior logic
  54162. // these following methods may be overwritten by the user to fit his needs
  54163. /**
  54164. * This function does nothing. It may be overwritten to set all the particle first values.
  54165. * The SPS doesn't call this function, you may have to call it by your own.
  54166. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54167. */
  54168. SolidParticleSystem.prototype.initParticles = function () {
  54169. };
  54170. /**
  54171. * This function does nothing. It may be overwritten to recycle a particle.
  54172. * The SPS doesn't call this function, you may have to call it by your own.
  54173. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54174. * @param particle The particle to recycle
  54175. * @returns the recycled particle
  54176. */
  54177. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54178. return particle;
  54179. };
  54180. /**
  54181. * Updates a particle : this function should be overwritten by the user.
  54182. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54183. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54184. * @example : just set a particle position or velocity and recycle conditions
  54185. * @param particle The particle to update
  54186. * @returns the updated particle
  54187. */
  54188. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54189. return particle;
  54190. };
  54191. /**
  54192. * Updates a vertex of a particle : it can be overwritten by the user.
  54193. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54194. * @param particle the current particle
  54195. * @param vertex the current index of the current particle
  54196. * @param pt the index of the current vertex in the particle shape
  54197. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54198. * @example : just set a vertex particle position
  54199. * @returns the updated vertex
  54200. */
  54201. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54202. return vertex;
  54203. };
  54204. /**
  54205. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54206. * This does nothing and may be overwritten by the user.
  54207. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54208. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54209. * @param update the boolean update value actually passed to setParticles()
  54210. */
  54211. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54212. };
  54213. /**
  54214. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54215. * This will be passed three parameters.
  54216. * This does nothing and may be overwritten by the user.
  54217. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54218. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54219. * @param update the boolean update value actually passed to setParticles()
  54220. */
  54221. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54222. };
  54223. return SolidParticleSystem;
  54224. }());
  54225. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54226. })(BABYLON || (BABYLON = {}));
  54227. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54228. var BABYLON;
  54229. (function (BABYLON) {
  54230. var ShaderMaterial = /** @class */ (function (_super) {
  54231. __extends(ShaderMaterial, _super);
  54232. function ShaderMaterial(name, scene, shaderPath, options) {
  54233. var _this = _super.call(this, name, scene) || this;
  54234. _this._textures = {};
  54235. _this._textureArrays = {};
  54236. _this._floats = {};
  54237. _this._ints = {};
  54238. _this._floatsArrays = {};
  54239. _this._colors3 = {};
  54240. _this._colors3Arrays = {};
  54241. _this._colors4 = {};
  54242. _this._vectors2 = {};
  54243. _this._vectors3 = {};
  54244. _this._vectors4 = {};
  54245. _this._matrices = {};
  54246. _this._matrices3x3 = {};
  54247. _this._matrices2x2 = {};
  54248. _this._vectors2Arrays = {};
  54249. _this._vectors3Arrays = {};
  54250. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54251. _this._shaderPath = shaderPath;
  54252. options.needAlphaBlending = options.needAlphaBlending || false;
  54253. options.needAlphaTesting = options.needAlphaTesting || false;
  54254. options.attributes = options.attributes || ["position", "normal", "uv"];
  54255. options.uniforms = options.uniforms || ["worldViewProjection"];
  54256. options.uniformBuffers = options.uniformBuffers || [];
  54257. options.samplers = options.samplers || [];
  54258. options.defines = options.defines || [];
  54259. _this._options = options;
  54260. return _this;
  54261. }
  54262. ShaderMaterial.prototype.getClassName = function () {
  54263. return "ShaderMaterial";
  54264. };
  54265. ShaderMaterial.prototype.needAlphaBlending = function () {
  54266. return this._options.needAlphaBlending;
  54267. };
  54268. ShaderMaterial.prototype.needAlphaTesting = function () {
  54269. return this._options.needAlphaTesting;
  54270. };
  54271. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54272. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54273. this._options.uniforms.push(uniformName);
  54274. }
  54275. };
  54276. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54277. if (this._options.samplers.indexOf(name) === -1) {
  54278. this._options.samplers.push(name);
  54279. }
  54280. this._textures[name] = texture;
  54281. return this;
  54282. };
  54283. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54284. if (this._options.samplers.indexOf(name) === -1) {
  54285. this._options.samplers.push(name);
  54286. }
  54287. this._checkUniform(name);
  54288. this._textureArrays[name] = textures;
  54289. return this;
  54290. };
  54291. ShaderMaterial.prototype.setFloat = function (name, value) {
  54292. this._checkUniform(name);
  54293. this._floats[name] = value;
  54294. return this;
  54295. };
  54296. ShaderMaterial.prototype.setInt = function (name, value) {
  54297. this._checkUniform(name);
  54298. this._ints[name] = value;
  54299. return this;
  54300. };
  54301. ShaderMaterial.prototype.setFloats = function (name, value) {
  54302. this._checkUniform(name);
  54303. this._floatsArrays[name] = value;
  54304. return this;
  54305. };
  54306. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54307. this._checkUniform(name);
  54308. this._colors3[name] = value;
  54309. return this;
  54310. };
  54311. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54312. this._checkUniform(name);
  54313. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54314. color.toArray(arr, arr.length);
  54315. return arr;
  54316. }, []);
  54317. return this;
  54318. };
  54319. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54320. this._checkUniform(name);
  54321. this._colors4[name] = value;
  54322. return this;
  54323. };
  54324. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54325. this._checkUniform(name);
  54326. this._vectors2[name] = value;
  54327. return this;
  54328. };
  54329. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54330. this._checkUniform(name);
  54331. this._vectors3[name] = value;
  54332. return this;
  54333. };
  54334. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54335. this._checkUniform(name);
  54336. this._vectors4[name] = value;
  54337. return this;
  54338. };
  54339. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54340. this._checkUniform(name);
  54341. this._matrices[name] = value;
  54342. return this;
  54343. };
  54344. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54345. this._checkUniform(name);
  54346. this._matrices3x3[name] = value;
  54347. return this;
  54348. };
  54349. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54350. this._checkUniform(name);
  54351. this._matrices2x2[name] = value;
  54352. return this;
  54353. };
  54354. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54355. this._checkUniform(name);
  54356. this._vectors2Arrays[name] = value;
  54357. return this;
  54358. };
  54359. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54360. this._checkUniform(name);
  54361. this._vectors3Arrays[name] = value;
  54362. return this;
  54363. };
  54364. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54365. if (!mesh) {
  54366. return true;
  54367. }
  54368. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54369. return false;
  54370. }
  54371. return false;
  54372. };
  54373. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54374. var scene = this.getScene();
  54375. var engine = scene.getEngine();
  54376. if (!this.checkReadyOnEveryCall) {
  54377. if (this._renderId === scene.getRenderId()) {
  54378. if (this._checkCache(scene, mesh, useInstances)) {
  54379. return true;
  54380. }
  54381. }
  54382. }
  54383. // Instances
  54384. var defines = [];
  54385. var attribs = [];
  54386. var fallbacks = new BABYLON.EffectFallbacks();
  54387. if (useInstances) {
  54388. defines.push("#define INSTANCES");
  54389. }
  54390. for (var index = 0; index < this._options.defines.length; index++) {
  54391. defines.push(this._options.defines[index]);
  54392. }
  54393. for (var index = 0; index < this._options.attributes.length; index++) {
  54394. attribs.push(this._options.attributes[index]);
  54395. }
  54396. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54397. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54398. defines.push("#define VERTEXCOLOR");
  54399. }
  54400. // Bones
  54401. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54402. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54403. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54404. if (mesh.numBoneInfluencers > 4) {
  54405. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54406. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54407. }
  54408. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54409. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54410. fallbacks.addCPUSkinningFallback(0, mesh);
  54411. if (this._options.uniforms.indexOf("mBones") === -1) {
  54412. this._options.uniforms.push("mBones");
  54413. }
  54414. }
  54415. else {
  54416. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54417. }
  54418. // Textures
  54419. for (var name in this._textures) {
  54420. if (!this._textures[name].isReady()) {
  54421. return false;
  54422. }
  54423. }
  54424. // Alpha test
  54425. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54426. defines.push("#define ALPHATEST");
  54427. }
  54428. var previousEffect = this._effect;
  54429. var join = defines.join("\n");
  54430. this._effect = engine.createEffect(this._shaderPath, {
  54431. attributes: attribs,
  54432. uniformsNames: this._options.uniforms,
  54433. uniformBuffersNames: this._options.uniformBuffers,
  54434. samplers: this._options.samplers,
  54435. defines: join,
  54436. fallbacks: fallbacks,
  54437. onCompiled: this.onCompiled,
  54438. onError: this.onError
  54439. }, engine);
  54440. if (!this._effect.isReady()) {
  54441. return false;
  54442. }
  54443. if (previousEffect !== this._effect) {
  54444. scene.resetCachedMaterial();
  54445. }
  54446. this._renderId = scene.getRenderId();
  54447. return true;
  54448. };
  54449. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54450. var scene = this.getScene();
  54451. if (!this._effect) {
  54452. return;
  54453. }
  54454. if (this._options.uniforms.indexOf("world") !== -1) {
  54455. this._effect.setMatrix("world", world);
  54456. }
  54457. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54458. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54459. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54460. }
  54461. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54462. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54463. }
  54464. };
  54465. ShaderMaterial.prototype.bind = function (world, mesh) {
  54466. // Std values
  54467. this.bindOnlyWorldMatrix(world);
  54468. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54469. if (this._options.uniforms.indexOf("view") !== -1) {
  54470. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54471. }
  54472. if (this._options.uniforms.indexOf("projection") !== -1) {
  54473. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54474. }
  54475. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54476. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54477. }
  54478. // Bones
  54479. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54480. var name;
  54481. // Texture
  54482. for (name in this._textures) {
  54483. this._effect.setTexture(name, this._textures[name]);
  54484. }
  54485. // Texture arrays
  54486. for (name in this._textureArrays) {
  54487. this._effect.setTextureArray(name, this._textureArrays[name]);
  54488. }
  54489. // Int
  54490. for (name in this._ints) {
  54491. this._effect.setInt(name, this._ints[name]);
  54492. }
  54493. // Float
  54494. for (name in this._floats) {
  54495. this._effect.setFloat(name, this._floats[name]);
  54496. }
  54497. // Floats
  54498. for (name in this._floatsArrays) {
  54499. this._effect.setArray(name, this._floatsArrays[name]);
  54500. }
  54501. // Color3
  54502. for (name in this._colors3) {
  54503. this._effect.setColor3(name, this._colors3[name]);
  54504. }
  54505. for (name in this._colors3Arrays) {
  54506. this._effect.setArray3(name, this._colors3Arrays[name]);
  54507. }
  54508. // Color4
  54509. for (name in this._colors4) {
  54510. var color = this._colors4[name];
  54511. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54512. }
  54513. // Vector2
  54514. for (name in this._vectors2) {
  54515. this._effect.setVector2(name, this._vectors2[name]);
  54516. }
  54517. // Vector3
  54518. for (name in this._vectors3) {
  54519. this._effect.setVector3(name, this._vectors3[name]);
  54520. }
  54521. // Vector4
  54522. for (name in this._vectors4) {
  54523. this._effect.setVector4(name, this._vectors4[name]);
  54524. }
  54525. // Matrix
  54526. for (name in this._matrices) {
  54527. this._effect.setMatrix(name, this._matrices[name]);
  54528. }
  54529. // Matrix 3x3
  54530. for (name in this._matrices3x3) {
  54531. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54532. }
  54533. // Matrix 2x2
  54534. for (name in this._matrices2x2) {
  54535. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54536. }
  54537. // Vector2Array
  54538. for (name in this._vectors2Arrays) {
  54539. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54540. }
  54541. // Vector3Array
  54542. for (name in this._vectors3Arrays) {
  54543. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54544. }
  54545. }
  54546. this._afterBind(mesh);
  54547. };
  54548. ShaderMaterial.prototype.getActiveTextures = function () {
  54549. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54550. for (var name in this._textures) {
  54551. activeTextures.push(this._textures[name]);
  54552. }
  54553. for (var name in this._textureArrays) {
  54554. var array = this._textureArrays[name];
  54555. for (var index = 0; index < array.length; index++) {
  54556. activeTextures.push(array[index]);
  54557. }
  54558. }
  54559. return activeTextures;
  54560. };
  54561. ShaderMaterial.prototype.hasTexture = function (texture) {
  54562. if (_super.prototype.hasTexture.call(this, texture)) {
  54563. return true;
  54564. }
  54565. for (var name in this._textures) {
  54566. if (this._textures[name] === texture) {
  54567. return true;
  54568. }
  54569. }
  54570. for (var name in this._textureArrays) {
  54571. var array = this._textureArrays[name];
  54572. for (var index = 0; index < array.length; index++) {
  54573. if (array[index] === texture) {
  54574. return true;
  54575. }
  54576. }
  54577. }
  54578. return false;
  54579. };
  54580. ShaderMaterial.prototype.clone = function (name) {
  54581. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54582. return newShaderMaterial;
  54583. };
  54584. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54585. if (forceDisposeTextures) {
  54586. var name;
  54587. for (name in this._textures) {
  54588. this._textures[name].dispose();
  54589. }
  54590. for (name in this._textureArrays) {
  54591. var array = this._textureArrays[name];
  54592. for (var index = 0; index < array.length; index++) {
  54593. array[index].dispose();
  54594. }
  54595. }
  54596. }
  54597. this._textures = {};
  54598. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54599. };
  54600. ShaderMaterial.prototype.serialize = function () {
  54601. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54602. serializationObject.customType = "BABYLON.ShaderMaterial";
  54603. serializationObject.options = this._options;
  54604. serializationObject.shaderPath = this._shaderPath;
  54605. var name;
  54606. // Texture
  54607. serializationObject.textures = {};
  54608. for (name in this._textures) {
  54609. serializationObject.textures[name] = this._textures[name].serialize();
  54610. }
  54611. // Texture arrays
  54612. serializationObject.textureArrays = {};
  54613. for (name in this._textureArrays) {
  54614. serializationObject.textureArrays[name] = [];
  54615. var array = this._textureArrays[name];
  54616. for (var index = 0; index < array.length; index++) {
  54617. serializationObject.textureArrays[name].push(array[index].serialize());
  54618. }
  54619. }
  54620. // Float
  54621. serializationObject.floats = {};
  54622. for (name in this._floats) {
  54623. serializationObject.floats[name] = this._floats[name];
  54624. }
  54625. // Float s
  54626. serializationObject.FloatArrays = {};
  54627. for (name in this._floatsArrays) {
  54628. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54629. }
  54630. // Color3
  54631. serializationObject.colors3 = {};
  54632. for (name in this._colors3) {
  54633. serializationObject.colors3[name] = this._colors3[name].asArray();
  54634. }
  54635. // Color3 array
  54636. serializationObject.colors3Arrays = {};
  54637. for (name in this._colors3Arrays) {
  54638. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54639. }
  54640. // Color4
  54641. serializationObject.colors4 = {};
  54642. for (name in this._colors4) {
  54643. serializationObject.colors4[name] = this._colors4[name].asArray();
  54644. }
  54645. // Vector2
  54646. serializationObject.vectors2 = {};
  54647. for (name in this._vectors2) {
  54648. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54649. }
  54650. // Vector3
  54651. serializationObject.vectors3 = {};
  54652. for (name in this._vectors3) {
  54653. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54654. }
  54655. // Vector4
  54656. serializationObject.vectors4 = {};
  54657. for (name in this._vectors4) {
  54658. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54659. }
  54660. // Matrix
  54661. serializationObject.matrices = {};
  54662. for (name in this._matrices) {
  54663. serializationObject.matrices[name] = this._matrices[name].asArray();
  54664. }
  54665. // Matrix 3x3
  54666. serializationObject.matrices3x3 = {};
  54667. for (name in this._matrices3x3) {
  54668. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54669. }
  54670. // Matrix 2x2
  54671. serializationObject.matrices2x2 = {};
  54672. for (name in this._matrices2x2) {
  54673. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54674. }
  54675. // Vector2Array
  54676. serializationObject.vectors2Arrays = {};
  54677. for (name in this._vectors2Arrays) {
  54678. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54679. }
  54680. // Vector3Array
  54681. serializationObject.vectors3Arrays = {};
  54682. for (name in this._vectors3Arrays) {
  54683. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54684. }
  54685. return serializationObject;
  54686. };
  54687. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54688. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54689. var name;
  54690. // Texture
  54691. for (name in source.textures) {
  54692. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54693. }
  54694. // Texture arrays
  54695. for (name in source.textureArrays) {
  54696. var array = source.textureArrays[name];
  54697. var textureArray = new Array();
  54698. for (var index = 0; index < array.length; index++) {
  54699. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54700. }
  54701. material.setTextureArray(name, textureArray);
  54702. }
  54703. // Float
  54704. for (name in source.floats) {
  54705. material.setFloat(name, source.floats[name]);
  54706. }
  54707. // Float s
  54708. for (name in source.floatsArrays) {
  54709. material.setFloats(name, source.floatsArrays[name]);
  54710. }
  54711. // Color3
  54712. for (name in source.colors3) {
  54713. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54714. }
  54715. // Color3 arrays
  54716. for (name in source.colors3Arrays) {
  54717. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54718. if (i % 3 === 0) {
  54719. arr.push([num]);
  54720. }
  54721. else {
  54722. arr[arr.length - 1].push(num);
  54723. }
  54724. return arr;
  54725. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54726. material.setColor3Array(name, colors);
  54727. }
  54728. // Color4
  54729. for (name in source.colors4) {
  54730. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54731. }
  54732. // Vector2
  54733. for (name in source.vectors2) {
  54734. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54735. }
  54736. // Vector3
  54737. for (name in source.vectors3) {
  54738. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54739. }
  54740. // Vector4
  54741. for (name in source.vectors4) {
  54742. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54743. }
  54744. // Matrix
  54745. for (name in source.matrices) {
  54746. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54747. }
  54748. // Matrix 3x3
  54749. for (name in source.matrices3x3) {
  54750. material.setMatrix3x3(name, source.matrices3x3[name]);
  54751. }
  54752. // Matrix 2x2
  54753. for (name in source.matrices2x2) {
  54754. material.setMatrix2x2(name, source.matrices2x2[name]);
  54755. }
  54756. // Vector2Array
  54757. for (name in source.vectors2Arrays) {
  54758. material.setArray2(name, source.vectors2Arrays[name]);
  54759. }
  54760. // Vector3Array
  54761. for (name in source.vectors3Arrays) {
  54762. material.setArray3(name, source.vectors3Arrays[name]);
  54763. }
  54764. return material;
  54765. };
  54766. return ShaderMaterial;
  54767. }(BABYLON.Material));
  54768. BABYLON.ShaderMaterial = ShaderMaterial;
  54769. })(BABYLON || (BABYLON = {}));
  54770. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54771. var BABYLON;
  54772. (function (BABYLON) {
  54773. var GroundMesh = /** @class */ (function (_super) {
  54774. __extends(GroundMesh, _super);
  54775. function GroundMesh(name, scene) {
  54776. var _this = _super.call(this, name, scene) || this;
  54777. _this.generateOctree = false;
  54778. return _this;
  54779. }
  54780. GroundMesh.prototype.getClassName = function () {
  54781. return "GroundMesh";
  54782. };
  54783. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54784. get: function () {
  54785. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54786. },
  54787. enumerable: true,
  54788. configurable: true
  54789. });
  54790. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54791. get: function () {
  54792. return this._subdivisionsX;
  54793. },
  54794. enumerable: true,
  54795. configurable: true
  54796. });
  54797. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54798. get: function () {
  54799. return this._subdivisionsY;
  54800. },
  54801. enumerable: true,
  54802. configurable: true
  54803. });
  54804. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54805. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54806. this._subdivisionsX = chunksCount;
  54807. this._subdivisionsY = chunksCount;
  54808. this.subdivide(chunksCount);
  54809. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54810. };
  54811. /**
  54812. * Returns a height (y) value in the Worl system :
  54813. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54814. * Returns the ground y position if (x, z) are outside the ground surface.
  54815. */
  54816. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54817. var world = this.getWorldMatrix();
  54818. var invMat = BABYLON.Tmp.Matrix[5];
  54819. world.invertToRef(invMat);
  54820. var tmpVect = BABYLON.Tmp.Vector3[8];
  54821. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54822. x = tmpVect.x;
  54823. z = tmpVect.z;
  54824. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54825. return this.position.y;
  54826. }
  54827. if (!this._heightQuads || this._heightQuads.length == 0) {
  54828. this._initHeightQuads();
  54829. this._computeHeightQuads();
  54830. }
  54831. var facet = this._getFacetAt(x, z);
  54832. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54833. // return y in the World system
  54834. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54835. return tmpVect.y;
  54836. };
  54837. /**
  54838. * Returns a normalized vector (Vector3) orthogonal to the ground
  54839. * at the ground coordinates (x, z) expressed in the World system.
  54840. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54841. */
  54842. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54843. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54844. this.getNormalAtCoordinatesToRef(x, z, normal);
  54845. return normal;
  54846. };
  54847. /**
  54848. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54849. * at the ground coordinates (x, z) expressed in the World system.
  54850. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54851. * Returns the GroundMesh.
  54852. */
  54853. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54854. var world = this.getWorldMatrix();
  54855. var tmpMat = BABYLON.Tmp.Matrix[5];
  54856. world.invertToRef(tmpMat);
  54857. var tmpVect = BABYLON.Tmp.Vector3[8];
  54858. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54859. x = tmpVect.x;
  54860. z = tmpVect.z;
  54861. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54862. return this;
  54863. }
  54864. if (!this._heightQuads || this._heightQuads.length == 0) {
  54865. this._initHeightQuads();
  54866. this._computeHeightQuads();
  54867. }
  54868. var facet = this._getFacetAt(x, z);
  54869. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54870. return this;
  54871. };
  54872. /**
  54873. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54874. * if the ground has been updated.
  54875. * This can be used in the render loop.
  54876. * Returns the GroundMesh.
  54877. */
  54878. GroundMesh.prototype.updateCoordinateHeights = function () {
  54879. if (!this._heightQuads || this._heightQuads.length == 0) {
  54880. this._initHeightQuads();
  54881. }
  54882. this._computeHeightQuads();
  54883. return this;
  54884. };
  54885. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54886. GroundMesh.prototype._getFacetAt = function (x, z) {
  54887. // retrieve col and row from x, z coordinates in the ground local system
  54888. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54889. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54890. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54891. var facet;
  54892. if (z < quad.slope.x * x + quad.slope.y) {
  54893. facet = quad.facet1;
  54894. }
  54895. else {
  54896. facet = quad.facet2;
  54897. }
  54898. return facet;
  54899. };
  54900. // Creates and populates the heightMap array with "facet" elements :
  54901. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54902. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54903. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54904. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54905. // Returns the GroundMesh.
  54906. GroundMesh.prototype._initHeightQuads = function () {
  54907. var subdivisionsX = this._subdivisionsX;
  54908. var subdivisionsY = this._subdivisionsY;
  54909. this._heightQuads = new Array();
  54910. for (var row = 0; row < subdivisionsY; row++) {
  54911. for (var col = 0; col < subdivisionsX; col++) {
  54912. 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) };
  54913. this._heightQuads[row * subdivisionsX + col] = quad;
  54914. }
  54915. }
  54916. return this;
  54917. };
  54918. // Compute each quad element values and update the the heightMap array :
  54919. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54920. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54921. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54922. // Returns the GroundMesh.
  54923. GroundMesh.prototype._computeHeightQuads = function () {
  54924. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54925. if (!positions) {
  54926. return this;
  54927. }
  54928. var v1 = BABYLON.Tmp.Vector3[3];
  54929. var v2 = BABYLON.Tmp.Vector3[2];
  54930. var v3 = BABYLON.Tmp.Vector3[1];
  54931. var v4 = BABYLON.Tmp.Vector3[0];
  54932. var v1v2 = BABYLON.Tmp.Vector3[4];
  54933. var v1v3 = BABYLON.Tmp.Vector3[5];
  54934. var v1v4 = BABYLON.Tmp.Vector3[6];
  54935. var norm1 = BABYLON.Tmp.Vector3[7];
  54936. var norm2 = BABYLON.Tmp.Vector3[8];
  54937. var i = 0;
  54938. var j = 0;
  54939. var k = 0;
  54940. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54941. var h = 0;
  54942. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54943. var d2 = 0;
  54944. var subdivisionsX = this._subdivisionsX;
  54945. var subdivisionsY = this._subdivisionsY;
  54946. for (var row = 0; row < subdivisionsY; row++) {
  54947. for (var col = 0; col < subdivisionsX; col++) {
  54948. i = col * 3;
  54949. j = row * (subdivisionsX + 1) * 3;
  54950. k = (row + 1) * (subdivisionsX + 1) * 3;
  54951. v1.x = positions[j + i];
  54952. v1.y = positions[j + i + 1];
  54953. v1.z = positions[j + i + 2];
  54954. v2.x = positions[j + i + 3];
  54955. v2.y = positions[j + i + 4];
  54956. v2.z = positions[j + i + 5];
  54957. v3.x = positions[k + i];
  54958. v3.y = positions[k + i + 1];
  54959. v3.z = positions[k + i + 2];
  54960. v4.x = positions[k + i + 3];
  54961. v4.y = positions[k + i + 4];
  54962. v4.z = positions[k + i + 5];
  54963. // 2D slope V1V4
  54964. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54965. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54966. // facet equations :
  54967. // we compute each facet normal vector
  54968. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54969. // we compute the value d by applying the equation to v1 which belongs to the plane
  54970. // then we store the facet equation in a Vector4
  54971. v2.subtractToRef(v1, v1v2);
  54972. v3.subtractToRef(v1, v1v3);
  54973. v4.subtractToRef(v1, v1v4);
  54974. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54975. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54976. norm1.normalize();
  54977. norm2.normalize();
  54978. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54979. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54980. var quad = this._heightQuads[row * subdivisionsX + col];
  54981. quad.slope.copyFromFloats(cd, h);
  54982. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54983. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54984. }
  54985. }
  54986. return this;
  54987. };
  54988. GroundMesh.prototype.serialize = function (serializationObject) {
  54989. _super.prototype.serialize.call(this, serializationObject);
  54990. serializationObject.subdivisionsX = this._subdivisionsX;
  54991. serializationObject.subdivisionsY = this._subdivisionsY;
  54992. serializationObject.minX = this._minX;
  54993. serializationObject.maxX = this._maxX;
  54994. serializationObject.minZ = this._minZ;
  54995. serializationObject.maxZ = this._maxZ;
  54996. serializationObject.width = this._width;
  54997. serializationObject.height = this._height;
  54998. };
  54999. GroundMesh.Parse = function (parsedMesh, scene) {
  55000. var result = new GroundMesh(parsedMesh.name, scene);
  55001. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55002. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55003. result._minX = parsedMesh.minX;
  55004. result._maxX = parsedMesh.maxX;
  55005. result._minZ = parsedMesh.minZ;
  55006. result._maxZ = parsedMesh.maxZ;
  55007. result._width = parsedMesh.width;
  55008. result._height = parsedMesh.height;
  55009. return result;
  55010. };
  55011. return GroundMesh;
  55012. }(BABYLON.Mesh));
  55013. BABYLON.GroundMesh = GroundMesh;
  55014. })(BABYLON || (BABYLON = {}));
  55015. //# sourceMappingURL=babylon.groundMesh.js.map
  55016. var BABYLON;
  55017. (function (BABYLON) {
  55018. /**
  55019. * Creates an instance based on a source mesh.
  55020. */
  55021. var InstancedMesh = /** @class */ (function (_super) {
  55022. __extends(InstancedMesh, _super);
  55023. function InstancedMesh(name, source) {
  55024. var _this = _super.call(this, name, source.getScene()) || this;
  55025. source.instances.push(_this);
  55026. _this._sourceMesh = source;
  55027. _this.position.copyFrom(source.position);
  55028. _this.rotation.copyFrom(source.rotation);
  55029. _this.scaling.copyFrom(source.scaling);
  55030. if (source.rotationQuaternion) {
  55031. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55032. }
  55033. _this.infiniteDistance = source.infiniteDistance;
  55034. _this.setPivotMatrix(source.getPivotMatrix());
  55035. _this.refreshBoundingInfo();
  55036. _this._syncSubMeshes();
  55037. return _this;
  55038. }
  55039. /**
  55040. * Returns the string "InstancedMesh".
  55041. */
  55042. InstancedMesh.prototype.getClassName = function () {
  55043. return "InstancedMesh";
  55044. };
  55045. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55046. // Methods
  55047. get: function () {
  55048. return this._sourceMesh.receiveShadows;
  55049. },
  55050. enumerable: true,
  55051. configurable: true
  55052. });
  55053. Object.defineProperty(InstancedMesh.prototype, "material", {
  55054. get: function () {
  55055. return this._sourceMesh.material;
  55056. },
  55057. enumerable: true,
  55058. configurable: true
  55059. });
  55060. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55061. get: function () {
  55062. return this._sourceMesh.visibility;
  55063. },
  55064. enumerable: true,
  55065. configurable: true
  55066. });
  55067. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55068. get: function () {
  55069. return this._sourceMesh.skeleton;
  55070. },
  55071. enumerable: true,
  55072. configurable: true
  55073. });
  55074. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55075. get: function () {
  55076. return this._sourceMesh.renderingGroupId;
  55077. },
  55078. enumerable: true,
  55079. configurable: true
  55080. });
  55081. /**
  55082. * Returns the total number of vertices (integer).
  55083. */
  55084. InstancedMesh.prototype.getTotalVertices = function () {
  55085. return this._sourceMesh.getTotalVertices();
  55086. };
  55087. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55088. get: function () {
  55089. return this._sourceMesh;
  55090. },
  55091. enumerable: true,
  55092. configurable: true
  55093. });
  55094. /**
  55095. * Is this node ready to be used/rendered
  55096. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55097. * @return {boolean} is it ready
  55098. */
  55099. InstancedMesh.prototype.isReady = function (completeCheck) {
  55100. if (completeCheck === void 0) { completeCheck = false; }
  55101. return this._sourceMesh.isReady(completeCheck, true);
  55102. };
  55103. /**
  55104. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55105. */
  55106. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55107. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55108. };
  55109. /**
  55110. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55111. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55112. * The `data` are either a numeric array either a Float32Array.
  55113. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55114. * 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).
  55115. * Note that a new underlying VertexBuffer object is created each call.
  55116. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55117. *
  55118. * Possible `kind` values :
  55119. * - BABYLON.VertexBuffer.PositionKind
  55120. * - BABYLON.VertexBuffer.UVKind
  55121. * - BABYLON.VertexBuffer.UV2Kind
  55122. * - BABYLON.VertexBuffer.UV3Kind
  55123. * - BABYLON.VertexBuffer.UV4Kind
  55124. * - BABYLON.VertexBuffer.UV5Kind
  55125. * - BABYLON.VertexBuffer.UV6Kind
  55126. * - BABYLON.VertexBuffer.ColorKind
  55127. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55128. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55129. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55130. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55131. *
  55132. * Returns the Mesh.
  55133. */
  55134. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55135. if (this.sourceMesh) {
  55136. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55137. }
  55138. return this.sourceMesh;
  55139. };
  55140. /**
  55141. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55142. * If the mesh has no geometry, it is simply returned as it is.
  55143. * The `data` are either a numeric array either a Float32Array.
  55144. * No new underlying VertexBuffer object is created.
  55145. * 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.
  55146. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55147. *
  55148. * Possible `kind` values :
  55149. * - BABYLON.VertexBuffer.PositionKind
  55150. * - BABYLON.VertexBuffer.UVKind
  55151. * - BABYLON.VertexBuffer.UV2Kind
  55152. * - BABYLON.VertexBuffer.UV3Kind
  55153. * - BABYLON.VertexBuffer.UV4Kind
  55154. * - BABYLON.VertexBuffer.UV5Kind
  55155. * - BABYLON.VertexBuffer.UV6Kind
  55156. * - BABYLON.VertexBuffer.ColorKind
  55157. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55158. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55159. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55160. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55161. *
  55162. * Returns the Mesh.
  55163. */
  55164. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55165. if (this.sourceMesh) {
  55166. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55167. }
  55168. return this.sourceMesh;
  55169. };
  55170. /**
  55171. * Sets the mesh indices.
  55172. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55173. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55174. * This method creates a new index buffer each call.
  55175. * Returns the Mesh.
  55176. */
  55177. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55178. if (totalVertices === void 0) { totalVertices = null; }
  55179. if (this.sourceMesh) {
  55180. this.sourceMesh.setIndices(indices, totalVertices);
  55181. }
  55182. return this.sourceMesh;
  55183. };
  55184. /**
  55185. * Boolean : True if the mesh owns the requested kind of data.
  55186. */
  55187. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55188. return this._sourceMesh.isVerticesDataPresent(kind);
  55189. };
  55190. /**
  55191. * Returns an array of indices (IndicesArray).
  55192. */
  55193. InstancedMesh.prototype.getIndices = function () {
  55194. return this._sourceMesh.getIndices();
  55195. };
  55196. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55197. get: function () {
  55198. return this._sourceMesh._positions;
  55199. },
  55200. enumerable: true,
  55201. configurable: true
  55202. });
  55203. /**
  55204. * Sets a new updated BoundingInfo to the mesh.
  55205. * Returns the mesh.
  55206. */
  55207. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55208. var meshBB = this._sourceMesh.getBoundingInfo();
  55209. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55210. this._updateBoundingInfo();
  55211. return this;
  55212. };
  55213. InstancedMesh.prototype._preActivate = function () {
  55214. if (this._currentLOD) {
  55215. this._currentLOD._preActivate();
  55216. }
  55217. return this;
  55218. };
  55219. InstancedMesh.prototype._activate = function (renderId) {
  55220. if (this._currentLOD) {
  55221. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55222. }
  55223. return this;
  55224. };
  55225. /**
  55226. * Returns the current associated LOD AbstractMesh.
  55227. */
  55228. InstancedMesh.prototype.getLOD = function (camera) {
  55229. if (!camera) {
  55230. return this;
  55231. }
  55232. var boundingInfo = this.getBoundingInfo();
  55233. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55234. if (this._currentLOD === this.sourceMesh) {
  55235. return this;
  55236. }
  55237. return this._currentLOD;
  55238. };
  55239. InstancedMesh.prototype._syncSubMeshes = function () {
  55240. this.releaseSubMeshes();
  55241. if (this._sourceMesh.subMeshes) {
  55242. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55243. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55244. }
  55245. }
  55246. return this;
  55247. };
  55248. InstancedMesh.prototype._generatePointsArray = function () {
  55249. return this._sourceMesh._generatePointsArray();
  55250. };
  55251. /**
  55252. * Creates a new InstancedMesh from the current mesh.
  55253. * - name (string) : the cloned mesh name
  55254. * - newParent (optional Node) : the optional Node to parent the clone to.
  55255. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55256. *
  55257. * Returns the clone.
  55258. */
  55259. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55260. var result = this._sourceMesh.createInstance(name);
  55261. // Deep copy
  55262. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55263. // Bounding info
  55264. this.refreshBoundingInfo();
  55265. // Parent
  55266. if (newParent) {
  55267. result.parent = newParent;
  55268. }
  55269. if (!doNotCloneChildren) {
  55270. // Children
  55271. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55272. var mesh = this.getScene().meshes[index];
  55273. if (mesh.parent === this) {
  55274. mesh.clone(mesh.name, result);
  55275. }
  55276. }
  55277. }
  55278. result.computeWorldMatrix(true);
  55279. return result;
  55280. };
  55281. /**
  55282. * Disposes the InstancedMesh.
  55283. * Returns nothing.
  55284. */
  55285. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  55286. // Remove from mesh
  55287. var index = this._sourceMesh.instances.indexOf(this);
  55288. this._sourceMesh.instances.splice(index, 1);
  55289. _super.prototype.dispose.call(this, doNotRecurse);
  55290. };
  55291. return InstancedMesh;
  55292. }(BABYLON.AbstractMesh));
  55293. BABYLON.InstancedMesh = InstancedMesh;
  55294. })(BABYLON || (BABYLON = {}));
  55295. //# sourceMappingURL=babylon.instancedMesh.js.map
  55296. var BABYLON;
  55297. (function (BABYLON) {
  55298. var LinesMesh = /** @class */ (function (_super) {
  55299. __extends(LinesMesh, _super);
  55300. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55301. if (scene === void 0) { scene = null; }
  55302. if (parent === void 0) { parent = null; }
  55303. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55304. _this.useVertexColor = useVertexColor;
  55305. _this.useVertexAlpha = useVertexAlpha;
  55306. _this.color = new BABYLON.Color3(1, 1, 1);
  55307. _this.alpha = 1;
  55308. if (source) {
  55309. _this.color = source.color.clone();
  55310. _this.alpha = source.alpha;
  55311. _this.useVertexColor = source.useVertexColor;
  55312. _this.useVertexAlpha = source.useVertexAlpha;
  55313. }
  55314. _this._intersectionThreshold = 0.1;
  55315. var defines = [];
  55316. var options = {
  55317. attributes: [BABYLON.VertexBuffer.PositionKind],
  55318. uniforms: ["world", "viewProjection"],
  55319. needAlphaBlending: true,
  55320. defines: defines
  55321. };
  55322. if (useVertexAlpha === false) {
  55323. options.needAlphaBlending = false;
  55324. }
  55325. if (!useVertexColor) {
  55326. options.uniforms.push("color");
  55327. }
  55328. else {
  55329. options.defines.push("#define VERTEXCOLOR");
  55330. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55331. }
  55332. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55333. return _this;
  55334. }
  55335. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55336. /**
  55337. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55338. * This margin is expressed in world space coordinates, so its value may vary.
  55339. * Default value is 0.1
  55340. * @returns the intersection Threshold value.
  55341. */
  55342. get: function () {
  55343. return this._intersectionThreshold;
  55344. },
  55345. /**
  55346. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55347. * This margin is expressed in world space coordinates, so its value may vary.
  55348. * @param value the new threshold to apply
  55349. */
  55350. set: function (value) {
  55351. if (this._intersectionThreshold === value) {
  55352. return;
  55353. }
  55354. this._intersectionThreshold = value;
  55355. if (this.geometry) {
  55356. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55357. }
  55358. },
  55359. enumerable: true,
  55360. configurable: true
  55361. });
  55362. /**
  55363. * Returns the string "LineMesh"
  55364. */
  55365. LinesMesh.prototype.getClassName = function () {
  55366. return "LinesMesh";
  55367. };
  55368. Object.defineProperty(LinesMesh.prototype, "material", {
  55369. get: function () {
  55370. return this._colorShader;
  55371. },
  55372. set: function (value) {
  55373. // Do nothing
  55374. },
  55375. enumerable: true,
  55376. configurable: true
  55377. });
  55378. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55379. get: function () {
  55380. return false;
  55381. },
  55382. enumerable: true,
  55383. configurable: true
  55384. });
  55385. LinesMesh.prototype.createInstance = function (name) {
  55386. throw new Error("LinesMeshes do not support createInstance.");
  55387. };
  55388. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55389. if (!this._geometry) {
  55390. return this;
  55391. }
  55392. // VBOs
  55393. this._geometry._bind(this._colorShader.getEffect());
  55394. // Color
  55395. if (!this.useVertexColor) {
  55396. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55397. }
  55398. return this;
  55399. };
  55400. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55401. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55402. return this;
  55403. }
  55404. var engine = this.getScene().getEngine();
  55405. // Draw order
  55406. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55407. return this;
  55408. };
  55409. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55410. this._colorShader.dispose();
  55411. _super.prototype.dispose.call(this, doNotRecurse);
  55412. };
  55413. /**
  55414. * Returns a new LineMesh object cloned from the current one.
  55415. */
  55416. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55417. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55418. };
  55419. return LinesMesh;
  55420. }(BABYLON.Mesh));
  55421. BABYLON.LinesMesh = LinesMesh;
  55422. })(BABYLON || (BABYLON = {}));
  55423. //# sourceMappingURL=babylon.linesMesh.js.map
  55424. var BABYLON;
  55425. (function (BABYLON) {
  55426. var MeshBuilder = /** @class */ (function () {
  55427. function MeshBuilder() {
  55428. }
  55429. MeshBuilder.updateSideOrientation = function (orientation) {
  55430. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55431. return BABYLON.Mesh.DOUBLESIDE;
  55432. }
  55433. if (orientation === undefined || orientation === null) {
  55434. return BABYLON.Mesh.FRONTSIDE;
  55435. }
  55436. return orientation;
  55437. };
  55438. /**
  55439. * Creates a box mesh.
  55440. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55441. * The parameter `size` sets the size (float) of each box side (default 1).
  55442. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55443. * 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).
  55444. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55445. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55446. * 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).
  55447. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55448. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55449. */
  55450. MeshBuilder.CreateBox = function (name, options, scene) {
  55451. if (scene === void 0) { scene = null; }
  55452. var box = new BABYLON.Mesh(name, scene);
  55453. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55454. box._originalBuilderSideOrientation = options.sideOrientation;
  55455. var vertexData = BABYLON.VertexData.CreateBox(options);
  55456. vertexData.applyToMesh(box, options.updatable);
  55457. return box;
  55458. };
  55459. /**
  55460. * Creates a sphere mesh.
  55461. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55462. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55463. * 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`).
  55464. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55465. * 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
  55466. * 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).
  55467. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55468. * 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).
  55469. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55470. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55471. */
  55472. MeshBuilder.CreateSphere = function (name, options, scene) {
  55473. var sphere = new BABYLON.Mesh(name, scene);
  55474. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55475. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55476. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55477. vertexData.applyToMesh(sphere, options.updatable);
  55478. return sphere;
  55479. };
  55480. /**
  55481. * Creates a plane polygonal mesh. By default, this is a disc.
  55482. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55483. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55484. * 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.
  55485. * 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
  55486. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55487. * 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).
  55488. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55489. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55490. */
  55491. MeshBuilder.CreateDisc = function (name, options, scene) {
  55492. if (scene === void 0) { scene = null; }
  55493. var disc = new BABYLON.Mesh(name, scene);
  55494. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55495. disc._originalBuilderSideOrientation = options.sideOrientation;
  55496. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55497. vertexData.applyToMesh(disc, options.updatable);
  55498. return disc;
  55499. };
  55500. /**
  55501. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55502. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55503. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55504. * 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`).
  55505. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55506. * 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.
  55507. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55508. * 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).
  55509. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55510. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55511. */
  55512. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55513. var sphere = new BABYLON.Mesh(name, scene);
  55514. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55515. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55516. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55517. vertexData.applyToMesh(sphere, options.updatable);
  55518. return sphere;
  55519. };
  55520. ;
  55521. /**
  55522. * Creates a ribbon mesh.
  55523. * 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.
  55524. *
  55525. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55526. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55527. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55528. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55529. * 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.
  55530. * 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.
  55531. * 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
  55532. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55533. * 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).
  55534. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55535. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55536. * 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.
  55537. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55538. * 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
  55539. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55540. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55541. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55542. */
  55543. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55544. if (scene === void 0) { scene = null; }
  55545. var pathArray = options.pathArray;
  55546. var closeArray = options.closeArray;
  55547. var closePath = options.closePath;
  55548. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55549. var instance = options.instance;
  55550. var updatable = options.updatable;
  55551. if (instance) {
  55552. // positionFunction : ribbon case
  55553. // only pathArray and sideOrientation parameters are taken into account for positions update
  55554. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55555. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55556. var positionFunction = function (positions) {
  55557. var minlg = pathArray[0].length;
  55558. var i = 0;
  55559. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55560. for (var si = 1; si <= ns; si++) {
  55561. for (var p = 0; p < pathArray.length; p++) {
  55562. var path = pathArray[p];
  55563. var l = path.length;
  55564. minlg = (minlg < l) ? minlg : l;
  55565. var j = 0;
  55566. while (j < minlg) {
  55567. positions[i] = path[j].x;
  55568. positions[i + 1] = path[j].y;
  55569. positions[i + 2] = path[j].z;
  55570. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55571. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55572. }
  55573. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55574. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55575. }
  55576. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55577. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55578. }
  55579. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55580. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55581. }
  55582. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55583. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55584. }
  55585. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55586. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55587. }
  55588. j++;
  55589. i += 3;
  55590. }
  55591. if (instance._closePath) {
  55592. positions[i] = path[0].x;
  55593. positions[i + 1] = path[0].y;
  55594. positions[i + 2] = path[0].z;
  55595. i += 3;
  55596. }
  55597. }
  55598. }
  55599. };
  55600. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55601. positionFunction(positions);
  55602. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55603. instance._boundingInfo.update(instance._worldMatrix);
  55604. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55605. if (options.colors) {
  55606. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55607. for (var c = 0; c < options.colors.length; c++) {
  55608. colors[c * 4] = options.colors[c].r;
  55609. colors[c * 4 + 1] = options.colors[c].g;
  55610. colors[c * 4 + 2] = options.colors[c].b;
  55611. colors[c * 4 + 3] = options.colors[c].a;
  55612. }
  55613. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55614. }
  55615. if (options.uvs) {
  55616. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55617. for (var i = 0; i < options.uvs.length; i++) {
  55618. uvs[i * 2] = options.uvs[i].x;
  55619. uvs[i * 2 + 1] = options.uvs[i].y;
  55620. }
  55621. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55622. }
  55623. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55624. var indices = instance.getIndices();
  55625. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55626. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55627. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55628. if (instance._closePath) {
  55629. var indexFirst = 0;
  55630. var indexLast = 0;
  55631. for (var p = 0; p < pathArray.length; p++) {
  55632. indexFirst = instance._idx[p] * 3;
  55633. if (p + 1 < pathArray.length) {
  55634. indexLast = (instance._idx[p + 1] - 1) * 3;
  55635. }
  55636. else {
  55637. indexLast = normals.length - 3;
  55638. }
  55639. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55640. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55641. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55642. normals[indexLast] = normals[indexFirst];
  55643. normals[indexLast + 1] = normals[indexFirst + 1];
  55644. normals[indexLast + 2] = normals[indexFirst + 2];
  55645. }
  55646. }
  55647. if (!(instance.areNormalsFrozen)) {
  55648. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55649. }
  55650. }
  55651. return instance;
  55652. }
  55653. else {
  55654. var ribbon = new BABYLON.Mesh(name, scene);
  55655. ribbon._originalBuilderSideOrientation = sideOrientation;
  55656. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55657. if (closePath) {
  55658. ribbon._idx = vertexData._idx;
  55659. }
  55660. ribbon._closePath = closePath;
  55661. ribbon._closeArray = closeArray;
  55662. vertexData.applyToMesh(ribbon, updatable);
  55663. return ribbon;
  55664. }
  55665. };
  55666. /**
  55667. * Creates a cylinder or a cone mesh.
  55668. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55669. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55670. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55671. * 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.
  55672. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55673. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55674. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55675. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55676. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55677. * 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).
  55678. * 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
  55679. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55680. * 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
  55681. * 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.
  55682. * If `enclose` is false, a ring surface is one element.
  55683. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55684. * 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
  55685. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55686. * 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).
  55687. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55689. */
  55690. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55691. var cylinder = new BABYLON.Mesh(name, scene);
  55692. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55693. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55694. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55695. vertexData.applyToMesh(cylinder, options.updatable);
  55696. return cylinder;
  55697. };
  55698. /**
  55699. * Creates a torus mesh.
  55700. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55701. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55702. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55703. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55704. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55705. * 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).
  55706. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55707. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55708. */
  55709. MeshBuilder.CreateTorus = function (name, options, scene) {
  55710. var torus = new BABYLON.Mesh(name, scene);
  55711. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55712. torus._originalBuilderSideOrientation = options.sideOrientation;
  55713. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55714. vertexData.applyToMesh(torus, options.updatable);
  55715. return torus;
  55716. };
  55717. /**
  55718. * Creates a torus knot mesh.
  55719. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55720. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55721. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55722. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55723. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55724. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55725. * 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).
  55726. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55727. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55728. */
  55729. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55730. var torusKnot = new BABYLON.Mesh(name, scene);
  55731. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55732. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55733. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55734. vertexData.applyToMesh(torusKnot, options.updatable);
  55735. return torusKnot;
  55736. };
  55737. /**
  55738. * Creates a line system mesh.
  55739. * A line system is a pool of many lines gathered in a single mesh.
  55740. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55741. * 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.
  55742. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55743. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55744. * 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
  55745. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55746. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55747. * 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
  55748. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55750. */
  55751. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55752. var instance = options.instance;
  55753. var lines = options.lines;
  55754. var colors = options.colors;
  55755. if (instance) {
  55756. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55757. var vertexColor;
  55758. var lineColors;
  55759. if (colors) {
  55760. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55761. }
  55762. var i = 0;
  55763. var c = 0;
  55764. for (var l = 0; l < lines.length; l++) {
  55765. var points = lines[l];
  55766. for (var p = 0; p < points.length; p++) {
  55767. positions[i] = points[p].x;
  55768. positions[i + 1] = points[p].y;
  55769. positions[i + 2] = points[p].z;
  55770. if (colors && vertexColor) {
  55771. lineColors = colors[l];
  55772. vertexColor[c] = lineColors[p].r;
  55773. vertexColor[c + 1] = lineColors[p].g;
  55774. vertexColor[c + 2] = lineColors[p].b;
  55775. vertexColor[c + 3] = lineColors[p].a;
  55776. c += 4;
  55777. }
  55778. i += 3;
  55779. }
  55780. }
  55781. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55782. if (colors && vertexColor) {
  55783. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55784. }
  55785. return instance;
  55786. }
  55787. // line system creation
  55788. var useVertexColor = (colors) ? true : false;
  55789. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55790. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55791. vertexData.applyToMesh(lineSystem, options.updatable);
  55792. return lineSystem;
  55793. };
  55794. /**
  55795. * Creates a line mesh.
  55796. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55797. * 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.
  55798. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55799. * The parameter `points` is an array successive Vector3.
  55800. * 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
  55801. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55802. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55803. * When updating an instance, remember that only point positions can change, not the number of points.
  55804. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55805. */
  55806. MeshBuilder.CreateLines = function (name, options, scene) {
  55807. if (scene === void 0) { scene = null; }
  55808. var colors = (options.colors) ? [options.colors] : null;
  55809. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55810. return lines;
  55811. };
  55812. /**
  55813. * Creates a dashed line mesh.
  55814. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55815. * 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.
  55816. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55817. * The parameter `points` is an array successive Vector3.
  55818. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55819. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55820. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55821. * 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
  55822. * When updating an instance, remember that only point positions can change, not the number of points.
  55823. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55824. */
  55825. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55826. if (scene === void 0) { scene = null; }
  55827. var points = options.points;
  55828. var instance = options.instance;
  55829. var gapSize = options.gapSize || 1;
  55830. var dashSize = options.dashSize || 3;
  55831. if (instance) {
  55832. var positionFunction = function (positions) {
  55833. var curvect = BABYLON.Vector3.Zero();
  55834. var nbSeg = positions.length / 6;
  55835. var lg = 0;
  55836. var nb = 0;
  55837. var shft = 0;
  55838. var dashshft = 0;
  55839. var curshft = 0;
  55840. var p = 0;
  55841. var i = 0;
  55842. var j = 0;
  55843. for (i = 0; i < points.length - 1; i++) {
  55844. points[i + 1].subtractToRef(points[i], curvect);
  55845. lg += curvect.length();
  55846. }
  55847. shft = lg / nbSeg;
  55848. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55849. for (i = 0; i < points.length - 1; i++) {
  55850. points[i + 1].subtractToRef(points[i], curvect);
  55851. nb = Math.floor(curvect.length() / shft);
  55852. curvect.normalize();
  55853. j = 0;
  55854. while (j < nb && p < positions.length) {
  55855. curshft = shft * j;
  55856. positions[p] = points[i].x + curshft * curvect.x;
  55857. positions[p + 1] = points[i].y + curshft * curvect.y;
  55858. positions[p + 2] = points[i].z + curshft * curvect.z;
  55859. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55860. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55861. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55862. p += 6;
  55863. j++;
  55864. }
  55865. }
  55866. while (p < positions.length) {
  55867. positions[p] = points[i].x;
  55868. positions[p + 1] = points[i].y;
  55869. positions[p + 2] = points[i].z;
  55870. p += 3;
  55871. }
  55872. };
  55873. instance.updateMeshPositions(positionFunction, false);
  55874. return instance;
  55875. }
  55876. // dashed lines creation
  55877. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55878. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55879. vertexData.applyToMesh(dashedLines, options.updatable);
  55880. dashedLines.dashSize = dashSize;
  55881. dashedLines.gapSize = gapSize;
  55882. return dashedLines;
  55883. };
  55884. /**
  55885. * Creates an extruded shape mesh.
  55886. * 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.
  55887. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55888. *
  55889. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55890. * 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
  55891. * extruded along the Z axis.
  55892. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55893. * 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.
  55894. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55895. * 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
  55896. * 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
  55897. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55898. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55899. * 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).
  55900. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55901. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55903. */
  55904. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55905. if (scene === void 0) { scene = null; }
  55906. var path = options.path;
  55907. var shape = options.shape;
  55908. var scale = options.scale || 1;
  55909. var rotation = options.rotation || 0;
  55910. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55911. var updatable = options.updatable;
  55912. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55913. var instance = options.instance || null;
  55914. var invertUV = options.invertUV || false;
  55915. 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);
  55916. };
  55917. /**
  55918. * Creates an custom extruded shape mesh.
  55919. * 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.
  55920. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55921. *
  55922. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55923. * 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
  55924. * extruded along the Z axis.
  55925. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55926. * 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
  55927. * and the distance of this point from the begining of the path :
  55928. * ```javascript
  55929. * var rotationFunction = function(i, distance) {
  55930. * // do things
  55931. * return rotationValue; }
  55932. * ```
  55933. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55934. * 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
  55935. * and the distance of this point from the begining of the path :
  55936. * ```javascript
  55937. * var scaleFunction = function(i, distance) {
  55938. * // do things
  55939. * return scaleValue;}
  55940. * ```
  55941. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55942. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55943. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55944. * 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
  55945. * 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
  55946. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55947. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55948. * 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).
  55949. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55950. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55952. */
  55953. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55954. var path = options.path;
  55955. var shape = options.shape;
  55956. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55957. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55958. var ribbonCloseArray = options.ribbonCloseArray || false;
  55959. var ribbonClosePath = options.ribbonClosePath || false;
  55960. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55961. var updatable = options.updatable;
  55962. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55963. var instance = options.instance;
  55964. var invertUV = options.invertUV || false;
  55965. 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);
  55966. };
  55967. /**
  55968. * Creates lathe mesh.
  55969. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55970. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55971. *
  55972. * 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
  55973. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55974. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55975. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55976. * 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.
  55977. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55978. * 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
  55979. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55980. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  55981. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55982. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55984. */
  55985. MeshBuilder.CreateLathe = function (name, options, scene) {
  55986. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55987. var closed = (options.closed === undefined) ? true : options.closed;
  55988. var shape = options.shape;
  55989. var radius = options.radius || 1;
  55990. var tessellation = options.tessellation || 64;
  55991. var updatable = options.updatable;
  55992. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55993. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55994. var pi2 = Math.PI * 2;
  55995. var paths = new Array();
  55996. var invertUV = options.invertUV || false;
  55997. var i = 0;
  55998. var p = 0;
  55999. var step = pi2 / tessellation * arc;
  56000. var rotated;
  56001. var path = new Array();
  56002. ;
  56003. for (i = 0; i <= tessellation; i++) {
  56004. var path = [];
  56005. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56006. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56007. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56008. }
  56009. for (p = 0; p < shape.length; p++) {
  56010. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56011. path.push(rotated);
  56012. }
  56013. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56014. 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));
  56015. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56016. }
  56017. paths.push(path);
  56018. }
  56019. // lathe ribbon
  56020. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56021. return lathe;
  56022. };
  56023. /**
  56024. * Creates a plane mesh.
  56025. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56026. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56027. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56028. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56029. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56030. * 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).
  56031. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56032. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56033. */
  56034. MeshBuilder.CreatePlane = function (name, options, scene) {
  56035. var plane = new BABYLON.Mesh(name, scene);
  56036. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56037. plane._originalBuilderSideOrientation = options.sideOrientation;
  56038. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56039. vertexData.applyToMesh(plane, options.updatable);
  56040. if (options.sourcePlane) {
  56041. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56042. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56043. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56044. plane.rotate(vectorProduct, product);
  56045. }
  56046. return plane;
  56047. };
  56048. /**
  56049. * Creates a ground mesh.
  56050. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56051. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56052. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56053. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56054. */
  56055. MeshBuilder.CreateGround = function (name, options, scene) {
  56056. var ground = new BABYLON.GroundMesh(name, scene);
  56057. ground._setReady(false);
  56058. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56059. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56060. ground._width = options.width || 1;
  56061. ground._height = options.height || 1;
  56062. ground._maxX = ground._width / 2;
  56063. ground._maxZ = ground._height / 2;
  56064. ground._minX = -ground._maxX;
  56065. ground._minZ = -ground._maxZ;
  56066. var vertexData = BABYLON.VertexData.CreateGround(options);
  56067. vertexData.applyToMesh(ground, options.updatable);
  56068. ground._setReady(true);
  56069. return ground;
  56070. };
  56071. /**
  56072. * Creates a tiled ground mesh.
  56073. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56074. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56075. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56076. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56077. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56078. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56079. * numbers of subdivisions on the ground width and height of each tile.
  56080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56081. */
  56082. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56083. var tiledGround = new BABYLON.Mesh(name, scene);
  56084. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56085. vertexData.applyToMesh(tiledGround, options.updatable);
  56086. return tiledGround;
  56087. };
  56088. /**
  56089. * Creates a ground mesh from a height map.
  56090. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56091. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56092. * The parameter `url` sets the URL of the height map image resource.
  56093. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56094. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56095. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56096. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56097. * 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.
  56098. * 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).
  56099. * This function is passed the newly built mesh :
  56100. * ```javascript
  56101. * function(mesh) { // do things
  56102. * return; }
  56103. * ```
  56104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56105. */
  56106. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56107. var width = options.width || 10.0;
  56108. var height = options.height || 10.0;
  56109. var subdivisions = options.subdivisions || 1 | 0;
  56110. var minHeight = options.minHeight || 0.0;
  56111. var maxHeight = options.maxHeight || 1.0;
  56112. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56113. var updatable = options.updatable;
  56114. var onReady = options.onReady;
  56115. var ground = new BABYLON.GroundMesh(name, scene);
  56116. ground._subdivisionsX = subdivisions;
  56117. ground._subdivisionsY = subdivisions;
  56118. ground._width = width;
  56119. ground._height = height;
  56120. ground._maxX = ground._width / 2.0;
  56121. ground._maxZ = ground._height / 2.0;
  56122. ground._minX = -ground._maxX;
  56123. ground._minZ = -ground._maxZ;
  56124. ground._setReady(false);
  56125. var onload = function (img) {
  56126. // Getting height map data
  56127. var canvas = document.createElement("canvas");
  56128. var context = canvas.getContext("2d");
  56129. if (!context) {
  56130. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56131. }
  56132. if (scene.isDisposed) {
  56133. return;
  56134. }
  56135. var bufferWidth = img.width;
  56136. var bufferHeight = img.height;
  56137. canvas.width = bufferWidth;
  56138. canvas.height = bufferHeight;
  56139. context.drawImage(img, 0, 0);
  56140. // Create VertexData from map data
  56141. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56142. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56143. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56144. width: width, height: height,
  56145. subdivisions: subdivisions,
  56146. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56147. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56148. });
  56149. vertexData.applyToMesh(ground, updatable);
  56150. ground._setReady(true);
  56151. //execute ready callback, if set
  56152. if (onReady) {
  56153. onReady(ground);
  56154. }
  56155. };
  56156. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56157. return ground;
  56158. };
  56159. /**
  56160. * Creates a polygon mesh.
  56161. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56162. * 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.
  56163. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56164. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56165. * 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).
  56166. * Remember you can only change the shape positions, not their number when updating a polygon.
  56167. */
  56168. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56169. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56170. var shape = options.shape;
  56171. var holes = options.holes || [];
  56172. var depth = options.depth || 0;
  56173. var contours = [];
  56174. var hole = [];
  56175. for (var i = 0; i < shape.length; i++) {
  56176. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56177. }
  56178. var epsilon = 0.00000001;
  56179. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56180. contours.pop();
  56181. }
  56182. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56183. for (var hNb = 0; hNb < holes.length; hNb++) {
  56184. hole = [];
  56185. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56186. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56187. }
  56188. polygonTriangulation.addHole(hole);
  56189. }
  56190. var polygon = polygonTriangulation.build(options.updatable, depth);
  56191. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56192. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56193. vertexData.applyToMesh(polygon, options.updatable);
  56194. return polygon;
  56195. };
  56196. ;
  56197. /**
  56198. * Creates an extruded polygon mesh, with depth in the Y direction.
  56199. * 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).
  56200. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56201. */
  56202. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56203. return MeshBuilder.CreatePolygon(name, options, scene);
  56204. };
  56205. ;
  56206. /**
  56207. * Creates a tube mesh.
  56208. * 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.
  56209. *
  56210. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56211. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56212. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56213. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56214. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56215. * 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.
  56216. * It must return a radius value (positive float) :
  56217. * ```javascript
  56218. * var radiusFunction = function(i, distance) {
  56219. * // do things
  56220. * return radius; }
  56221. * ```
  56222. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56223. * 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
  56224. * 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
  56225. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56226. * 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).
  56227. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56228. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56229. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56230. */
  56231. MeshBuilder.CreateTube = function (name, options, scene) {
  56232. var path = options.path;
  56233. var instance = options.instance;
  56234. var radius = 1.0;
  56235. if (instance) {
  56236. radius = instance.radius;
  56237. }
  56238. if (options.radius !== undefined) {
  56239. radius = options.radius;
  56240. }
  56241. ;
  56242. var tessellation = options.tessellation || 64 | 0;
  56243. var radiusFunction = options.radiusFunction || null;
  56244. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56245. var invertUV = options.invertUV || false;
  56246. var updatable = options.updatable;
  56247. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56248. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56249. // tube geometry
  56250. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56251. var tangents = path3D.getTangents();
  56252. var normals = path3D.getNormals();
  56253. var distances = path3D.getDistances();
  56254. var pi2 = Math.PI * 2;
  56255. var step = pi2 / tessellation * arc;
  56256. var returnRadius = function () { return radius; };
  56257. var radiusFunctionFinal = radiusFunction || returnRadius;
  56258. var circlePath;
  56259. var rad;
  56260. var normal;
  56261. var rotated;
  56262. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56263. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56264. for (var i = 0; i < path.length; i++) {
  56265. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56266. circlePath = Array(); // current circle array
  56267. normal = normals[i]; // current normal
  56268. for (var t = 0; t < tessellation; t++) {
  56269. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56270. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56271. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56272. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56273. circlePath[t] = rotated;
  56274. }
  56275. circlePaths[index] = circlePath;
  56276. index++;
  56277. }
  56278. // cap
  56279. var capPath = function (nbPoints, pathIndex) {
  56280. var pointCap = Array();
  56281. for (var i = 0; i < nbPoints; i++) {
  56282. pointCap.push(path[pathIndex]);
  56283. }
  56284. return pointCap;
  56285. };
  56286. switch (cap) {
  56287. case BABYLON.Mesh.NO_CAP:
  56288. break;
  56289. case BABYLON.Mesh.CAP_START:
  56290. circlePaths[0] = capPath(tessellation, 0);
  56291. circlePaths[1] = circlePaths[2].slice(0);
  56292. break;
  56293. case BABYLON.Mesh.CAP_END:
  56294. circlePaths[index] = circlePaths[index - 1].slice(0);
  56295. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56296. break;
  56297. case BABYLON.Mesh.CAP_ALL:
  56298. circlePaths[0] = capPath(tessellation, 0);
  56299. circlePaths[1] = circlePaths[2].slice(0);
  56300. circlePaths[index] = circlePaths[index - 1].slice(0);
  56301. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56302. break;
  56303. default:
  56304. break;
  56305. }
  56306. return circlePaths;
  56307. };
  56308. var path3D;
  56309. var pathArray;
  56310. if (instance) {
  56311. var arc = options.arc || instance.arc;
  56312. path3D = (instance.path3D).update(path);
  56313. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56314. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56315. instance.path3D = path3D;
  56316. instance.pathArray = pathArray;
  56317. instance.arc = arc;
  56318. instance.radius = radius;
  56319. return instance;
  56320. }
  56321. // tube creation
  56322. path3D = new BABYLON.Path3D(path);
  56323. var newPathArray = new Array();
  56324. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56325. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56326. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56327. tube.pathArray = pathArray;
  56328. tube.path3D = path3D;
  56329. tube.tessellation = tessellation;
  56330. tube.cap = cap;
  56331. tube.arc = options.arc;
  56332. tube.radius = radius;
  56333. return tube;
  56334. };
  56335. /**
  56336. * Creates a polyhedron mesh.
  56337. *
  56338. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56339. * 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
  56340. * to choose the wanted type.
  56341. * The parameter `size` (positive float, default 1) sets the polygon size.
  56342. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56343. * 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`.
  56344. * 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
  56345. * 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)`).
  56346. * 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
  56347. * 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.
  56348. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56349. * 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).
  56350. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56352. */
  56353. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56354. var polyhedron = new BABYLON.Mesh(name, scene);
  56355. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56356. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56357. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56358. vertexData.applyToMesh(polyhedron, options.updatable);
  56359. return polyhedron;
  56360. };
  56361. /**
  56362. * Creates a decal mesh.
  56363. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56364. * 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.
  56365. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56366. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56367. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56368. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56369. */
  56370. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56371. var indices = sourceMesh.getIndices();
  56372. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56373. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56374. var position = options.position || BABYLON.Vector3.Zero();
  56375. var normal = options.normal || BABYLON.Vector3.Up();
  56376. var size = options.size || BABYLON.Vector3.One();
  56377. var angle = options.angle || 0;
  56378. // Getting correct rotation
  56379. if (!normal) {
  56380. var target = new BABYLON.Vector3(0, 0, 1);
  56381. var camera = sourceMesh.getScene().activeCamera;
  56382. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56383. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56384. }
  56385. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56386. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56387. var pitch = Math.atan2(normal.y, len);
  56388. // Matrix
  56389. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56390. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56391. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56392. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56393. var vertexData = new BABYLON.VertexData();
  56394. vertexData.indices = [];
  56395. vertexData.positions = [];
  56396. vertexData.normals = [];
  56397. vertexData.uvs = [];
  56398. var currentVertexDataIndex = 0;
  56399. var extractDecalVector3 = function (indexId) {
  56400. var result = new BABYLON.PositionNormalVertex();
  56401. if (!indices || !positions || !normals) {
  56402. return result;
  56403. }
  56404. var vertexId = indices[indexId];
  56405. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56406. // Send vector to decal local world
  56407. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56408. // Get normal
  56409. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56410. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56411. return result;
  56412. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56413. var clip = function (vertices, axis) {
  56414. if (vertices.length === 0) {
  56415. return vertices;
  56416. }
  56417. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56418. var clipVertices = function (v0, v1) {
  56419. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56420. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56421. };
  56422. var result = new Array();
  56423. for (var index = 0; index < vertices.length; index += 3) {
  56424. var v1Out;
  56425. var v2Out;
  56426. var v3Out;
  56427. var total = 0;
  56428. var nV1 = null;
  56429. var nV2 = null;
  56430. var nV3 = null;
  56431. var nV4 = null;
  56432. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56433. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56434. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56435. v1Out = d1 > 0;
  56436. v2Out = d2 > 0;
  56437. v3Out = d3 > 0;
  56438. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56439. switch (total) {
  56440. case 0:
  56441. result.push(vertices[index]);
  56442. result.push(vertices[index + 1]);
  56443. result.push(vertices[index + 2]);
  56444. break;
  56445. case 1:
  56446. if (v1Out) {
  56447. nV1 = vertices[index + 1];
  56448. nV2 = vertices[index + 2];
  56449. nV3 = clipVertices(vertices[index], nV1);
  56450. nV4 = clipVertices(vertices[index], nV2);
  56451. }
  56452. if (v2Out) {
  56453. nV1 = vertices[index];
  56454. nV2 = vertices[index + 2];
  56455. nV3 = clipVertices(vertices[index + 1], nV1);
  56456. nV4 = clipVertices(vertices[index + 1], nV2);
  56457. result.push(nV3);
  56458. result.push(nV2.clone());
  56459. result.push(nV1.clone());
  56460. result.push(nV2.clone());
  56461. result.push(nV3.clone());
  56462. result.push(nV4);
  56463. break;
  56464. }
  56465. if (v3Out) {
  56466. nV1 = vertices[index];
  56467. nV2 = vertices[index + 1];
  56468. nV3 = clipVertices(vertices[index + 2], nV1);
  56469. nV4 = clipVertices(vertices[index + 2], nV2);
  56470. }
  56471. if (nV1 && nV2 && nV3 && nV4) {
  56472. result.push(nV1.clone());
  56473. result.push(nV2.clone());
  56474. result.push(nV3);
  56475. result.push(nV4);
  56476. result.push(nV3.clone());
  56477. result.push(nV2.clone());
  56478. }
  56479. break;
  56480. case 2:
  56481. if (!v1Out) {
  56482. nV1 = vertices[index].clone();
  56483. nV2 = clipVertices(nV1, vertices[index + 1]);
  56484. nV3 = clipVertices(nV1, vertices[index + 2]);
  56485. result.push(nV1);
  56486. result.push(nV2);
  56487. result.push(nV3);
  56488. }
  56489. if (!v2Out) {
  56490. nV1 = vertices[index + 1].clone();
  56491. nV2 = clipVertices(nV1, vertices[index + 2]);
  56492. nV3 = clipVertices(nV1, vertices[index]);
  56493. result.push(nV1);
  56494. result.push(nV2);
  56495. result.push(nV3);
  56496. }
  56497. if (!v3Out) {
  56498. nV1 = vertices[index + 2].clone();
  56499. nV2 = clipVertices(nV1, vertices[index]);
  56500. nV3 = clipVertices(nV1, vertices[index + 1]);
  56501. result.push(nV1);
  56502. result.push(nV2);
  56503. result.push(nV3);
  56504. }
  56505. break;
  56506. case 3:
  56507. break;
  56508. }
  56509. }
  56510. return result;
  56511. };
  56512. for (var index = 0; index < indices.length; index += 3) {
  56513. var faceVertices = new Array();
  56514. faceVertices.push(extractDecalVector3(index));
  56515. faceVertices.push(extractDecalVector3(index + 1));
  56516. faceVertices.push(extractDecalVector3(index + 2));
  56517. // Clip
  56518. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56519. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56520. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56521. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56522. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56523. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56524. if (faceVertices.length === 0) {
  56525. continue;
  56526. }
  56527. // Add UVs and get back to world
  56528. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56529. var vertex = faceVertices[vIndex];
  56530. //TODO check for Int32Array | Uint32Array | Uint16Array
  56531. vertexData.indices.push(currentVertexDataIndex);
  56532. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56533. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56534. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56535. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56536. currentVertexDataIndex++;
  56537. }
  56538. }
  56539. // Return mesh
  56540. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56541. vertexData.applyToMesh(decal);
  56542. decal.position = position.clone();
  56543. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56544. return decal;
  56545. };
  56546. // Privates
  56547. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56548. // extrusion geometry
  56549. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56550. var tangents = path3D.getTangents();
  56551. var normals = path3D.getNormals();
  56552. var binormals = path3D.getBinormals();
  56553. var distances = path3D.getDistances();
  56554. var angle = 0;
  56555. var returnScale = function () { return scale !== null ? scale : 1; };
  56556. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56557. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56558. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56559. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56560. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56561. for (var i = 0; i < curve.length; i++) {
  56562. var shapePath = new Array();
  56563. var angleStep = rotate(i, distances[i]);
  56564. var scaleRatio = scl(i, distances[i]);
  56565. for (var p = 0; p < shape.length; p++) {
  56566. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56567. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56568. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56569. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56570. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56571. shapePath[p] = rotated;
  56572. }
  56573. shapePaths[index] = shapePath;
  56574. angle += angleStep;
  56575. index++;
  56576. }
  56577. // cap
  56578. var capPath = function (shapePath) {
  56579. var pointCap = Array();
  56580. var barycenter = BABYLON.Vector3.Zero();
  56581. var i;
  56582. for (i = 0; i < shapePath.length; i++) {
  56583. barycenter.addInPlace(shapePath[i]);
  56584. }
  56585. barycenter.scaleInPlace(1.0 / shapePath.length);
  56586. for (i = 0; i < shapePath.length; i++) {
  56587. pointCap.push(barycenter);
  56588. }
  56589. return pointCap;
  56590. };
  56591. switch (cap) {
  56592. case BABYLON.Mesh.NO_CAP:
  56593. break;
  56594. case BABYLON.Mesh.CAP_START:
  56595. shapePaths[0] = capPath(shapePaths[2]);
  56596. shapePaths[1] = shapePaths[2];
  56597. break;
  56598. case BABYLON.Mesh.CAP_END:
  56599. shapePaths[index] = shapePaths[index - 1];
  56600. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56601. break;
  56602. case BABYLON.Mesh.CAP_ALL:
  56603. shapePaths[0] = capPath(shapePaths[2]);
  56604. shapePaths[1] = shapePaths[2];
  56605. shapePaths[index] = shapePaths[index - 1];
  56606. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56607. break;
  56608. default:
  56609. break;
  56610. }
  56611. return shapePaths;
  56612. };
  56613. var path3D;
  56614. var pathArray;
  56615. if (instance) {
  56616. path3D = (instance.path3D).update(curve);
  56617. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56618. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56619. return instance;
  56620. }
  56621. // extruded shape creation
  56622. path3D = new BABYLON.Path3D(curve);
  56623. var newShapePaths = new Array();
  56624. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56625. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56626. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56627. extrudedGeneric.pathArray = pathArray;
  56628. extrudedGeneric.path3D = path3D;
  56629. extrudedGeneric.cap = cap;
  56630. return extrudedGeneric;
  56631. };
  56632. return MeshBuilder;
  56633. }());
  56634. BABYLON.MeshBuilder = MeshBuilder;
  56635. })(BABYLON || (BABYLON = {}));
  56636. //# sourceMappingURL=babylon.meshBuilder.js.map
  56637. var BABYLON;
  56638. (function (BABYLON) {
  56639. /**
  56640. * Draco compression (https://google.github.io/draco/)
  56641. */
  56642. var DracoCompression = /** @class */ (function () {
  56643. /**
  56644. * Constructor
  56645. * @param numWorkers The number of workers for async operations
  56646. */
  56647. function DracoCompression(numWorkers) {
  56648. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56649. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56650. if (!workerBlobUrl || !Worker) {
  56651. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56652. return;
  56653. }
  56654. var workers = new Array(numWorkers);
  56655. for (var i = 0; i < workers.length; i++) {
  56656. var worker = new Worker(workerBlobUrl);
  56657. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56658. workers[i] = worker;
  56659. }
  56660. this._workerPool = new BABYLON.WorkerPool(workers);
  56661. }
  56662. /**
  56663. * Stop all async operations and release resources.
  56664. */
  56665. DracoCompression.prototype.dispose = function () {
  56666. this._workerPool.dispose();
  56667. delete this._workerPool;
  56668. };
  56669. /**
  56670. * Decode Draco compressed mesh data to vertex data.
  56671. * @param data The array buffer view for the Draco compression data
  56672. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56673. * @returns A promise that resolves with the decoded vertex data
  56674. */
  56675. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56676. var _this = this;
  56677. return new Promise(function (resolve, reject) {
  56678. _this._workerPool.push(function (worker, onComplete) {
  56679. var vertexData = new BABYLON.VertexData();
  56680. var onError = function (error) {
  56681. worker.removeEventListener("error", onError);
  56682. worker.removeEventListener("message", onMessage);
  56683. reject(error);
  56684. onComplete();
  56685. };
  56686. var onMessage = function (message) {
  56687. if (message.data === "done") {
  56688. worker.removeEventListener("error", onError);
  56689. worker.removeEventListener("message", onMessage);
  56690. resolve(vertexData);
  56691. onComplete();
  56692. }
  56693. else if (message.data.id === "indices") {
  56694. vertexData.indices = message.data.value;
  56695. }
  56696. else {
  56697. vertexData.set(message.data.value, message.data.id);
  56698. }
  56699. };
  56700. worker.addEventListener("error", onError);
  56701. worker.addEventListener("message", onMessage);
  56702. var dataCopy = new Uint8Array(data.byteLength);
  56703. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56704. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56705. });
  56706. });
  56707. };
  56708. /**
  56709. * The worker function that gets converted to a blob url to pass into a worker.
  56710. */
  56711. DracoCompression._Worker = function () {
  56712. // self is actually a DedicatedWorkerGlobalScope
  56713. var _self = self;
  56714. var decodeMesh = function (data, attributes) {
  56715. var dracoModule = new DracoDecoderModule();
  56716. var buffer = new dracoModule.DecoderBuffer();
  56717. buffer.Init(data, data.byteLength);
  56718. var decoder = new dracoModule.Decoder();
  56719. var geometry;
  56720. var status;
  56721. try {
  56722. var type = decoder.GetEncodedGeometryType(buffer);
  56723. switch (type) {
  56724. case dracoModule.TRIANGULAR_MESH:
  56725. geometry = new dracoModule.Mesh();
  56726. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56727. break;
  56728. case dracoModule.POINT_CLOUD:
  56729. geometry = new dracoModule.PointCloud();
  56730. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56731. break;
  56732. default:
  56733. throw new Error("Invalid geometry type " + type);
  56734. }
  56735. if (!status.ok() || !geometry.ptr) {
  56736. throw new Error(status.error_msg());
  56737. }
  56738. var numPoints = geometry.num_points();
  56739. if (type === dracoModule.TRIANGULAR_MESH) {
  56740. var numFaces = geometry.num_faces();
  56741. var faceIndices = new dracoModule.DracoInt32Array();
  56742. try {
  56743. var indices = new Uint32Array(numFaces * 3);
  56744. for (var i = 0; i < numFaces; i++) {
  56745. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56746. var offset = i * 3;
  56747. indices[offset + 0] = faceIndices.GetValue(0);
  56748. indices[offset + 1] = faceIndices.GetValue(1);
  56749. indices[offset + 2] = faceIndices.GetValue(2);
  56750. }
  56751. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56752. }
  56753. finally {
  56754. dracoModule.destroy(faceIndices);
  56755. }
  56756. }
  56757. for (var kind in attributes) {
  56758. var uniqueId = attributes[kind];
  56759. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56760. var dracoData = new dracoModule.DracoFloat32Array();
  56761. try {
  56762. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56763. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56764. for (var i = 0; i < babylonData.length; i++) {
  56765. babylonData[i] = dracoData.GetValue(i);
  56766. }
  56767. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56768. }
  56769. finally {
  56770. dracoModule.destroy(dracoData);
  56771. }
  56772. }
  56773. }
  56774. finally {
  56775. if (geometry) {
  56776. dracoModule.destroy(geometry);
  56777. }
  56778. dracoModule.destroy(decoder);
  56779. dracoModule.destroy(buffer);
  56780. }
  56781. _self.postMessage("done");
  56782. };
  56783. _self.onmessage = function (event) {
  56784. switch (event.data.id) {
  56785. case "initDecoder": {
  56786. importScripts(event.data.url);
  56787. break;
  56788. }
  56789. case "decodeMesh": {
  56790. decodeMesh(event.data.data, event.data.attributes);
  56791. break;
  56792. }
  56793. }
  56794. };
  56795. };
  56796. DracoCompression._GetDefaultDecoderUrl = function () {
  56797. for (var i = 0; i < document.scripts.length; i++) {
  56798. if (document.scripts[i].type === "text/x-draco-decoder") {
  56799. return document.scripts[i].src;
  56800. }
  56801. }
  56802. return null;
  56803. };
  56804. /**
  56805. * Gets the url to the draco decoder if available.
  56806. */
  56807. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56808. return DracoCompression;
  56809. }());
  56810. BABYLON.DracoCompression = DracoCompression;
  56811. })(BABYLON || (BABYLON = {}));
  56812. //# sourceMappingURL=babylon.dracoCompression.js.map
  56813. var BABYLON;
  56814. (function (BABYLON) {
  56815. var AudioEngine = /** @class */ (function () {
  56816. function AudioEngine() {
  56817. this._audioContext = null;
  56818. this._audioContextInitialized = false;
  56819. this.canUseWebAudio = false;
  56820. this.WarnedWebAudioUnsupported = false;
  56821. this.unlocked = false;
  56822. this.isMP3supported = false;
  56823. this.isOGGsupported = false;
  56824. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56825. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56826. this.canUseWebAudio = true;
  56827. }
  56828. var audioElem = document.createElement('audio');
  56829. try {
  56830. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56831. this.isMP3supported = true;
  56832. }
  56833. }
  56834. catch (e) {
  56835. // protect error during capability check.
  56836. }
  56837. try {
  56838. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56839. this.isOGGsupported = true;
  56840. }
  56841. }
  56842. catch (e) {
  56843. // protect error during capability check.
  56844. }
  56845. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56846. this._unlockiOSaudio();
  56847. }
  56848. else {
  56849. this.unlocked = true;
  56850. }
  56851. }
  56852. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56853. get: function () {
  56854. if (!this._audioContextInitialized) {
  56855. this._initializeAudioContext();
  56856. }
  56857. return this._audioContext;
  56858. },
  56859. enumerable: true,
  56860. configurable: true
  56861. });
  56862. AudioEngine.prototype._unlockiOSaudio = function () {
  56863. var _this = this;
  56864. var unlockaudio = function () {
  56865. if (!_this.audioContext) {
  56866. return;
  56867. }
  56868. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56869. var source = _this.audioContext.createBufferSource();
  56870. source.buffer = buffer;
  56871. source.connect(_this.audioContext.destination);
  56872. source.start(0);
  56873. setTimeout(function () {
  56874. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56875. _this.unlocked = true;
  56876. window.removeEventListener('touchend', unlockaudio, false);
  56877. if (_this.onAudioUnlocked) {
  56878. _this.onAudioUnlocked();
  56879. }
  56880. }
  56881. }, 0);
  56882. };
  56883. window.addEventListener('touchend', unlockaudio, false);
  56884. };
  56885. AudioEngine.prototype._initializeAudioContext = function () {
  56886. try {
  56887. if (this.canUseWebAudio) {
  56888. this._audioContext = new AudioContext();
  56889. // create a global volume gain node
  56890. this.masterGain = this._audioContext.createGain();
  56891. this.masterGain.gain.value = 1;
  56892. this.masterGain.connect(this._audioContext.destination);
  56893. this._audioContextInitialized = true;
  56894. }
  56895. }
  56896. catch (e) {
  56897. this.canUseWebAudio = false;
  56898. BABYLON.Tools.Error("Web Audio: " + e.message);
  56899. }
  56900. };
  56901. AudioEngine.prototype.dispose = function () {
  56902. if (this.canUseWebAudio && this._audioContextInitialized) {
  56903. if (this._connectedAnalyser && this._audioContext) {
  56904. this._connectedAnalyser.stopDebugCanvas();
  56905. this._connectedAnalyser.dispose();
  56906. this.masterGain.disconnect();
  56907. this.masterGain.connect(this._audioContext.destination);
  56908. this._connectedAnalyser = null;
  56909. }
  56910. this.masterGain.gain.value = 1;
  56911. }
  56912. this.WarnedWebAudioUnsupported = false;
  56913. };
  56914. AudioEngine.prototype.getGlobalVolume = function () {
  56915. if (this.canUseWebAudio && this._audioContextInitialized) {
  56916. return this.masterGain.gain.value;
  56917. }
  56918. else {
  56919. return -1;
  56920. }
  56921. };
  56922. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56923. if (this.canUseWebAudio && this._audioContextInitialized) {
  56924. this.masterGain.gain.value = newVolume;
  56925. }
  56926. };
  56927. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56928. if (this._connectedAnalyser) {
  56929. this._connectedAnalyser.stopDebugCanvas();
  56930. }
  56931. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56932. this._connectedAnalyser = analyser;
  56933. this.masterGain.disconnect();
  56934. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56935. }
  56936. };
  56937. return AudioEngine;
  56938. }());
  56939. BABYLON.AudioEngine = AudioEngine;
  56940. })(BABYLON || (BABYLON = {}));
  56941. //# sourceMappingURL=babylon.audioEngine.js.map
  56942. var BABYLON;
  56943. (function (BABYLON) {
  56944. var Sound = /** @class */ (function () {
  56945. /**
  56946. * Create a sound and attach it to a scene
  56947. * @param name Name of your sound
  56948. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56949. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56950. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56951. */
  56952. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56953. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56954. var _this = this;
  56955. this.autoplay = false;
  56956. this.loop = false;
  56957. this.useCustomAttenuation = false;
  56958. this.spatialSound = false;
  56959. this.refDistance = 1;
  56960. this.rolloffFactor = 1;
  56961. this.maxDistance = 100;
  56962. this.distanceModel = "linear";
  56963. this._panningModel = "equalpower";
  56964. this._playbackRate = 1;
  56965. this._streaming = false;
  56966. this._startTime = 0;
  56967. this._startOffset = 0;
  56968. this._position = BABYLON.Vector3.Zero();
  56969. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56970. this._volume = 1;
  56971. this._isReadyToPlay = false;
  56972. this.isPlaying = false;
  56973. this.isPaused = false;
  56974. this._isDirectional = false;
  56975. // Used if you'd like to create a directional sound.
  56976. // If not set, the sound will be omnidirectional
  56977. this._coneInnerAngle = 360;
  56978. this._coneOuterAngle = 360;
  56979. this._coneOuterGain = 0;
  56980. this._isOutputConnected = false;
  56981. this._urlType = "Unknown";
  56982. this.name = name;
  56983. this._scene = scene;
  56984. this._readyToPlayCallback = readyToPlayCallback;
  56985. // Default custom attenuation function is a linear attenuation
  56986. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56987. if (currentDistance < maxDistance) {
  56988. return currentVolume * (1 - currentDistance / maxDistance);
  56989. }
  56990. else {
  56991. return 0;
  56992. }
  56993. };
  56994. if (options) {
  56995. this.autoplay = options.autoplay || false;
  56996. this.loop = options.loop || false;
  56997. // if volume === 0, we need another way to check this option
  56998. if (options.volume !== undefined) {
  56999. this._volume = options.volume;
  57000. }
  57001. this.spatialSound = options.spatialSound || false;
  57002. this.maxDistance = options.maxDistance || 100;
  57003. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57004. this.rolloffFactor = options.rolloffFactor || 1;
  57005. this.refDistance = options.refDistance || 1;
  57006. this.distanceModel = options.distanceModel || "linear";
  57007. this._playbackRate = options.playbackRate || 1;
  57008. this._streaming = options.streaming || false;
  57009. }
  57010. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57011. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57012. this._soundGain.gain.value = this._volume;
  57013. this._inputAudioNode = this._soundGain;
  57014. this._ouputAudioNode = this._soundGain;
  57015. if (this.spatialSound) {
  57016. this._createSpatialParameters();
  57017. }
  57018. this._scene.mainSoundTrack.AddSound(this);
  57019. var validParameter = true;
  57020. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57021. if (urlOrArrayBuffer) {
  57022. if (typeof (urlOrArrayBuffer) === "string")
  57023. this._urlType = "String";
  57024. if (Array.isArray(urlOrArrayBuffer))
  57025. this._urlType = "Array";
  57026. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57027. this._urlType = "ArrayBuffer";
  57028. var urls = [];
  57029. var codecSupportedFound = false;
  57030. switch (this._urlType) {
  57031. case "ArrayBuffer":
  57032. if (urlOrArrayBuffer.byteLength > 0) {
  57033. codecSupportedFound = true;
  57034. this._soundLoaded(urlOrArrayBuffer);
  57035. }
  57036. break;
  57037. case "String":
  57038. urls.push(urlOrArrayBuffer);
  57039. case "Array":
  57040. if (urls.length === 0)
  57041. urls = urlOrArrayBuffer;
  57042. // If we found a supported format, we load it immediately and stop the loop
  57043. for (var i = 0; i < urls.length; i++) {
  57044. var url = urls[i];
  57045. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57046. codecSupportedFound = true;
  57047. }
  57048. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57049. codecSupportedFound = true;
  57050. }
  57051. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57052. codecSupportedFound = true;
  57053. }
  57054. if (url.indexOf("blob:") !== -1) {
  57055. codecSupportedFound = true;
  57056. }
  57057. if (codecSupportedFound) {
  57058. // Loading sound using XHR2
  57059. if (!this._streaming) {
  57060. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57061. }
  57062. else {
  57063. this._htmlAudioElement = new Audio(url);
  57064. this._htmlAudioElement.controls = false;
  57065. this._htmlAudioElement.loop = this.loop;
  57066. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57067. this._htmlAudioElement.preload = "auto";
  57068. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57069. _this._isReadyToPlay = true;
  57070. if (_this.autoplay) {
  57071. _this.play();
  57072. }
  57073. if (_this._readyToPlayCallback) {
  57074. _this._readyToPlayCallback();
  57075. }
  57076. });
  57077. document.body.appendChild(this._htmlAudioElement);
  57078. }
  57079. break;
  57080. }
  57081. }
  57082. break;
  57083. default:
  57084. validParameter = false;
  57085. break;
  57086. }
  57087. if (!validParameter) {
  57088. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57089. }
  57090. else {
  57091. if (!codecSupportedFound) {
  57092. this._isReadyToPlay = true;
  57093. // Simulating a ready to play event to avoid breaking code path
  57094. if (this._readyToPlayCallback) {
  57095. window.setTimeout(function () {
  57096. if (_this._readyToPlayCallback) {
  57097. _this._readyToPlayCallback();
  57098. }
  57099. }, 1000);
  57100. }
  57101. }
  57102. }
  57103. }
  57104. }
  57105. else {
  57106. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57107. this._scene.mainSoundTrack.AddSound(this);
  57108. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57109. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57110. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57111. }
  57112. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57113. if (this._readyToPlayCallback) {
  57114. window.setTimeout(function () {
  57115. if (_this._readyToPlayCallback) {
  57116. _this._readyToPlayCallback();
  57117. }
  57118. }, 1000);
  57119. }
  57120. }
  57121. }
  57122. Sound.prototype.dispose = function () {
  57123. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57124. if (this.isPlaying) {
  57125. this.stop();
  57126. }
  57127. this._isReadyToPlay = false;
  57128. if (this.soundTrackId === -1) {
  57129. this._scene.mainSoundTrack.RemoveSound(this);
  57130. }
  57131. else {
  57132. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57133. }
  57134. if (this._soundGain) {
  57135. this._soundGain.disconnect();
  57136. this._soundGain = null;
  57137. }
  57138. if (this._soundPanner) {
  57139. this._soundPanner.disconnect();
  57140. this._soundPanner = null;
  57141. }
  57142. if (this._soundSource) {
  57143. this._soundSource.disconnect();
  57144. this._soundSource = null;
  57145. }
  57146. this._audioBuffer = null;
  57147. if (this._htmlAudioElement) {
  57148. this._htmlAudioElement.pause();
  57149. this._htmlAudioElement.src = "";
  57150. document.body.removeChild(this._htmlAudioElement);
  57151. }
  57152. if (this._connectedMesh && this._registerFunc) {
  57153. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57154. this._connectedMesh = null;
  57155. }
  57156. }
  57157. };
  57158. Sound.prototype.isReady = function () {
  57159. return this._isReadyToPlay;
  57160. };
  57161. Sound.prototype._soundLoaded = function (audioData) {
  57162. var _this = this;
  57163. if (!BABYLON.Engine.audioEngine.audioContext) {
  57164. return;
  57165. }
  57166. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57167. _this._audioBuffer = buffer;
  57168. _this._isReadyToPlay = true;
  57169. if (_this.autoplay) {
  57170. _this.play();
  57171. }
  57172. if (_this._readyToPlayCallback) {
  57173. _this._readyToPlayCallback();
  57174. }
  57175. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57176. };
  57177. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57178. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57179. this._audioBuffer = audioBuffer;
  57180. this._isReadyToPlay = true;
  57181. }
  57182. };
  57183. Sound.prototype.updateOptions = function (options) {
  57184. if (options) {
  57185. this.loop = options.loop || this.loop;
  57186. this.maxDistance = options.maxDistance || this.maxDistance;
  57187. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57188. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57189. this.refDistance = options.refDistance || this.refDistance;
  57190. this.distanceModel = options.distanceModel || this.distanceModel;
  57191. this._playbackRate = options.playbackRate || this._playbackRate;
  57192. this._updateSpatialParameters();
  57193. if (this.isPlaying) {
  57194. if (this._streaming) {
  57195. this._htmlAudioElement.playbackRate = this._playbackRate;
  57196. }
  57197. else {
  57198. if (this._soundSource) {
  57199. this._soundSource.playbackRate.value = this._playbackRate;
  57200. }
  57201. }
  57202. }
  57203. }
  57204. };
  57205. Sound.prototype._createSpatialParameters = function () {
  57206. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57207. if (this._scene.headphone) {
  57208. this._panningModel = "HRTF";
  57209. }
  57210. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57211. this._updateSpatialParameters();
  57212. this._soundPanner.connect(this._ouputAudioNode);
  57213. this._inputAudioNode = this._soundPanner;
  57214. }
  57215. };
  57216. Sound.prototype._updateSpatialParameters = function () {
  57217. if (this.spatialSound && this._soundPanner) {
  57218. if (this.useCustomAttenuation) {
  57219. // Tricks to disable in a way embedded Web Audio attenuation
  57220. this._soundPanner.distanceModel = "linear";
  57221. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57222. this._soundPanner.refDistance = 1;
  57223. this._soundPanner.rolloffFactor = 1;
  57224. this._soundPanner.panningModel = this._panningModel;
  57225. }
  57226. else {
  57227. this._soundPanner.distanceModel = this.distanceModel;
  57228. this._soundPanner.maxDistance = this.maxDistance;
  57229. this._soundPanner.refDistance = this.refDistance;
  57230. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57231. this._soundPanner.panningModel = this._panningModel;
  57232. }
  57233. }
  57234. };
  57235. Sound.prototype.switchPanningModelToHRTF = function () {
  57236. this._panningModel = "HRTF";
  57237. this._switchPanningModel();
  57238. };
  57239. Sound.prototype.switchPanningModelToEqualPower = function () {
  57240. this._panningModel = "equalpower";
  57241. this._switchPanningModel();
  57242. };
  57243. Sound.prototype._switchPanningModel = function () {
  57244. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57245. this._soundPanner.panningModel = this._panningModel;
  57246. }
  57247. };
  57248. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57249. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57250. if (this._isOutputConnected) {
  57251. this._ouputAudioNode.disconnect();
  57252. }
  57253. this._ouputAudioNode.connect(soundTrackAudioNode);
  57254. this._isOutputConnected = true;
  57255. }
  57256. };
  57257. /**
  57258. * Transform this sound into a directional source
  57259. * @param coneInnerAngle Size of the inner cone in degree
  57260. * @param coneOuterAngle Size of the outer cone in degree
  57261. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57262. */
  57263. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57264. if (coneOuterAngle < coneInnerAngle) {
  57265. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57266. return;
  57267. }
  57268. this._coneInnerAngle = coneInnerAngle;
  57269. this._coneOuterAngle = coneOuterAngle;
  57270. this._coneOuterGain = coneOuterGain;
  57271. this._isDirectional = true;
  57272. if (this.isPlaying && this.loop) {
  57273. this.stop();
  57274. this.play();
  57275. }
  57276. };
  57277. Sound.prototype.setPosition = function (newPosition) {
  57278. this._position = newPosition;
  57279. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57280. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57281. }
  57282. };
  57283. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57284. this._localDirection = newLocalDirection;
  57285. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57286. this._updateDirection();
  57287. }
  57288. };
  57289. Sound.prototype._updateDirection = function () {
  57290. if (!this._connectedMesh || !this._soundPanner) {
  57291. return;
  57292. }
  57293. var mat = this._connectedMesh.getWorldMatrix();
  57294. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57295. direction.normalize();
  57296. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57297. };
  57298. Sound.prototype.updateDistanceFromListener = function () {
  57299. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57300. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57301. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57302. }
  57303. };
  57304. Sound.prototype.setAttenuationFunction = function (callback) {
  57305. this._customAttenuationFunction = callback;
  57306. };
  57307. /**
  57308. * Play the sound
  57309. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57310. * @param offset (optional) Start the sound setting it at a specific time
  57311. */
  57312. Sound.prototype.play = function (time, offset) {
  57313. var _this = this;
  57314. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57315. try {
  57316. if (this._startOffset < 0) {
  57317. time = -this._startOffset;
  57318. this._startOffset = 0;
  57319. }
  57320. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57321. if (!this._soundSource || !this._streamingSource) {
  57322. if (this.spatialSound && this._soundPanner) {
  57323. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57324. if (this._isDirectional) {
  57325. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57326. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57327. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57328. if (this._connectedMesh) {
  57329. this._updateDirection();
  57330. }
  57331. else {
  57332. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57333. }
  57334. }
  57335. }
  57336. }
  57337. if (this._streaming) {
  57338. if (!this._streamingSource) {
  57339. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57340. this._htmlAudioElement.onended = function () { _this._onended(); };
  57341. this._htmlAudioElement.playbackRate = this._playbackRate;
  57342. }
  57343. this._streamingSource.disconnect();
  57344. this._streamingSource.connect(this._inputAudioNode);
  57345. this._htmlAudioElement.play();
  57346. }
  57347. else {
  57348. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57349. this._soundSource.buffer = this._audioBuffer;
  57350. this._soundSource.connect(this._inputAudioNode);
  57351. this._soundSource.loop = this.loop;
  57352. this._soundSource.playbackRate.value = this._playbackRate;
  57353. this._soundSource.onended = function () { _this._onended(); };
  57354. if (this._soundSource.buffer) {
  57355. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57356. }
  57357. }
  57358. this._startTime = startTime;
  57359. this.isPlaying = true;
  57360. this.isPaused = false;
  57361. }
  57362. catch (ex) {
  57363. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57364. }
  57365. }
  57366. };
  57367. Sound.prototype._onended = function () {
  57368. this.isPlaying = false;
  57369. if (this.onended) {
  57370. this.onended();
  57371. }
  57372. };
  57373. /**
  57374. * Stop the sound
  57375. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57376. */
  57377. Sound.prototype.stop = function (time) {
  57378. if (this.isPlaying) {
  57379. if (this._streaming) {
  57380. this._htmlAudioElement.pause();
  57381. // Test needed for Firefox or it will generate an Invalid State Error
  57382. if (this._htmlAudioElement.currentTime > 0) {
  57383. this._htmlAudioElement.currentTime = 0;
  57384. }
  57385. }
  57386. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57387. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57388. this._soundSource.stop(stopTime);
  57389. this._soundSource.onended = function () { };
  57390. if (!this.isPaused) {
  57391. this._startOffset = 0;
  57392. }
  57393. }
  57394. this.isPlaying = false;
  57395. }
  57396. };
  57397. Sound.prototype.pause = function () {
  57398. if (this.isPlaying) {
  57399. this.isPaused = true;
  57400. if (this._streaming) {
  57401. this._htmlAudioElement.pause();
  57402. }
  57403. else if (BABYLON.Engine.audioEngine.audioContext) {
  57404. this.stop(0);
  57405. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57406. }
  57407. }
  57408. };
  57409. Sound.prototype.setVolume = function (newVolume, time) {
  57410. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57411. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57412. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57413. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57414. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57415. }
  57416. else {
  57417. this._soundGain.gain.value = newVolume;
  57418. }
  57419. }
  57420. this._volume = newVolume;
  57421. };
  57422. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57423. this._playbackRate = newPlaybackRate;
  57424. if (this.isPlaying) {
  57425. if (this._streaming) {
  57426. this._htmlAudioElement.playbackRate = this._playbackRate;
  57427. }
  57428. else if (this._soundSource) {
  57429. this._soundSource.playbackRate.value = this._playbackRate;
  57430. }
  57431. }
  57432. };
  57433. Sound.prototype.getVolume = function () {
  57434. return this._volume;
  57435. };
  57436. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57437. var _this = this;
  57438. if (this._connectedMesh && this._registerFunc) {
  57439. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57440. this._registerFunc = null;
  57441. }
  57442. this._connectedMesh = meshToConnectTo;
  57443. if (!this.spatialSound) {
  57444. this.spatialSound = true;
  57445. this._createSpatialParameters();
  57446. if (this.isPlaying && this.loop) {
  57447. this.stop();
  57448. this.play();
  57449. }
  57450. }
  57451. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57452. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57453. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57454. };
  57455. Sound.prototype.detachFromMesh = function () {
  57456. if (this._connectedMesh && this._registerFunc) {
  57457. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57458. this._registerFunc = null;
  57459. this._connectedMesh = null;
  57460. }
  57461. };
  57462. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57463. if (!node.getBoundingInfo) {
  57464. return;
  57465. }
  57466. var mesh = node;
  57467. var boundingInfo = mesh.getBoundingInfo();
  57468. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57469. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57470. this._updateDirection();
  57471. }
  57472. };
  57473. Sound.prototype.clone = function () {
  57474. var _this = this;
  57475. if (!this._streaming) {
  57476. var setBufferAndRun = function () {
  57477. if (_this._isReadyToPlay) {
  57478. clonedSound._audioBuffer = _this.getAudioBuffer();
  57479. clonedSound._isReadyToPlay = true;
  57480. if (clonedSound.autoplay) {
  57481. clonedSound.play();
  57482. }
  57483. }
  57484. else {
  57485. window.setTimeout(setBufferAndRun, 300);
  57486. }
  57487. };
  57488. var currentOptions = {
  57489. autoplay: this.autoplay, loop: this.loop,
  57490. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57491. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57492. refDistance: this.refDistance, distanceModel: this.distanceModel
  57493. };
  57494. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57495. if (this.useCustomAttenuation) {
  57496. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57497. }
  57498. clonedSound.setPosition(this._position);
  57499. clonedSound.setPlaybackRate(this._playbackRate);
  57500. setBufferAndRun();
  57501. return clonedSound;
  57502. }
  57503. else {
  57504. return null;
  57505. }
  57506. };
  57507. Sound.prototype.getAudioBuffer = function () {
  57508. return this._audioBuffer;
  57509. };
  57510. Sound.prototype.serialize = function () {
  57511. var serializationObject = {
  57512. name: this.name,
  57513. url: this.name,
  57514. autoplay: this.autoplay,
  57515. loop: this.loop,
  57516. volume: this._volume,
  57517. spatialSound: this.spatialSound,
  57518. maxDistance: this.maxDistance,
  57519. rolloffFactor: this.rolloffFactor,
  57520. refDistance: this.refDistance,
  57521. distanceModel: this.distanceModel,
  57522. playbackRate: this._playbackRate,
  57523. panningModel: this._panningModel,
  57524. soundTrackId: this.soundTrackId
  57525. };
  57526. if (this.spatialSound) {
  57527. if (this._connectedMesh)
  57528. serializationObject.connectedMeshId = this._connectedMesh.id;
  57529. serializationObject.position = this._position.asArray();
  57530. serializationObject.refDistance = this.refDistance;
  57531. serializationObject.distanceModel = this.distanceModel;
  57532. serializationObject.isDirectional = this._isDirectional;
  57533. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57534. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57535. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57536. serializationObject.coneOuterGain = this._coneOuterGain;
  57537. }
  57538. return serializationObject;
  57539. };
  57540. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57541. var soundName = parsedSound.name;
  57542. var soundUrl;
  57543. if (parsedSound.url) {
  57544. soundUrl = rootUrl + parsedSound.url;
  57545. }
  57546. else {
  57547. soundUrl = rootUrl + soundName;
  57548. }
  57549. var options = {
  57550. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57551. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57552. rolloffFactor: parsedSound.rolloffFactor,
  57553. refDistance: parsedSound.refDistance,
  57554. distanceModel: parsedSound.distanceModel,
  57555. playbackRate: parsedSound.playbackRate
  57556. };
  57557. var newSound;
  57558. if (!sourceSound) {
  57559. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57560. scene._addPendingData(newSound);
  57561. }
  57562. else {
  57563. var setBufferAndRun = function () {
  57564. if (sourceSound._isReadyToPlay) {
  57565. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57566. newSound._isReadyToPlay = true;
  57567. if (newSound.autoplay) {
  57568. newSound.play();
  57569. }
  57570. }
  57571. else {
  57572. window.setTimeout(setBufferAndRun, 300);
  57573. }
  57574. };
  57575. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57576. setBufferAndRun();
  57577. }
  57578. if (parsedSound.position) {
  57579. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57580. newSound.setPosition(soundPosition);
  57581. }
  57582. if (parsedSound.isDirectional) {
  57583. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57584. if (parsedSound.localDirectionToMesh) {
  57585. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57586. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57587. }
  57588. }
  57589. if (parsedSound.connectedMeshId) {
  57590. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57591. if (connectedMesh) {
  57592. newSound.attachToMesh(connectedMesh);
  57593. }
  57594. }
  57595. return newSound;
  57596. };
  57597. return Sound;
  57598. }());
  57599. BABYLON.Sound = Sound;
  57600. })(BABYLON || (BABYLON = {}));
  57601. //# sourceMappingURL=babylon.sound.js.map
  57602. var BABYLON;
  57603. (function (BABYLON) {
  57604. var SoundTrack = /** @class */ (function () {
  57605. function SoundTrack(scene, options) {
  57606. this.id = -1;
  57607. this._isMainTrack = false;
  57608. this._isInitialized = false;
  57609. this._scene = scene;
  57610. this.soundCollection = new Array();
  57611. this._options = options;
  57612. if (!this._isMainTrack) {
  57613. this._scene.soundTracks.push(this);
  57614. this.id = this._scene.soundTracks.length - 1;
  57615. }
  57616. }
  57617. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57618. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57619. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57620. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57621. if (this._options) {
  57622. if (this._options.volume) {
  57623. this._outputAudioNode.gain.value = this._options.volume;
  57624. }
  57625. if (this._options.mainTrack) {
  57626. this._isMainTrack = this._options.mainTrack;
  57627. }
  57628. }
  57629. this._isInitialized = true;
  57630. }
  57631. };
  57632. SoundTrack.prototype.dispose = function () {
  57633. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57634. if (this._connectedAnalyser) {
  57635. this._connectedAnalyser.stopDebugCanvas();
  57636. }
  57637. while (this.soundCollection.length) {
  57638. this.soundCollection[0].dispose();
  57639. }
  57640. if (this._outputAudioNode) {
  57641. this._outputAudioNode.disconnect();
  57642. }
  57643. this._outputAudioNode = null;
  57644. }
  57645. };
  57646. SoundTrack.prototype.AddSound = function (sound) {
  57647. if (!this._isInitialized) {
  57648. this._initializeSoundTrackAudioGraph();
  57649. }
  57650. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57651. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57652. }
  57653. if (sound.soundTrackId) {
  57654. if (sound.soundTrackId === -1) {
  57655. this._scene.mainSoundTrack.RemoveSound(sound);
  57656. }
  57657. else {
  57658. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57659. }
  57660. }
  57661. this.soundCollection.push(sound);
  57662. sound.soundTrackId = this.id;
  57663. };
  57664. SoundTrack.prototype.RemoveSound = function (sound) {
  57665. var index = this.soundCollection.indexOf(sound);
  57666. if (index !== -1) {
  57667. this.soundCollection.splice(index, 1);
  57668. }
  57669. };
  57670. SoundTrack.prototype.setVolume = function (newVolume) {
  57671. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57672. this._outputAudioNode.gain.value = newVolume;
  57673. }
  57674. };
  57675. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57676. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57677. for (var i = 0; i < this.soundCollection.length; i++) {
  57678. this.soundCollection[i].switchPanningModelToHRTF();
  57679. }
  57680. }
  57681. };
  57682. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57683. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57684. for (var i = 0; i < this.soundCollection.length; i++) {
  57685. this.soundCollection[i].switchPanningModelToEqualPower();
  57686. }
  57687. }
  57688. };
  57689. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57690. if (this._connectedAnalyser) {
  57691. this._connectedAnalyser.stopDebugCanvas();
  57692. }
  57693. this._connectedAnalyser = analyser;
  57694. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57695. this._outputAudioNode.disconnect();
  57696. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57697. }
  57698. };
  57699. return SoundTrack;
  57700. }());
  57701. BABYLON.SoundTrack = SoundTrack;
  57702. })(BABYLON || (BABYLON = {}));
  57703. //# sourceMappingURL=babylon.soundtrack.js.map
  57704. var BABYLON;
  57705. (function (BABYLON) {
  57706. var Analyser = /** @class */ (function () {
  57707. function Analyser(scene) {
  57708. this.SMOOTHING = 0.75;
  57709. this.FFT_SIZE = 512;
  57710. this.BARGRAPHAMPLITUDE = 256;
  57711. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57712. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57713. this._scene = scene;
  57714. this._audioEngine = BABYLON.Engine.audioEngine;
  57715. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57716. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57717. this._webAudioAnalyser.minDecibels = -140;
  57718. this._webAudioAnalyser.maxDecibels = 0;
  57719. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57720. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57721. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57722. }
  57723. }
  57724. Analyser.prototype.getFrequencyBinCount = function () {
  57725. if (this._audioEngine.canUseWebAudio) {
  57726. return this._webAudioAnalyser.frequencyBinCount;
  57727. }
  57728. else {
  57729. return 0;
  57730. }
  57731. };
  57732. Analyser.prototype.getByteFrequencyData = function () {
  57733. if (this._audioEngine.canUseWebAudio) {
  57734. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57735. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57736. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57737. }
  57738. return this._byteFreqs;
  57739. };
  57740. Analyser.prototype.getByteTimeDomainData = function () {
  57741. if (this._audioEngine.canUseWebAudio) {
  57742. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57743. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57744. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57745. }
  57746. return this._byteTime;
  57747. };
  57748. Analyser.prototype.getFloatFrequencyData = function () {
  57749. if (this._audioEngine.canUseWebAudio) {
  57750. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57751. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57752. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57753. }
  57754. return this._floatFreqs;
  57755. };
  57756. Analyser.prototype.drawDebugCanvas = function () {
  57757. var _this = this;
  57758. if (this._audioEngine.canUseWebAudio) {
  57759. if (!this._debugCanvas) {
  57760. this._debugCanvas = document.createElement("canvas");
  57761. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57762. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57763. this._debugCanvas.style.position = "absolute";
  57764. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57765. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57766. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57767. document.body.appendChild(this._debugCanvas);
  57768. this._registerFunc = function () {
  57769. _this.drawDebugCanvas();
  57770. };
  57771. this._scene.registerBeforeRender(this._registerFunc);
  57772. }
  57773. if (this._registerFunc && this._debugCanvasContext) {
  57774. var workingArray = this.getByteFrequencyData();
  57775. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57776. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57777. // Draw the frequency domain chart.
  57778. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57779. var value = workingArray[i];
  57780. var percent = value / this.BARGRAPHAMPLITUDE;
  57781. var height = this.DEBUGCANVASSIZE.height * percent;
  57782. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57783. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57784. var hue = i / this.getFrequencyBinCount() * 360;
  57785. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57786. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57787. }
  57788. }
  57789. }
  57790. };
  57791. Analyser.prototype.stopDebugCanvas = function () {
  57792. if (this._debugCanvas) {
  57793. if (this._registerFunc) {
  57794. this._scene.unregisterBeforeRender(this._registerFunc);
  57795. this._registerFunc = null;
  57796. }
  57797. document.body.removeChild(this._debugCanvas);
  57798. this._debugCanvas = null;
  57799. this._debugCanvasContext = null;
  57800. }
  57801. };
  57802. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57803. if (this._audioEngine.canUseWebAudio) {
  57804. inputAudioNode.connect(this._webAudioAnalyser);
  57805. this._webAudioAnalyser.connect(outputAudioNode);
  57806. }
  57807. };
  57808. Analyser.prototype.dispose = function () {
  57809. if (this._audioEngine.canUseWebAudio) {
  57810. this._webAudioAnalyser.disconnect();
  57811. }
  57812. };
  57813. return Analyser;
  57814. }());
  57815. BABYLON.Analyser = Analyser;
  57816. })(BABYLON || (BABYLON = {}));
  57817. //# sourceMappingURL=babylon.analyser.js.map
  57818. var BABYLON;
  57819. (function (BABYLON) {
  57820. var CubeTexture = /** @class */ (function (_super) {
  57821. __extends(CubeTexture, _super);
  57822. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57823. if (extensions === void 0) { extensions = null; }
  57824. if (noMipmap === void 0) { noMipmap = false; }
  57825. if (files === void 0) { files = null; }
  57826. if (onLoad === void 0) { onLoad = null; }
  57827. if (onError === void 0) { onError = null; }
  57828. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57829. if (prefiltered === void 0) { prefiltered = false; }
  57830. if (forcedExtension === void 0) { forcedExtension = null; }
  57831. var _this = _super.call(this, scene) || this;
  57832. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57833. /**
  57834. * Gets or sets the center of the bounding box associated with the cube texture
  57835. * It must define where the camera used to render the texture was set
  57836. */
  57837. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57838. _this.name = rootUrl;
  57839. _this.url = rootUrl;
  57840. _this._noMipmap = noMipmap;
  57841. _this.hasAlpha = false;
  57842. _this._format = format;
  57843. _this._prefiltered = prefiltered;
  57844. _this.isCube = true;
  57845. _this._textureMatrix = BABYLON.Matrix.Identity();
  57846. if (prefiltered) {
  57847. _this.gammaSpace = false;
  57848. }
  57849. if (!rootUrl && !files) {
  57850. return _this;
  57851. }
  57852. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57853. var lastDot = rootUrl.lastIndexOf(".");
  57854. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57855. var isDDS = (extension === ".dds");
  57856. if (!files) {
  57857. if (!isDDS && !extensions) {
  57858. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57859. }
  57860. files = [];
  57861. if (extensions) {
  57862. for (var index = 0; index < extensions.length; index++) {
  57863. files.push(rootUrl + extensions[index]);
  57864. }
  57865. }
  57866. }
  57867. _this._files = files;
  57868. if (!_this._texture) {
  57869. if (!scene.useDelayedTextureLoading) {
  57870. if (prefiltered) {
  57871. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57872. }
  57873. else {
  57874. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57875. }
  57876. }
  57877. else {
  57878. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57879. }
  57880. }
  57881. else if (onLoad) {
  57882. if (_this._texture.isReady) {
  57883. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57884. }
  57885. else {
  57886. _this._texture.onLoadedObservable.add(onLoad);
  57887. }
  57888. }
  57889. return _this;
  57890. }
  57891. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57892. get: function () {
  57893. return this._boundingBoxSize;
  57894. },
  57895. /**
  57896. * Gets or sets the size of the bounding box associated with the cube texture
  57897. * When defined, the cubemap will switch to local mode
  57898. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57899. * @example https://www.babylonjs-playground.com/#RNASML
  57900. */
  57901. set: function (value) {
  57902. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57903. return;
  57904. }
  57905. this._boundingBoxSize = value;
  57906. var scene = this.getScene();
  57907. if (scene) {
  57908. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57909. }
  57910. },
  57911. enumerable: true,
  57912. configurable: true
  57913. });
  57914. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57915. var rootUrlKey = "";
  57916. files.forEach(function (url) { return rootUrlKey += url; });
  57917. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57918. };
  57919. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57920. if (forcedExtension === void 0) { forcedExtension = null; }
  57921. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57922. };
  57923. // Methods
  57924. CubeTexture.prototype.delayLoad = function () {
  57925. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57926. return;
  57927. }
  57928. var scene = this.getScene();
  57929. if (!scene) {
  57930. return;
  57931. }
  57932. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57933. this._texture = this._getFromCache(this.url, this._noMipmap);
  57934. if (!this._texture) {
  57935. if (this._prefiltered) {
  57936. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57937. }
  57938. else {
  57939. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57940. }
  57941. }
  57942. };
  57943. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57944. return this._textureMatrix;
  57945. };
  57946. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57947. this._textureMatrix = value;
  57948. };
  57949. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57950. var texture = BABYLON.SerializationHelper.Parse(function () {
  57951. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57952. }, parsedTexture, scene);
  57953. // Local Cubemaps
  57954. if (parsedTexture.boundingBoxPosition) {
  57955. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57956. }
  57957. if (parsedTexture.boundingBoxSize) {
  57958. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57959. }
  57960. // Animations
  57961. if (parsedTexture.animations) {
  57962. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57963. var parsedAnimation = parsedTexture.animations[animationIndex];
  57964. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57965. }
  57966. }
  57967. return texture;
  57968. };
  57969. CubeTexture.prototype.clone = function () {
  57970. var _this = this;
  57971. return BABYLON.SerializationHelper.Clone(function () {
  57972. var scene = _this.getScene();
  57973. if (!scene) {
  57974. return _this;
  57975. }
  57976. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57977. }, this);
  57978. };
  57979. return CubeTexture;
  57980. }(BABYLON.BaseTexture));
  57981. BABYLON.CubeTexture = CubeTexture;
  57982. })(BABYLON || (BABYLON = {}));
  57983. //# sourceMappingURL=babylon.cubeTexture.js.map
  57984. var BABYLON;
  57985. (function (BABYLON) {
  57986. var RenderTargetTexture = /** @class */ (function (_super) {
  57987. __extends(RenderTargetTexture, _super);
  57988. /**
  57989. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57990. * or used a shadow, depth texture...
  57991. * @param name The friendly name of the texture
  57992. * @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)
  57993. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57994. * @param generateMipMaps True if mip maps need to be generated after render.
  57995. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57996. * @param type The type of the buffer in the RTT (int, half float, float...)
  57997. * @param isCube True if a cube texture needs to be created
  57998. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57999. * @param generateDepthBuffer True to generate a depth buffer
  58000. * @param generateStencilBuffer True to generate a stencil buffer
  58001. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58002. */
  58003. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58004. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58005. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58006. if (isCube === void 0) { isCube = false; }
  58007. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58008. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58009. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58010. if (isMulti === void 0) { isMulti = false; }
  58011. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58012. _this.isCube = isCube;
  58013. /**
  58014. * Use this list to define the list of mesh you want to render.
  58015. */
  58016. _this.renderList = new Array();
  58017. _this.renderParticles = true;
  58018. _this.renderSprites = false;
  58019. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58020. _this.ignoreCameraViewport = false;
  58021. // Events
  58022. /**
  58023. * An event triggered when the texture is unbind.
  58024. * @type {BABYLON.Observable}
  58025. */
  58026. _this.onBeforeBindObservable = new BABYLON.Observable();
  58027. /**
  58028. * An event triggered when the texture is unbind.
  58029. * @type {BABYLON.Observable}
  58030. */
  58031. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58032. /**
  58033. * An event triggered before rendering the texture
  58034. * @type {BABYLON.Observable}
  58035. */
  58036. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58037. /**
  58038. * An event triggered after rendering the texture
  58039. * @type {BABYLON.Observable}
  58040. */
  58041. _this.onAfterRenderObservable = new BABYLON.Observable();
  58042. /**
  58043. * An event triggered after the texture clear
  58044. * @type {BABYLON.Observable}
  58045. */
  58046. _this.onClearObservable = new BABYLON.Observable();
  58047. _this._currentRefreshId = -1;
  58048. _this._refreshRate = 1;
  58049. _this._samples = 1;
  58050. /**
  58051. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58052. * It must define where the camera used to render the texture is set
  58053. */
  58054. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58055. scene = _this.getScene();
  58056. if (!scene) {
  58057. return _this;
  58058. }
  58059. _this._engine = scene.getEngine();
  58060. _this.name = name;
  58061. _this.isRenderTarget = true;
  58062. _this._initialSizeParameter = size;
  58063. _this._processSizeParameter(size);
  58064. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58065. });
  58066. _this._generateMipMaps = generateMipMaps ? true : false;
  58067. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58068. // Rendering groups
  58069. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58070. if (isMulti) {
  58071. return _this;
  58072. }
  58073. _this._renderTargetOptions = {
  58074. generateMipMaps: generateMipMaps,
  58075. type: type,
  58076. samplingMode: samplingMode,
  58077. generateDepthBuffer: generateDepthBuffer,
  58078. generateStencilBuffer: generateStencilBuffer
  58079. };
  58080. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58081. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58082. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58083. }
  58084. if (isCube) {
  58085. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58086. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58087. _this._textureMatrix = BABYLON.Matrix.Identity();
  58088. }
  58089. else {
  58090. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58091. }
  58092. return _this;
  58093. }
  58094. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58095. get: function () {
  58096. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58097. },
  58098. enumerable: true,
  58099. configurable: true
  58100. });
  58101. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58102. get: function () {
  58103. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58104. },
  58105. enumerable: true,
  58106. configurable: true
  58107. });
  58108. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58109. get: function () {
  58110. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58111. },
  58112. enumerable: true,
  58113. configurable: true
  58114. });
  58115. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58116. set: function (callback) {
  58117. if (this._onAfterUnbindObserver) {
  58118. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58119. }
  58120. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58121. },
  58122. enumerable: true,
  58123. configurable: true
  58124. });
  58125. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58126. set: function (callback) {
  58127. if (this._onBeforeRenderObserver) {
  58128. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58129. }
  58130. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58131. },
  58132. enumerable: true,
  58133. configurable: true
  58134. });
  58135. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58136. set: function (callback) {
  58137. if (this._onAfterRenderObserver) {
  58138. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58139. }
  58140. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58141. },
  58142. enumerable: true,
  58143. configurable: true
  58144. });
  58145. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58146. set: function (callback) {
  58147. if (this._onClearObserver) {
  58148. this.onClearObservable.remove(this._onClearObserver);
  58149. }
  58150. this._onClearObserver = this.onClearObservable.add(callback);
  58151. },
  58152. enumerable: true,
  58153. configurable: true
  58154. });
  58155. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58156. get: function () {
  58157. return this._renderTargetOptions;
  58158. },
  58159. enumerable: true,
  58160. configurable: true
  58161. });
  58162. RenderTargetTexture.prototype._onRatioRescale = function () {
  58163. if (this._sizeRatio) {
  58164. this.resize(this._initialSizeParameter);
  58165. }
  58166. };
  58167. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58168. get: function () {
  58169. return this._boundingBoxSize;
  58170. },
  58171. /**
  58172. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58173. * When defined, the cubemap will switch to local mode
  58174. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58175. * @example https://www.babylonjs-playground.com/#RNASML
  58176. */
  58177. set: function (value) {
  58178. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58179. return;
  58180. }
  58181. this._boundingBoxSize = value;
  58182. var scene = this.getScene();
  58183. if (scene) {
  58184. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58185. }
  58186. },
  58187. enumerable: true,
  58188. configurable: true
  58189. });
  58190. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58191. if (size.ratio) {
  58192. this._sizeRatio = size.ratio;
  58193. this._size = {
  58194. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58195. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58196. };
  58197. }
  58198. else {
  58199. this._size = size;
  58200. }
  58201. };
  58202. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58203. get: function () {
  58204. return this._samples;
  58205. },
  58206. set: function (value) {
  58207. if (this._samples === value) {
  58208. return;
  58209. }
  58210. var scene = this.getScene();
  58211. if (!scene) {
  58212. return;
  58213. }
  58214. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58215. },
  58216. enumerable: true,
  58217. configurable: true
  58218. });
  58219. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58220. this._currentRefreshId = -1;
  58221. };
  58222. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58223. get: function () {
  58224. return this._refreshRate;
  58225. },
  58226. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58227. set: function (value) {
  58228. this._refreshRate = value;
  58229. this.resetRefreshCounter();
  58230. },
  58231. enumerable: true,
  58232. configurable: true
  58233. });
  58234. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58235. if (!this._postProcessManager) {
  58236. var scene = this.getScene();
  58237. if (!scene) {
  58238. return;
  58239. }
  58240. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58241. this._postProcesses = new Array();
  58242. }
  58243. this._postProcesses.push(postProcess);
  58244. this._postProcesses[0].autoClear = false;
  58245. };
  58246. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58247. if (!this._postProcesses) {
  58248. return;
  58249. }
  58250. if (dispose) {
  58251. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58252. var postProcess = _a[_i];
  58253. postProcess.dispose();
  58254. }
  58255. }
  58256. this._postProcesses = [];
  58257. };
  58258. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58259. if (!this._postProcesses) {
  58260. return;
  58261. }
  58262. var index = this._postProcesses.indexOf(postProcess);
  58263. if (index === -1) {
  58264. return;
  58265. }
  58266. this._postProcesses.splice(index, 1);
  58267. if (this._postProcesses.length > 0) {
  58268. this._postProcesses[0].autoClear = false;
  58269. }
  58270. };
  58271. RenderTargetTexture.prototype._shouldRender = function () {
  58272. if (this._currentRefreshId === -1) {
  58273. this._currentRefreshId = 1;
  58274. return true;
  58275. }
  58276. if (this.refreshRate === this._currentRefreshId) {
  58277. this._currentRefreshId = 1;
  58278. return true;
  58279. }
  58280. this._currentRefreshId++;
  58281. return false;
  58282. };
  58283. RenderTargetTexture.prototype.getRenderSize = function () {
  58284. if (this._size.width) {
  58285. return this._size.width;
  58286. }
  58287. return this._size;
  58288. };
  58289. RenderTargetTexture.prototype.getRenderWidth = function () {
  58290. if (this._size.width) {
  58291. return this._size.width;
  58292. }
  58293. return this._size;
  58294. };
  58295. RenderTargetTexture.prototype.getRenderHeight = function () {
  58296. if (this._size.width) {
  58297. return this._size.height;
  58298. }
  58299. return this._size;
  58300. };
  58301. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58302. get: function () {
  58303. return true;
  58304. },
  58305. enumerable: true,
  58306. configurable: true
  58307. });
  58308. RenderTargetTexture.prototype.scale = function (ratio) {
  58309. var newSize = this.getRenderSize() * ratio;
  58310. this.resize(newSize);
  58311. };
  58312. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58313. if (this.isCube) {
  58314. return this._textureMatrix;
  58315. }
  58316. return _super.prototype.getReflectionTextureMatrix.call(this);
  58317. };
  58318. RenderTargetTexture.prototype.resize = function (size) {
  58319. this.releaseInternalTexture();
  58320. var scene = this.getScene();
  58321. if (!scene) {
  58322. return;
  58323. }
  58324. this._processSizeParameter(size);
  58325. if (this.isCube) {
  58326. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58327. }
  58328. else {
  58329. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58330. }
  58331. };
  58332. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58333. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58334. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58335. var scene = this.getScene();
  58336. if (!scene) {
  58337. return;
  58338. }
  58339. var engine = scene.getEngine();
  58340. if (this.useCameraPostProcesses !== undefined) {
  58341. useCameraPostProcess = this.useCameraPostProcesses;
  58342. }
  58343. if (this._waitingRenderList) {
  58344. this.renderList = [];
  58345. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58346. var id = this._waitingRenderList[index];
  58347. var mesh_1 = scene.getMeshByID(id);
  58348. if (mesh_1) {
  58349. this.renderList.push(mesh_1);
  58350. }
  58351. }
  58352. delete this._waitingRenderList;
  58353. }
  58354. // Is predicate defined?
  58355. if (this.renderListPredicate) {
  58356. if (this.renderList) {
  58357. this.renderList.splice(0); // Clear previous renderList
  58358. }
  58359. else {
  58360. this.renderList = [];
  58361. }
  58362. var scene = this.getScene();
  58363. if (!scene) {
  58364. return;
  58365. }
  58366. var sceneMeshes = scene.meshes;
  58367. for (var index = 0; index < sceneMeshes.length; index++) {
  58368. var mesh = sceneMeshes[index];
  58369. if (this.renderListPredicate(mesh)) {
  58370. this.renderList.push(mesh);
  58371. }
  58372. }
  58373. }
  58374. this.onBeforeBindObservable.notifyObservers(this);
  58375. // Set custom projection.
  58376. // Needs to be before binding to prevent changing the aspect ratio.
  58377. var camera;
  58378. if (this.activeCamera) {
  58379. camera = this.activeCamera;
  58380. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58381. if (this.activeCamera !== scene.activeCamera) {
  58382. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58383. }
  58384. }
  58385. else {
  58386. camera = scene.activeCamera;
  58387. if (camera) {
  58388. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58389. }
  58390. }
  58391. // Prepare renderingManager
  58392. this._renderingManager.reset();
  58393. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58394. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58395. var sceneRenderId = scene.getRenderId();
  58396. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58397. var mesh = currentRenderList[meshIndex];
  58398. if (mesh) {
  58399. if (!mesh.isReady()) {
  58400. // Reset _currentRefreshId
  58401. this.resetRefreshCounter();
  58402. continue;
  58403. }
  58404. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58405. var isMasked = void 0;
  58406. if (!this.renderList && camera) {
  58407. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58408. }
  58409. else {
  58410. isMasked = false;
  58411. }
  58412. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58413. mesh._activate(sceneRenderId);
  58414. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58415. var subMesh = mesh.subMeshes[subIndex];
  58416. scene._activeIndices.addCount(subMesh.indexCount, false);
  58417. this._renderingManager.dispatch(subMesh, mesh);
  58418. }
  58419. }
  58420. }
  58421. }
  58422. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58423. var particleSystem = scene.particleSystems[particleIndex];
  58424. var emitter = particleSystem.emitter;
  58425. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58426. continue;
  58427. }
  58428. if (currentRenderList.indexOf(emitter) >= 0) {
  58429. this._renderingManager.dispatchParticles(particleSystem);
  58430. }
  58431. }
  58432. if (this.isCube) {
  58433. for (var face = 0; face < 6; face++) {
  58434. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58435. scene.incrementRenderId();
  58436. scene.resetCachedMaterial();
  58437. }
  58438. }
  58439. else {
  58440. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58441. }
  58442. this.onAfterUnbindObservable.notifyObservers(this);
  58443. if (scene.activeCamera) {
  58444. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58445. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58446. }
  58447. engine.setViewport(scene.activeCamera.viewport);
  58448. }
  58449. scene.resetCachedMaterial();
  58450. };
  58451. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58452. var minimum = 128;
  58453. var x = renderDimension * scale;
  58454. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58455. // Ensure we don't exceed the render dimension (while staying POT)
  58456. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58457. };
  58458. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58459. var _this = this;
  58460. if (!this._texture) {
  58461. return;
  58462. }
  58463. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58464. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58465. });
  58466. };
  58467. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58468. var scene = this.getScene();
  58469. if (!scene) {
  58470. return;
  58471. }
  58472. var engine = scene.getEngine();
  58473. if (!this._texture) {
  58474. return;
  58475. }
  58476. // Bind
  58477. if (this._postProcessManager) {
  58478. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58479. }
  58480. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58481. if (this._texture) {
  58482. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58483. }
  58484. }
  58485. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58486. // Clear
  58487. if (this.onClearObservable.hasObservers()) {
  58488. this.onClearObservable.notifyObservers(engine);
  58489. }
  58490. else {
  58491. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58492. }
  58493. if (!this._doNotChangeAspectRatio) {
  58494. scene.updateTransformMatrix(true);
  58495. }
  58496. // Render
  58497. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58498. if (this._postProcessManager) {
  58499. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58500. }
  58501. else if (useCameraPostProcess) {
  58502. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58503. }
  58504. if (!this._doNotChangeAspectRatio) {
  58505. scene.updateTransformMatrix(true);
  58506. }
  58507. // Dump ?
  58508. if (dumpForDebug) {
  58509. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58510. }
  58511. // Unbind
  58512. if (!this.isCube || faceIndex === 5) {
  58513. if (this.isCube) {
  58514. if (faceIndex === 5) {
  58515. engine.generateMipMapsForCubemap(this._texture);
  58516. }
  58517. }
  58518. this.unbindFrameBuffer(engine, faceIndex);
  58519. }
  58520. else {
  58521. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58522. }
  58523. };
  58524. /**
  58525. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58526. * This allowed control for front to back rendering or reversly depending of the special needs.
  58527. *
  58528. * @param renderingGroupId The rendering group id corresponding to its index
  58529. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58530. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58531. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58532. */
  58533. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58534. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58535. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58536. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58537. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58538. };
  58539. /**
  58540. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58541. *
  58542. * @param renderingGroupId The rendering group id corresponding to its index
  58543. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58544. */
  58545. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58546. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58547. };
  58548. RenderTargetTexture.prototype.clone = function () {
  58549. var textureSize = this.getSize();
  58550. 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);
  58551. // Base texture
  58552. newTexture.hasAlpha = this.hasAlpha;
  58553. newTexture.level = this.level;
  58554. // RenderTarget Texture
  58555. newTexture.coordinatesMode = this.coordinatesMode;
  58556. if (this.renderList) {
  58557. newTexture.renderList = this.renderList.slice(0);
  58558. }
  58559. return newTexture;
  58560. };
  58561. RenderTargetTexture.prototype.serialize = function () {
  58562. if (!this.name) {
  58563. return null;
  58564. }
  58565. var serializationObject = _super.prototype.serialize.call(this);
  58566. serializationObject.renderTargetSize = this.getRenderSize();
  58567. serializationObject.renderList = [];
  58568. if (this.renderList) {
  58569. for (var index = 0; index < this.renderList.length; index++) {
  58570. serializationObject.renderList.push(this.renderList[index].id);
  58571. }
  58572. }
  58573. return serializationObject;
  58574. };
  58575. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58576. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58577. var objBuffer = this.getInternalTexture();
  58578. var scene = this.getScene();
  58579. if (objBuffer && scene) {
  58580. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58581. }
  58582. };
  58583. RenderTargetTexture.prototype.dispose = function () {
  58584. if (this._postProcessManager) {
  58585. this._postProcessManager.dispose();
  58586. this._postProcessManager = null;
  58587. }
  58588. this.clearPostProcesses(true);
  58589. if (this._resizeObserver) {
  58590. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58591. this._resizeObserver = null;
  58592. }
  58593. this.renderList = null;
  58594. // Remove from custom render targets
  58595. var scene = this.getScene();
  58596. if (!scene) {
  58597. return;
  58598. }
  58599. var index = scene.customRenderTargets.indexOf(this);
  58600. if (index >= 0) {
  58601. scene.customRenderTargets.splice(index, 1);
  58602. }
  58603. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58604. var camera = _a[_i];
  58605. index = camera.customRenderTargets.indexOf(this);
  58606. if (index >= 0) {
  58607. camera.customRenderTargets.splice(index, 1);
  58608. }
  58609. }
  58610. _super.prototype.dispose.call(this);
  58611. };
  58612. RenderTargetTexture.prototype._rebuild = function () {
  58613. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58614. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58615. }
  58616. if (this._postProcessManager) {
  58617. this._postProcessManager._rebuild();
  58618. }
  58619. };
  58620. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58621. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58622. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58623. return RenderTargetTexture;
  58624. }(BABYLON.Texture));
  58625. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58626. })(BABYLON || (BABYLON = {}));
  58627. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58628. var BABYLON;
  58629. (function (BABYLON) {
  58630. ;
  58631. var MultiRenderTarget = /** @class */ (function (_super) {
  58632. __extends(MultiRenderTarget, _super);
  58633. function MultiRenderTarget(name, size, count, scene, options) {
  58634. var _this = this;
  58635. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58636. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58637. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58638. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58639. _this._engine = scene.getEngine();
  58640. if (!_this.isSupported) {
  58641. _this.dispose();
  58642. return;
  58643. }
  58644. var types = [];
  58645. var samplingModes = [];
  58646. for (var i = 0; i < count; i++) {
  58647. if (options && options.types && options.types[i] !== undefined) {
  58648. types.push(options.types[i]);
  58649. }
  58650. else {
  58651. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58652. }
  58653. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58654. samplingModes.push(options.samplingModes[i]);
  58655. }
  58656. else {
  58657. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58658. }
  58659. }
  58660. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58661. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58662. _this._size = size;
  58663. _this._multiRenderTargetOptions = {
  58664. samplingModes: samplingModes,
  58665. generateMipMaps: generateMipMaps,
  58666. generateDepthBuffer: generateDepthBuffer,
  58667. generateStencilBuffer: generateStencilBuffer,
  58668. generateDepthTexture: generateDepthTexture,
  58669. types: types,
  58670. textureCount: count
  58671. };
  58672. _this._createInternalTextures();
  58673. _this._createTextures();
  58674. return _this;
  58675. }
  58676. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58677. get: function () {
  58678. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58679. },
  58680. enumerable: true,
  58681. configurable: true
  58682. });
  58683. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58684. get: function () {
  58685. return this._textures;
  58686. },
  58687. enumerable: true,
  58688. configurable: true
  58689. });
  58690. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58691. get: function () {
  58692. return this._textures[this._textures.length - 1];
  58693. },
  58694. enumerable: true,
  58695. configurable: true
  58696. });
  58697. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58698. set: function (wrap) {
  58699. if (this._textures) {
  58700. for (var i = 0; i < this._textures.length; i++) {
  58701. this._textures[i].wrapU = wrap;
  58702. }
  58703. }
  58704. },
  58705. enumerable: true,
  58706. configurable: true
  58707. });
  58708. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58709. set: function (wrap) {
  58710. if (this._textures) {
  58711. for (var i = 0; i < this._textures.length; i++) {
  58712. this._textures[i].wrapV = wrap;
  58713. }
  58714. }
  58715. },
  58716. enumerable: true,
  58717. configurable: true
  58718. });
  58719. MultiRenderTarget.prototype._rebuild = function () {
  58720. this.releaseInternalTextures();
  58721. this._createInternalTextures();
  58722. for (var i = 0; i < this._internalTextures.length; i++) {
  58723. var texture = this._textures[i];
  58724. texture._texture = this._internalTextures[i];
  58725. }
  58726. // Keeps references to frame buffer and stencil/depth buffer
  58727. this._texture = this._internalTextures[0];
  58728. };
  58729. MultiRenderTarget.prototype._createInternalTextures = function () {
  58730. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58731. };
  58732. MultiRenderTarget.prototype._createTextures = function () {
  58733. this._textures = [];
  58734. for (var i = 0; i < this._internalTextures.length; i++) {
  58735. var texture = new BABYLON.Texture(null, this.getScene());
  58736. texture._texture = this._internalTextures[i];
  58737. this._textures.push(texture);
  58738. }
  58739. // Keeps references to frame buffer and stencil/depth buffer
  58740. this._texture = this._internalTextures[0];
  58741. };
  58742. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58743. get: function () {
  58744. return this._samples;
  58745. },
  58746. set: function (value) {
  58747. if (this._samples === value) {
  58748. return;
  58749. }
  58750. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58751. },
  58752. enumerable: true,
  58753. configurable: true
  58754. });
  58755. MultiRenderTarget.prototype.resize = function (size) {
  58756. this.releaseInternalTextures();
  58757. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58758. this._createInternalTextures();
  58759. };
  58760. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58761. var _this = this;
  58762. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58763. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58764. });
  58765. };
  58766. MultiRenderTarget.prototype.dispose = function () {
  58767. this.releaseInternalTextures();
  58768. _super.prototype.dispose.call(this);
  58769. };
  58770. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58771. if (!this._internalTextures) {
  58772. return;
  58773. }
  58774. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58775. if (this._internalTextures[i] !== undefined) {
  58776. this._internalTextures[i].dispose();
  58777. this._internalTextures.splice(i, 1);
  58778. }
  58779. }
  58780. };
  58781. return MultiRenderTarget;
  58782. }(BABYLON.RenderTargetTexture));
  58783. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58784. })(BABYLON || (BABYLON = {}));
  58785. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58786. var BABYLON;
  58787. (function (BABYLON) {
  58788. var MirrorTexture = /** @class */ (function (_super) {
  58789. __extends(MirrorTexture, _super);
  58790. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58791. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58792. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58793. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58794. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58795. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58796. _this._transformMatrix = BABYLON.Matrix.Zero();
  58797. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58798. _this._adaptiveBlurKernel = 0;
  58799. _this._blurKernelX = 0;
  58800. _this._blurKernelY = 0;
  58801. _this._blurRatio = 1.0;
  58802. _this.ignoreCameraViewport = true;
  58803. _this.onBeforeRenderObservable.add(function () {
  58804. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58805. _this._savedViewMatrix = scene.getViewMatrix();
  58806. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58807. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58808. scene.clipPlane = _this.mirrorPlane;
  58809. scene.getEngine().cullBackFaces = false;
  58810. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58811. });
  58812. _this.onAfterRenderObservable.add(function () {
  58813. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58814. scene.getEngine().cullBackFaces = true;
  58815. scene._mirroredCameraPosition = null;
  58816. delete scene.clipPlane;
  58817. });
  58818. return _this;
  58819. }
  58820. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58821. get: function () {
  58822. return this._blurRatio;
  58823. },
  58824. set: function (value) {
  58825. if (this._blurRatio === value) {
  58826. return;
  58827. }
  58828. this._blurRatio = value;
  58829. this._preparePostProcesses();
  58830. },
  58831. enumerable: true,
  58832. configurable: true
  58833. });
  58834. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58835. set: function (value) {
  58836. this._adaptiveBlurKernel = value;
  58837. this._autoComputeBlurKernel();
  58838. },
  58839. enumerable: true,
  58840. configurable: true
  58841. });
  58842. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58843. set: function (value) {
  58844. this.blurKernelX = value;
  58845. this.blurKernelY = value;
  58846. },
  58847. enumerable: true,
  58848. configurable: true
  58849. });
  58850. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58851. get: function () {
  58852. return this._blurKernelX;
  58853. },
  58854. set: function (value) {
  58855. if (this._blurKernelX === value) {
  58856. return;
  58857. }
  58858. this._blurKernelX = value;
  58859. this._preparePostProcesses();
  58860. },
  58861. enumerable: true,
  58862. configurable: true
  58863. });
  58864. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58865. get: function () {
  58866. return this._blurKernelY;
  58867. },
  58868. set: function (value) {
  58869. if (this._blurKernelY === value) {
  58870. return;
  58871. }
  58872. this._blurKernelY = value;
  58873. this._preparePostProcesses();
  58874. },
  58875. enumerable: true,
  58876. configurable: true
  58877. });
  58878. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58879. var engine = this.getScene().getEngine();
  58880. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58881. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58882. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58883. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58884. };
  58885. MirrorTexture.prototype._onRatioRescale = function () {
  58886. if (this._sizeRatio) {
  58887. this.resize(this._initialSizeParameter);
  58888. if (!this._adaptiveBlurKernel) {
  58889. this._preparePostProcesses();
  58890. }
  58891. }
  58892. if (this._adaptiveBlurKernel) {
  58893. this._autoComputeBlurKernel();
  58894. }
  58895. };
  58896. MirrorTexture.prototype._preparePostProcesses = function () {
  58897. this.clearPostProcesses(true);
  58898. if (this._blurKernelX && this._blurKernelY) {
  58899. var engine = this.getScene().getEngine();
  58900. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58901. 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);
  58902. this._blurX.autoClear = false;
  58903. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58904. this._blurX.inputTexture = this._texture;
  58905. }
  58906. else {
  58907. this._blurX.alwaysForcePOT = true;
  58908. }
  58909. 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);
  58910. this._blurY.autoClear = false;
  58911. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58912. this.addPostProcess(this._blurX);
  58913. this.addPostProcess(this._blurY);
  58914. }
  58915. else {
  58916. if (this._blurY) {
  58917. this.removePostProcess(this._blurY);
  58918. this._blurY.dispose();
  58919. this._blurY = null;
  58920. }
  58921. if (this._blurX) {
  58922. this.removePostProcess(this._blurX);
  58923. this._blurX.dispose();
  58924. this._blurX = null;
  58925. }
  58926. }
  58927. };
  58928. MirrorTexture.prototype.clone = function () {
  58929. var scene = this.getScene();
  58930. if (!scene) {
  58931. return this;
  58932. }
  58933. var textureSize = this.getSize();
  58934. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58935. // Base texture
  58936. newTexture.hasAlpha = this.hasAlpha;
  58937. newTexture.level = this.level;
  58938. // Mirror Texture
  58939. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58940. if (this.renderList) {
  58941. newTexture.renderList = this.renderList.slice(0);
  58942. }
  58943. return newTexture;
  58944. };
  58945. MirrorTexture.prototype.serialize = function () {
  58946. if (!this.name) {
  58947. return null;
  58948. }
  58949. var serializationObject = _super.prototype.serialize.call(this);
  58950. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58951. return serializationObject;
  58952. };
  58953. return MirrorTexture;
  58954. }(BABYLON.RenderTargetTexture));
  58955. BABYLON.MirrorTexture = MirrorTexture;
  58956. })(BABYLON || (BABYLON = {}));
  58957. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58958. var BABYLON;
  58959. (function (BABYLON) {
  58960. /**
  58961. * Creates a refraction texture used by refraction channel of the standard material.
  58962. * @param name the texture name
  58963. * @param size size of the underlying texture
  58964. * @param scene root scene
  58965. */
  58966. var RefractionTexture = /** @class */ (function (_super) {
  58967. __extends(RefractionTexture, _super);
  58968. function RefractionTexture(name, size, scene, generateMipMaps) {
  58969. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58970. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58971. _this.depth = 2.0;
  58972. _this.onBeforeRenderObservable.add(function () {
  58973. scene.clipPlane = _this.refractionPlane;
  58974. });
  58975. _this.onAfterRenderObservable.add(function () {
  58976. delete scene.clipPlane;
  58977. });
  58978. return _this;
  58979. }
  58980. RefractionTexture.prototype.clone = function () {
  58981. var scene = this.getScene();
  58982. if (!scene) {
  58983. return this;
  58984. }
  58985. var textureSize = this.getSize();
  58986. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58987. // Base texture
  58988. newTexture.hasAlpha = this.hasAlpha;
  58989. newTexture.level = this.level;
  58990. // Refraction Texture
  58991. newTexture.refractionPlane = this.refractionPlane.clone();
  58992. if (this.renderList) {
  58993. newTexture.renderList = this.renderList.slice(0);
  58994. }
  58995. newTexture.depth = this.depth;
  58996. return newTexture;
  58997. };
  58998. RefractionTexture.prototype.serialize = function () {
  58999. if (!this.name) {
  59000. return null;
  59001. }
  59002. var serializationObject = _super.prototype.serialize.call(this);
  59003. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59004. serializationObject.depth = this.depth;
  59005. return serializationObject;
  59006. };
  59007. return RefractionTexture;
  59008. }(BABYLON.RenderTargetTexture));
  59009. BABYLON.RefractionTexture = RefractionTexture;
  59010. })(BABYLON || (BABYLON = {}));
  59011. //# sourceMappingURL=babylon.refractionTexture.js.map
  59012. var BABYLON;
  59013. (function (BABYLON) {
  59014. var DynamicTexture = /** @class */ (function (_super) {
  59015. __extends(DynamicTexture, _super);
  59016. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59017. if (scene === void 0) { scene = null; }
  59018. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59019. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59020. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59021. _this.name = name;
  59022. _this._engine = _this.getScene().getEngine();
  59023. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59024. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59025. _this._generateMipMaps = generateMipMaps;
  59026. if (options.getContext) {
  59027. _this._canvas = options;
  59028. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59029. }
  59030. else {
  59031. _this._canvas = document.createElement("canvas");
  59032. if (options.width) {
  59033. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59034. }
  59035. else {
  59036. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59037. }
  59038. }
  59039. var textureSize = _this.getSize();
  59040. _this._canvas.width = textureSize.width;
  59041. _this._canvas.height = textureSize.height;
  59042. _this._context = _this._canvas.getContext("2d");
  59043. return _this;
  59044. }
  59045. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59046. get: function () {
  59047. return true;
  59048. },
  59049. enumerable: true,
  59050. configurable: true
  59051. });
  59052. DynamicTexture.prototype._recreate = function (textureSize) {
  59053. this._canvas.width = textureSize.width;
  59054. this._canvas.height = textureSize.height;
  59055. this.releaseInternalTexture();
  59056. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59057. };
  59058. DynamicTexture.prototype.scale = function (ratio) {
  59059. var textureSize = this.getSize();
  59060. textureSize.width *= ratio;
  59061. textureSize.height *= ratio;
  59062. this._recreate(textureSize);
  59063. };
  59064. DynamicTexture.prototype.scaleTo = function (width, height) {
  59065. var textureSize = this.getSize();
  59066. textureSize.width = width;
  59067. textureSize.height = height;
  59068. this._recreate(textureSize);
  59069. };
  59070. DynamicTexture.prototype.getContext = function () {
  59071. return this._context;
  59072. };
  59073. DynamicTexture.prototype.clear = function () {
  59074. var size = this.getSize();
  59075. this._context.fillRect(0, 0, size.width, size.height);
  59076. };
  59077. DynamicTexture.prototype.update = function (invertY) {
  59078. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59079. };
  59080. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59081. if (update === void 0) { update = true; }
  59082. var size = this.getSize();
  59083. if (clearColor) {
  59084. this._context.fillStyle = clearColor;
  59085. this._context.fillRect(0, 0, size.width, size.height);
  59086. }
  59087. this._context.font = font;
  59088. if (x === null || x === undefined) {
  59089. var textSize = this._context.measureText(text);
  59090. x = (size.width - textSize.width) / 2;
  59091. }
  59092. if (y === null || y === undefined) {
  59093. var fontSize = parseInt((font.replace(/\D/g, '')));
  59094. ;
  59095. y = (size.height / 2) + (fontSize / 3.65);
  59096. }
  59097. this._context.fillStyle = color;
  59098. this._context.fillText(text, x, y);
  59099. if (update) {
  59100. this.update(invertY);
  59101. }
  59102. };
  59103. DynamicTexture.prototype.clone = function () {
  59104. var scene = this.getScene();
  59105. if (!scene) {
  59106. return this;
  59107. }
  59108. var textureSize = this.getSize();
  59109. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59110. // Base texture
  59111. newTexture.hasAlpha = this.hasAlpha;
  59112. newTexture.level = this.level;
  59113. // Dynamic Texture
  59114. newTexture.wrapU = this.wrapU;
  59115. newTexture.wrapV = this.wrapV;
  59116. return newTexture;
  59117. };
  59118. DynamicTexture.prototype._rebuild = function () {
  59119. this.update();
  59120. };
  59121. return DynamicTexture;
  59122. }(BABYLON.Texture));
  59123. BABYLON.DynamicTexture = DynamicTexture;
  59124. })(BABYLON || (BABYLON = {}));
  59125. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59126. var BABYLON;
  59127. (function (BABYLON) {
  59128. var VideoTexture = /** @class */ (function (_super) {
  59129. __extends(VideoTexture, _super);
  59130. /**
  59131. * Creates a video texture.
  59132. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59133. * @param {string | null} name optional name, will detect from video source, if not defined
  59134. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59135. * @param {BABYLON.Scene} scene is obviously the current scene.
  59136. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59137. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59138. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59139. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59140. */
  59141. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59142. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59143. if (invertY === void 0) { invertY = false; }
  59144. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59145. if (settings === void 0) { settings = {
  59146. autoPlay: true,
  59147. loop: true,
  59148. autoUpdateTexture: true,
  59149. }; }
  59150. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59151. _this._createInternalTexture = function () {
  59152. if (_this._texture != null) {
  59153. return;
  59154. }
  59155. if (!_this._engine.needPOTTextures ||
  59156. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59157. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59158. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59159. }
  59160. else {
  59161. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59162. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59163. _this._generateMipMaps = false;
  59164. }
  59165. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59166. _this._texture.isReady = true;
  59167. _this._updateInternalTexture();
  59168. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59169. _this.onLoadObservable.notifyObservers(_this);
  59170. }
  59171. };
  59172. _this.reset = function () {
  59173. if (_this._texture == null) {
  59174. return;
  59175. }
  59176. _this._texture.dispose();
  59177. _this._texture = null;
  59178. };
  59179. _this._updateInternalTexture = function (e) {
  59180. if (_this._texture == null || !_this._texture.isReady) {
  59181. return;
  59182. }
  59183. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59184. return;
  59185. }
  59186. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59187. };
  59188. _this._engine = _this.getScene().getEngine();
  59189. _this._generateMipMaps = generateMipMaps;
  59190. _this._samplingMode = samplingMode;
  59191. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59192. _this.name = name || _this._getName(src);
  59193. _this.video = _this._getVideo(src);
  59194. if (settings.autoPlay !== undefined) {
  59195. _this.video.autoplay = settings.autoPlay;
  59196. }
  59197. if (settings.loop !== undefined) {
  59198. _this.video.loop = settings.loop;
  59199. }
  59200. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59201. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59202. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59203. _this.video.addEventListener("emptied", _this.reset);
  59204. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59205. _this._createInternalTexture();
  59206. }
  59207. return _this;
  59208. }
  59209. VideoTexture.prototype._getName = function (src) {
  59210. if (src instanceof HTMLVideoElement) {
  59211. return src.currentSrc;
  59212. }
  59213. if (typeof src === "object") {
  59214. return src.toString();
  59215. }
  59216. return src;
  59217. };
  59218. ;
  59219. VideoTexture.prototype._getVideo = function (src) {
  59220. if (src instanceof HTMLVideoElement) {
  59221. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59222. return src;
  59223. }
  59224. var video = document.createElement("video");
  59225. if (typeof src === "string") {
  59226. BABYLON.Tools.SetCorsBehavior(src, video);
  59227. video.src = src;
  59228. }
  59229. else {
  59230. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59231. src.forEach(function (url) {
  59232. var source = document.createElement("source");
  59233. source.src = url;
  59234. video.appendChild(source);
  59235. });
  59236. }
  59237. return video;
  59238. };
  59239. ;
  59240. /**
  59241. * Internal method to initiate `update`.
  59242. */
  59243. VideoTexture.prototype._rebuild = function () {
  59244. this.update();
  59245. };
  59246. /**
  59247. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59248. */
  59249. VideoTexture.prototype.update = function () {
  59250. if (!this.autoUpdateTexture) {
  59251. // Expecting user to call `updateTexture` manually
  59252. return;
  59253. }
  59254. this.updateTexture(true);
  59255. };
  59256. /**
  59257. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59258. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59259. */
  59260. VideoTexture.prototype.updateTexture = function (isVisible) {
  59261. if (!isVisible) {
  59262. return;
  59263. }
  59264. if (this.video.paused) {
  59265. return;
  59266. }
  59267. this._updateInternalTexture();
  59268. };
  59269. /**
  59270. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59271. * @param url New url.
  59272. */
  59273. VideoTexture.prototype.updateURL = function (url) {
  59274. this.video.src = url;
  59275. };
  59276. VideoTexture.prototype.dispose = function () {
  59277. _super.prototype.dispose.call(this);
  59278. this.video.removeEventListener("canplay", this._createInternalTexture);
  59279. this.video.removeEventListener("paused", this._updateInternalTexture);
  59280. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59281. this.video.removeEventListener("emptied", this.reset);
  59282. this.video.pause();
  59283. };
  59284. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59285. var video = document.createElement("video");
  59286. var constraintsDeviceId;
  59287. if (constraints && constraints.deviceId) {
  59288. constraintsDeviceId = {
  59289. exact: constraints.deviceId,
  59290. };
  59291. }
  59292. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59293. if (navigator.mediaDevices) {
  59294. navigator.mediaDevices.getUserMedia({ video: constraints })
  59295. .then(function (stream) {
  59296. if (video.mozSrcObject !== undefined) {
  59297. // hack for Firefox < 19
  59298. video.mozSrcObject = stream;
  59299. }
  59300. else {
  59301. video.srcObject = stream;
  59302. }
  59303. var onPlaying = function () {
  59304. if (onReady) {
  59305. onReady(new VideoTexture("video", video, scene, true, true));
  59306. }
  59307. video.removeEventListener("playing", onPlaying);
  59308. };
  59309. video.addEventListener("playing", onPlaying);
  59310. video.play();
  59311. })
  59312. .catch(function (err) {
  59313. BABYLON.Tools.Error(err.name);
  59314. });
  59315. }
  59316. else {
  59317. navigator.getUserMedia =
  59318. navigator.getUserMedia ||
  59319. navigator.webkitGetUserMedia ||
  59320. navigator.mozGetUserMedia ||
  59321. navigator.msGetUserMedia;
  59322. if (navigator.getUserMedia) {
  59323. navigator.getUserMedia({
  59324. video: {
  59325. deviceId: constraintsDeviceId,
  59326. width: {
  59327. min: (constraints && constraints.minWidth) || 256,
  59328. max: (constraints && constraints.maxWidth) || 640,
  59329. },
  59330. height: {
  59331. min: (constraints && constraints.minHeight) || 256,
  59332. max: (constraints && constraints.maxHeight) || 480,
  59333. },
  59334. },
  59335. }, function (stream) {
  59336. if (video.mozSrcObject !== undefined) {
  59337. // hack for Firefox < 19
  59338. video.mozSrcObject = stream;
  59339. }
  59340. else {
  59341. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59342. }
  59343. video.play();
  59344. if (onReady) {
  59345. onReady(new VideoTexture("video", video, scene, true, true));
  59346. }
  59347. }, function (e) {
  59348. BABYLON.Tools.Error(e.name);
  59349. });
  59350. }
  59351. }
  59352. };
  59353. return VideoTexture;
  59354. }(BABYLON.Texture));
  59355. BABYLON.VideoTexture = VideoTexture;
  59356. })(BABYLON || (BABYLON = {}));
  59357. //# sourceMappingURL=babylon.videoTexture.js.map
  59358. var BABYLON;
  59359. (function (BABYLON) {
  59360. var RawTexture = /** @class */ (function (_super) {
  59361. __extends(RawTexture, _super);
  59362. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59363. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59364. if (invertY === void 0) { invertY = false; }
  59365. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59366. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59367. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59368. _this.format = format;
  59369. _this._engine = scene.getEngine();
  59370. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59371. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59372. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59373. return _this;
  59374. }
  59375. RawTexture.prototype.update = function (data) {
  59376. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59377. };
  59378. // Statics
  59379. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59380. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59381. if (invertY === void 0) { invertY = false; }
  59382. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59383. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59384. };
  59385. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59386. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59387. if (invertY === void 0) { invertY = false; }
  59388. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59389. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59390. };
  59391. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59392. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59393. if (invertY === void 0) { invertY = false; }
  59394. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59395. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59396. };
  59397. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59398. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59399. if (invertY === void 0) { invertY = false; }
  59400. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59401. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59402. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59403. };
  59404. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59405. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59406. if (invertY === void 0) { invertY = false; }
  59407. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59408. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59409. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59410. };
  59411. return RawTexture;
  59412. }(BABYLON.Texture));
  59413. BABYLON.RawTexture = RawTexture;
  59414. })(BABYLON || (BABYLON = {}));
  59415. //# sourceMappingURL=babylon.rawTexture.js.map
  59416. var BABYLON;
  59417. (function (BABYLON) {
  59418. /**
  59419. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59420. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59421. */
  59422. var PostProcess = /** @class */ (function () {
  59423. /**
  59424. * Creates a new instance of @see PostProcess
  59425. * @param name The name of the PostProcess.
  59426. * @param fragmentUrl The url of the fragment shader to be used.
  59427. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59428. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59429. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59430. * @param camera The camera to apply the render pass to.
  59431. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59432. * @param engine The engine which the post process will be applied. (default: current engine)
  59433. * @param reusable If the post process can be reused on the same frame. (default: false)
  59434. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59435. * @param textureType Type of textures used when performing the post process. (default: 0)
  59436. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59437. * @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
  59438. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59439. */
  59440. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59442. if (defines === void 0) { defines = null; }
  59443. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59444. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59445. if (blockCompilation === void 0) { blockCompilation = false; }
  59446. this.name = name;
  59447. /**
  59448. * Width of the texture to apply the post process on
  59449. */
  59450. this.width = -1;
  59451. /**
  59452. * Height of the texture to apply the post process on
  59453. */
  59454. this.height = -1;
  59455. /**
  59456. * If the buffer needs to be cleared before applying the post process. (default: true)
  59457. * Should be set to false if shader will overwrite all previous pixels.
  59458. */
  59459. this.autoClear = true;
  59460. /**
  59461. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59462. */
  59463. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59464. /**
  59465. * Animations to be used for the post processing
  59466. */
  59467. this.animations = new Array();
  59468. /**
  59469. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59470. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59471. */
  59472. this.enablePixelPerfectMode = false;
  59473. /**
  59474. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59475. */
  59476. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59477. /**
  59478. * Force textures to be a power of two (default: false)
  59479. */
  59480. this.alwaysForcePOT = false;
  59481. /**
  59482. * Number of sample textures (default: 1)
  59483. */
  59484. this.samples = 1;
  59485. /**
  59486. * Modify the scale of the post process to be the same as the viewport (default: false)
  59487. */
  59488. this.adaptScaleToCurrentViewport = false;
  59489. this._reusable = false;
  59490. /**
  59491. * Smart array of input and output textures for the post process.
  59492. */
  59493. this._textures = new BABYLON.SmartArray(2);
  59494. /**
  59495. * The index in _textures that corresponds to the output texture.
  59496. */
  59497. this._currentRenderTextureInd = 0;
  59498. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59499. this._texelSize = BABYLON.Vector2.Zero();
  59500. // Events
  59501. /**
  59502. * An event triggered when the postprocess is activated.
  59503. * @type {BABYLON.Observable}
  59504. */
  59505. this.onActivateObservable = new BABYLON.Observable();
  59506. /**
  59507. * An event triggered when the postprocess changes its size.
  59508. * @type {BABYLON.Observable}
  59509. */
  59510. this.onSizeChangedObservable = new BABYLON.Observable();
  59511. /**
  59512. * An event triggered when the postprocess applies its effect.
  59513. * @type {BABYLON.Observable}
  59514. */
  59515. this.onApplyObservable = new BABYLON.Observable();
  59516. /**
  59517. * An event triggered before rendering the postprocess
  59518. * @type {BABYLON.Observable}
  59519. */
  59520. this.onBeforeRenderObservable = new BABYLON.Observable();
  59521. /**
  59522. * An event triggered after rendering the postprocess
  59523. * @type {BABYLON.Observable}
  59524. */
  59525. this.onAfterRenderObservable = new BABYLON.Observable();
  59526. if (camera != null) {
  59527. this._camera = camera;
  59528. this._scene = camera.getScene();
  59529. camera.attachPostProcess(this);
  59530. this._engine = this._scene.getEngine();
  59531. this._scene.postProcesses.push(this);
  59532. }
  59533. else if (engine) {
  59534. this._engine = engine;
  59535. this._engine.postProcesses.push(this);
  59536. }
  59537. this._options = options;
  59538. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59539. this._reusable = reusable || false;
  59540. this._textureType = textureType;
  59541. this._samplers = samplers || [];
  59542. this._samplers.push("textureSampler");
  59543. this._fragmentUrl = fragmentUrl;
  59544. this._vertexUrl = vertexUrl;
  59545. this._parameters = parameters || [];
  59546. this._parameters.push("scale");
  59547. this._indexParameters = indexParameters;
  59548. if (!blockCompilation) {
  59549. this.updateEffect(defines);
  59550. }
  59551. }
  59552. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59553. /**
  59554. * A function that is added to the onActivateObservable
  59555. */
  59556. set: function (callback) {
  59557. if (this._onActivateObserver) {
  59558. this.onActivateObservable.remove(this._onActivateObserver);
  59559. }
  59560. if (callback) {
  59561. this._onActivateObserver = this.onActivateObservable.add(callback);
  59562. }
  59563. },
  59564. enumerable: true,
  59565. configurable: true
  59566. });
  59567. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59568. /**
  59569. * A function that is added to the onSizeChangedObservable
  59570. */
  59571. set: function (callback) {
  59572. if (this._onSizeChangedObserver) {
  59573. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59574. }
  59575. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59576. },
  59577. enumerable: true,
  59578. configurable: true
  59579. });
  59580. Object.defineProperty(PostProcess.prototype, "onApply", {
  59581. /**
  59582. * A function that is added to the onApplyObservable
  59583. */
  59584. set: function (callback) {
  59585. if (this._onApplyObserver) {
  59586. this.onApplyObservable.remove(this._onApplyObserver);
  59587. }
  59588. this._onApplyObserver = this.onApplyObservable.add(callback);
  59589. },
  59590. enumerable: true,
  59591. configurable: true
  59592. });
  59593. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59594. /**
  59595. * A function that is added to the onBeforeRenderObservable
  59596. */
  59597. set: function (callback) {
  59598. if (this._onBeforeRenderObserver) {
  59599. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59600. }
  59601. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59602. },
  59603. enumerable: true,
  59604. configurable: true
  59605. });
  59606. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59607. /**
  59608. * A function that is added to the onAfterRenderObservable
  59609. */
  59610. set: function (callback) {
  59611. if (this._onAfterRenderObserver) {
  59612. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59613. }
  59614. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59615. },
  59616. enumerable: true,
  59617. configurable: true
  59618. });
  59619. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59620. /**
  59621. * 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
  59622. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59623. */
  59624. get: function () {
  59625. return this._textures.data[this._currentRenderTextureInd];
  59626. },
  59627. set: function (value) {
  59628. this._forcedOutputTexture = value;
  59629. },
  59630. enumerable: true,
  59631. configurable: true
  59632. });
  59633. /**
  59634. * Gets the camera which post process is applied to.
  59635. * @returns The camera the post process is applied to.
  59636. */
  59637. PostProcess.prototype.getCamera = function () {
  59638. return this._camera;
  59639. };
  59640. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59641. /**
  59642. * Gets the texel size of the postprocess.
  59643. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59644. */
  59645. get: function () {
  59646. if (this._shareOutputWithPostProcess) {
  59647. return this._shareOutputWithPostProcess.texelSize;
  59648. }
  59649. if (this._forcedOutputTexture) {
  59650. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59651. }
  59652. return this._texelSize;
  59653. },
  59654. enumerable: true,
  59655. configurable: true
  59656. });
  59657. /**
  59658. * Gets the engine which this post process belongs to.
  59659. * @returns The engine the post process was enabled with.
  59660. */
  59661. PostProcess.prototype.getEngine = function () {
  59662. return this._engine;
  59663. };
  59664. /**
  59665. * The effect that is created when initializing the post process.
  59666. * @returns The created effect corrisponding the the postprocess.
  59667. */
  59668. PostProcess.prototype.getEffect = function () {
  59669. return this._effect;
  59670. };
  59671. /**
  59672. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59673. * @param postProcess The post process to share the output with.
  59674. * @returns This post process.
  59675. */
  59676. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59677. this._disposeTextures();
  59678. this._shareOutputWithPostProcess = postProcess;
  59679. return this;
  59680. };
  59681. /**
  59682. * Updates the effect with the current post process compile time values and recompiles the shader.
  59683. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59684. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59685. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59686. * @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
  59687. * @param onCompiled Called when the shader has been compiled.
  59688. * @param onError Called if there is an error when compiling a shader.
  59689. */
  59690. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59691. if (defines === void 0) { defines = null; }
  59692. if (uniforms === void 0) { uniforms = null; }
  59693. if (samplers === void 0) { samplers = null; }
  59694. 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);
  59695. };
  59696. /**
  59697. * The post process is reusable if it can be used multiple times within one frame.
  59698. * @returns If the post process is reusable
  59699. */
  59700. PostProcess.prototype.isReusable = function () {
  59701. return this._reusable;
  59702. };
  59703. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59704. PostProcess.prototype.markTextureDirty = function () {
  59705. this.width = -1;
  59706. };
  59707. /**
  59708. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59709. * 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.
  59710. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59711. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59712. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59713. */
  59714. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59715. var _this = this;
  59716. if (sourceTexture === void 0) { sourceTexture = null; }
  59717. camera = camera || this._camera;
  59718. var scene = camera.getScene();
  59719. var engine = scene.getEngine();
  59720. var maxSize = engine.getCaps().maxTextureSize;
  59721. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59722. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59723. // 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
  59724. var webVRCamera = camera.parent;
  59725. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59726. requiredWidth /= 2;
  59727. }
  59728. var desiredWidth = (this._options.width || requiredWidth);
  59729. var desiredHeight = this._options.height || requiredHeight;
  59730. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59731. if (this.adaptScaleToCurrentViewport) {
  59732. var currentViewport = engine.currentViewport;
  59733. if (currentViewport) {
  59734. desiredWidth *= currentViewport.width;
  59735. desiredHeight *= currentViewport.height;
  59736. }
  59737. }
  59738. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59739. if (!this._options.width) {
  59740. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59741. }
  59742. if (!this._options.height) {
  59743. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59744. }
  59745. }
  59746. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59747. if (this._textures.length > 0) {
  59748. for (var i = 0; i < this._textures.length; i++) {
  59749. this._engine._releaseTexture(this._textures.data[i]);
  59750. }
  59751. this._textures.reset();
  59752. }
  59753. this.width = desiredWidth;
  59754. this.height = desiredHeight;
  59755. var textureSize = { width: this.width, height: this.height };
  59756. var textureOptions = {
  59757. generateMipMaps: false,
  59758. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59759. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59760. samplingMode: this.renderTargetSamplingMode,
  59761. type: this._textureType
  59762. };
  59763. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59764. if (this._reusable) {
  59765. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59766. }
  59767. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59768. this.onSizeChangedObservable.notifyObservers(this);
  59769. }
  59770. this._textures.forEach(function (texture) {
  59771. if (texture.samples !== _this.samples) {
  59772. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59773. }
  59774. });
  59775. }
  59776. var target;
  59777. if (this._shareOutputWithPostProcess) {
  59778. target = this._shareOutputWithPostProcess.inputTexture;
  59779. }
  59780. else if (this._forcedOutputTexture) {
  59781. target = this._forcedOutputTexture;
  59782. this.width = this._forcedOutputTexture.width;
  59783. this.height = this._forcedOutputTexture.height;
  59784. }
  59785. else {
  59786. target = this.inputTexture;
  59787. }
  59788. // Bind the input of this post process to be used as the output of the previous post process.
  59789. if (this.enablePixelPerfectMode) {
  59790. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59791. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59792. }
  59793. else {
  59794. this._scaleRatio.copyFromFloats(1, 1);
  59795. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59796. }
  59797. this.onActivateObservable.notifyObservers(camera);
  59798. // Clear
  59799. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59800. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59801. }
  59802. if (this._reusable) {
  59803. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59804. }
  59805. };
  59806. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59807. /**
  59808. * If the post process is supported.
  59809. */
  59810. get: function () {
  59811. return this._effect.isSupported;
  59812. },
  59813. enumerable: true,
  59814. configurable: true
  59815. });
  59816. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59817. /**
  59818. * The aspect ratio of the output texture.
  59819. */
  59820. get: function () {
  59821. if (this._shareOutputWithPostProcess) {
  59822. return this._shareOutputWithPostProcess.aspectRatio;
  59823. }
  59824. if (this._forcedOutputTexture) {
  59825. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59826. }
  59827. return this.width / this.height;
  59828. },
  59829. enumerable: true,
  59830. configurable: true
  59831. });
  59832. /**
  59833. * Get a value indicating if the post-process is ready to be used
  59834. * @returns true if the post-process is ready (shader is compiled)
  59835. */
  59836. PostProcess.prototype.isReady = function () {
  59837. return this._effect && this._effect.isReady();
  59838. };
  59839. /**
  59840. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59841. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59842. */
  59843. PostProcess.prototype.apply = function () {
  59844. // Check
  59845. if (!this._effect || !this._effect.isReady())
  59846. return null;
  59847. // States
  59848. this._engine.enableEffect(this._effect);
  59849. this._engine.setState(false);
  59850. this._engine.setDepthBuffer(false);
  59851. this._engine.setDepthWrite(false);
  59852. // Alpha
  59853. this._engine.setAlphaMode(this.alphaMode);
  59854. if (this.alphaConstants) {
  59855. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59856. }
  59857. // Bind the output texture of the preivous post process as the input to this post process.
  59858. var source;
  59859. if (this._shareOutputWithPostProcess) {
  59860. source = this._shareOutputWithPostProcess.inputTexture;
  59861. }
  59862. else if (this._forcedOutputTexture) {
  59863. source = this._forcedOutputTexture;
  59864. }
  59865. else {
  59866. source = this.inputTexture;
  59867. }
  59868. this._effect._bindTexture("textureSampler", source);
  59869. // Parameters
  59870. this._effect.setVector2("scale", this._scaleRatio);
  59871. this.onApplyObservable.notifyObservers(this._effect);
  59872. return this._effect;
  59873. };
  59874. PostProcess.prototype._disposeTextures = function () {
  59875. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59876. return;
  59877. }
  59878. if (this._textures.length > 0) {
  59879. for (var i = 0; i < this._textures.length; i++) {
  59880. this._engine._releaseTexture(this._textures.data[i]);
  59881. }
  59882. }
  59883. this._textures.dispose();
  59884. };
  59885. /**
  59886. * Disposes the post process.
  59887. * @param camera The camera to dispose the post process on.
  59888. */
  59889. PostProcess.prototype.dispose = function (camera) {
  59890. camera = camera || this._camera;
  59891. this._disposeTextures();
  59892. if (this._scene) {
  59893. var index_1 = this._scene.postProcesses.indexOf(this);
  59894. if (index_1 !== -1) {
  59895. this._scene.postProcesses.splice(index_1, 1);
  59896. }
  59897. }
  59898. else {
  59899. var index_2 = this._engine.postProcesses.indexOf(this);
  59900. if (index_2 !== -1) {
  59901. this._engine.postProcesses.splice(index_2, 1);
  59902. }
  59903. }
  59904. if (!camera) {
  59905. return;
  59906. }
  59907. camera.detachPostProcess(this);
  59908. var index = camera._postProcesses.indexOf(this);
  59909. if (index === 0 && camera._postProcesses.length > 0) {
  59910. this._camera._postProcesses[0].markTextureDirty();
  59911. }
  59912. this.onActivateObservable.clear();
  59913. this.onAfterRenderObservable.clear();
  59914. this.onApplyObservable.clear();
  59915. this.onBeforeRenderObservable.clear();
  59916. this.onSizeChangedObservable.clear();
  59917. };
  59918. return PostProcess;
  59919. }());
  59920. BABYLON.PostProcess = PostProcess;
  59921. })(BABYLON || (BABYLON = {}));
  59922. //# sourceMappingURL=babylon.postProcess.js.map
  59923. var BABYLON;
  59924. (function (BABYLON) {
  59925. var PassPostProcess = /** @class */ (function (_super) {
  59926. __extends(PassPostProcess, _super);
  59927. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59928. if (camera === void 0) { camera = null; }
  59929. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59930. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  59931. }
  59932. return PassPostProcess;
  59933. }(BABYLON.PostProcess));
  59934. BABYLON.PassPostProcess = PassPostProcess;
  59935. })(BABYLON || (BABYLON = {}));
  59936. //# sourceMappingURL=babylon.passPostProcess.js.map
  59937. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59938. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59939. s = arguments[i];
  59940. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59941. t[p] = s[p];
  59942. }
  59943. return t;
  59944. };
  59945. var BABYLON;
  59946. (function (BABYLON) {
  59947. /**
  59948. * Default implementation of @see IShadowGenerator.
  59949. * This is the main object responsible of generating shadows in the framework.
  59950. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59951. */
  59952. var ShadowGenerator = /** @class */ (function () {
  59953. /**
  59954. * Creates a ShadowGenerator object.
  59955. * A ShadowGenerator is the required tool to use the shadows.
  59956. * Each light casting shadows needs to use its own ShadowGenerator.
  59957. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59958. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59959. * @param light The light object generating the shadows.
  59960. * @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.
  59961. */
  59962. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59963. this._bias = 0.00005;
  59964. this._blurBoxOffset = 1;
  59965. this._blurScale = 2;
  59966. this._blurKernel = 1;
  59967. this._useKernelBlur = false;
  59968. this._filter = ShadowGenerator.FILTER_NONE;
  59969. this._darkness = 0;
  59970. this._transparencyShadow = false;
  59971. /**
  59972. * Controls the extent to which the shadows fade out at the edge of the frustum
  59973. * Used only by directionals and spots
  59974. */
  59975. this.frustumEdgeFalloff = 0;
  59976. /**
  59977. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59978. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59979. * It might on the other hand introduce peter panning.
  59980. */
  59981. this.forceBackFacesOnly = false;
  59982. this._lightDirection = BABYLON.Vector3.Zero();
  59983. this._viewMatrix = BABYLON.Matrix.Zero();
  59984. this._projectionMatrix = BABYLON.Matrix.Zero();
  59985. this._transformMatrix = BABYLON.Matrix.Zero();
  59986. this._currentFaceIndex = 0;
  59987. this._currentFaceIndexCache = 0;
  59988. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59989. this._mapSize = mapSize;
  59990. this._light = light;
  59991. this._scene = light.getScene();
  59992. light._shadowGenerator = this;
  59993. // Texture type fallback from float to int if not supported.
  59994. var caps = this._scene.getEngine().getCaps();
  59995. if (!useFullFloatFirst) {
  59996. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59997. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59998. }
  59999. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60000. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60001. }
  60002. else {
  60003. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60004. }
  60005. }
  60006. else {
  60007. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60008. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60009. }
  60010. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60011. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60012. }
  60013. else {
  60014. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60015. }
  60016. }
  60017. this._initializeGenerator();
  60018. }
  60019. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  60020. /**
  60021. * Shadow generator mode None: no filtering applied.
  60022. */
  60023. get: function () {
  60024. return ShadowGenerator._FILTER_NONE;
  60025. },
  60026. enumerable: true,
  60027. configurable: true
  60028. });
  60029. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  60030. /**
  60031. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  60032. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  60033. */
  60034. get: function () {
  60035. return ShadowGenerator._FILTER_POISSONSAMPLING;
  60036. },
  60037. enumerable: true,
  60038. configurable: true
  60039. });
  60040. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  60041. /**
  60042. * Shadow generator mode ESM: Exponential Shadow Mapping.
  60043. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60044. */
  60045. get: function () {
  60046. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  60047. },
  60048. enumerable: true,
  60049. configurable: true
  60050. });
  60051. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  60052. /**
  60053. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  60054. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60055. */
  60056. get: function () {
  60057. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  60058. },
  60059. enumerable: true,
  60060. configurable: true
  60061. });
  60062. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  60063. /**
  60064. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  60065. * edge artifacts on steep falloff.
  60066. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60067. */
  60068. get: function () {
  60069. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60070. },
  60071. enumerable: true,
  60072. configurable: true
  60073. });
  60074. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  60075. /**
  60076. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  60077. * edge artifacts on steep falloff.
  60078. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60079. */
  60080. get: function () {
  60081. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60082. },
  60083. enumerable: true,
  60084. configurable: true
  60085. });
  60086. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60087. /**
  60088. * Gets the bias: offset applied on the depth preventing acnea.
  60089. */
  60090. get: function () {
  60091. return this._bias;
  60092. },
  60093. /**
  60094. * Sets the bias: offset applied on the depth preventing acnea.
  60095. */
  60096. set: function (bias) {
  60097. this._bias = bias;
  60098. },
  60099. enumerable: true,
  60100. configurable: true
  60101. });
  60102. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60103. /**
  60104. * Gets the blur box offset: offset applied during the blur pass.
  60105. * Only usefull if useKernelBlur = false
  60106. */
  60107. get: function () {
  60108. return this._blurBoxOffset;
  60109. },
  60110. /**
  60111. * Sets the blur box offset: offset applied during the blur pass.
  60112. * Only usefull if useKernelBlur = false
  60113. */
  60114. set: function (value) {
  60115. if (this._blurBoxOffset === value) {
  60116. return;
  60117. }
  60118. this._blurBoxOffset = value;
  60119. this._disposeBlurPostProcesses();
  60120. },
  60121. enumerable: true,
  60122. configurable: true
  60123. });
  60124. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60125. /**
  60126. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60127. * 2 means half of the size.
  60128. */
  60129. get: function () {
  60130. return this._blurScale;
  60131. },
  60132. /**
  60133. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60134. * 2 means half of the size.
  60135. */
  60136. set: function (value) {
  60137. if (this._blurScale === value) {
  60138. return;
  60139. }
  60140. this._blurScale = value;
  60141. this._disposeBlurPostProcesses();
  60142. },
  60143. enumerable: true,
  60144. configurable: true
  60145. });
  60146. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60147. /**
  60148. * Gets the blur kernel: kernel size of the blur pass.
  60149. * Only usefull if useKernelBlur = true
  60150. */
  60151. get: function () {
  60152. return this._blurKernel;
  60153. },
  60154. /**
  60155. * Sets the blur kernel: kernel size of the blur pass.
  60156. * Only usefull if useKernelBlur = true
  60157. */
  60158. set: function (value) {
  60159. if (this._blurKernel === value) {
  60160. return;
  60161. }
  60162. this._blurKernel = value;
  60163. this._disposeBlurPostProcesses();
  60164. },
  60165. enumerable: true,
  60166. configurable: true
  60167. });
  60168. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60169. /**
  60170. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60171. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60172. */
  60173. get: function () {
  60174. return this._useKernelBlur;
  60175. },
  60176. /**
  60177. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60178. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60179. */
  60180. set: function (value) {
  60181. if (this._useKernelBlur === value) {
  60182. return;
  60183. }
  60184. this._useKernelBlur = value;
  60185. this._disposeBlurPostProcesses();
  60186. },
  60187. enumerable: true,
  60188. configurable: true
  60189. });
  60190. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60191. /**
  60192. * Gets the depth scale used in ESM mode.
  60193. */
  60194. get: function () {
  60195. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60196. },
  60197. /**
  60198. * Sets the depth scale used in ESM mode.
  60199. * This can override the scale stored on the light.
  60200. */
  60201. set: function (value) {
  60202. this._depthScale = value;
  60203. },
  60204. enumerable: true,
  60205. configurable: true
  60206. });
  60207. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60208. /**
  60209. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60210. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60211. */
  60212. get: function () {
  60213. return this._filter;
  60214. },
  60215. /**
  60216. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60217. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60218. */
  60219. set: function (value) {
  60220. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60221. if (this._light.needCube()) {
  60222. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60223. this.useExponentialShadowMap = true;
  60224. return;
  60225. }
  60226. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60227. this.useCloseExponentialShadowMap = true;
  60228. return;
  60229. }
  60230. }
  60231. if (this._filter === value) {
  60232. return;
  60233. }
  60234. this._filter = value;
  60235. this._disposeBlurPostProcesses();
  60236. this._applyFilterValues();
  60237. this._light._markMeshesAsLightDirty();
  60238. },
  60239. enumerable: true,
  60240. configurable: true
  60241. });
  60242. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60243. /**
  60244. * Gets if the current filter is set to Poisson Sampling aka PCF.
  60245. */
  60246. get: function () {
  60247. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60248. },
  60249. /**
  60250. * Sets the current filter to Poisson Sampling aka PCF.
  60251. */
  60252. set: function (value) {
  60253. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60254. return;
  60255. }
  60256. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60257. },
  60258. enumerable: true,
  60259. configurable: true
  60260. });
  60261. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60262. /**
  60263. * Gets if the current filter is set to VSM.
  60264. * DEPRECATED. Should use useExponentialShadowMap instead.
  60265. */
  60266. get: function () {
  60267. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60268. return this.useExponentialShadowMap;
  60269. },
  60270. /**
  60271. * Sets the current filter is to VSM.
  60272. * DEPRECATED. Should use useExponentialShadowMap instead.
  60273. */
  60274. set: function (value) {
  60275. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60276. this.useExponentialShadowMap = value;
  60277. },
  60278. enumerable: true,
  60279. configurable: true
  60280. });
  60281. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60282. /**
  60283. * Gets if the current filter is set to blurred VSM.
  60284. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60285. */
  60286. get: function () {
  60287. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60288. return this.useBlurExponentialShadowMap;
  60289. },
  60290. /**
  60291. * Sets the current filter is to blurred VSM.
  60292. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60293. */
  60294. set: function (value) {
  60295. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60296. this.useBlurExponentialShadowMap = value;
  60297. },
  60298. enumerable: true,
  60299. configurable: true
  60300. });
  60301. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60302. /**
  60303. * Gets if the current filter is set to ESM.
  60304. */
  60305. get: function () {
  60306. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60307. },
  60308. /**
  60309. * Sets the current filter is to ESM.
  60310. */
  60311. set: function (value) {
  60312. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60313. return;
  60314. }
  60315. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60316. },
  60317. enumerable: true,
  60318. configurable: true
  60319. });
  60320. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60321. /**
  60322. * Gets if the current filter is set to filtered ESM.
  60323. */
  60324. get: function () {
  60325. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60326. },
  60327. /**
  60328. * Gets if the current filter is set to filtered ESM.
  60329. */
  60330. set: function (value) {
  60331. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60332. return;
  60333. }
  60334. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60335. },
  60336. enumerable: true,
  60337. configurable: true
  60338. });
  60339. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60340. /**
  60341. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60342. * exponential to prevent steep falloff artifacts).
  60343. */
  60344. get: function () {
  60345. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60346. },
  60347. /**
  60348. * Sets the current filter to "close ESM" (using the inverse of the
  60349. * exponential to prevent steep falloff artifacts).
  60350. */
  60351. set: function (value) {
  60352. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60353. return;
  60354. }
  60355. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60356. },
  60357. enumerable: true,
  60358. configurable: true
  60359. });
  60360. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60361. /**
  60362. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60363. * exponential to prevent steep falloff artifacts).
  60364. */
  60365. get: function () {
  60366. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60367. },
  60368. /**
  60369. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  60370. * exponential to prevent steep falloff artifacts).
  60371. */
  60372. set: function (value) {
  60373. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60374. return;
  60375. }
  60376. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60377. },
  60378. enumerable: true,
  60379. configurable: true
  60380. });
  60381. /**
  60382. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60383. * 0 means strongest and 1 would means no shadow.
  60384. * @returns the darkness.
  60385. */
  60386. ShadowGenerator.prototype.getDarkness = function () {
  60387. return this._darkness;
  60388. };
  60389. /**
  60390. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60391. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60392. * @returns the shadow generator allowing fluent coding.
  60393. */
  60394. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60395. if (darkness >= 1.0)
  60396. this._darkness = 1.0;
  60397. else if (darkness <= 0.0)
  60398. this._darkness = 0.0;
  60399. else
  60400. this._darkness = darkness;
  60401. return this;
  60402. };
  60403. /**
  60404. * Sets the ability to have transparent shadow (boolean).
  60405. * @param transparent True if transparent else False
  60406. * @returns the shadow generator allowing fluent coding
  60407. */
  60408. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60409. this._transparencyShadow = transparent;
  60410. return this;
  60411. };
  60412. /**
  60413. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60414. * @returns The render target texture if present otherwise, null
  60415. */
  60416. ShadowGenerator.prototype.getShadowMap = function () {
  60417. return this._shadowMap;
  60418. };
  60419. /**
  60420. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60421. * @returns The render target texture if the shadow map is present otherwise, null
  60422. */
  60423. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60424. if (this._shadowMap2) {
  60425. return this._shadowMap2;
  60426. }
  60427. return this._shadowMap;
  60428. };
  60429. /**
  60430. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60431. * @param mesh Mesh to add
  60432. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60433. * @returns the Shadow Generator itself
  60434. */
  60435. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60436. if (includeDescendants === void 0) { includeDescendants = true; }
  60437. if (!this._shadowMap) {
  60438. return this;
  60439. }
  60440. if (!this._shadowMap.renderList) {
  60441. this._shadowMap.renderList = [];
  60442. }
  60443. this._shadowMap.renderList.push(mesh);
  60444. if (includeDescendants) {
  60445. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60446. }
  60447. return this;
  60448. var _a;
  60449. };
  60450. /**
  60451. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60452. * @param mesh Mesh to remove
  60453. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60454. * @returns the Shadow Generator itself
  60455. */
  60456. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60457. if (includeDescendants === void 0) { includeDescendants = true; }
  60458. if (!this._shadowMap || !this._shadowMap.renderList) {
  60459. return this;
  60460. }
  60461. var index = this._shadowMap.renderList.indexOf(mesh);
  60462. if (index !== -1) {
  60463. this._shadowMap.renderList.splice(index, 1);
  60464. }
  60465. if (includeDescendants) {
  60466. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60467. var child = _a[_i];
  60468. this.removeShadowCaster(child);
  60469. }
  60470. }
  60471. return this;
  60472. };
  60473. /**
  60474. * Returns the associated light object.
  60475. * @returns the light generating the shadow
  60476. */
  60477. ShadowGenerator.prototype.getLight = function () {
  60478. return this._light;
  60479. };
  60480. ShadowGenerator.prototype._initializeGenerator = function () {
  60481. this._light._markMeshesAsLightDirty();
  60482. this._initializeShadowMap();
  60483. };
  60484. ShadowGenerator.prototype._initializeShadowMap = function () {
  60485. var _this = this;
  60486. // Render target
  60487. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60488. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60489. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60490. this._shadowMap.anisotropicFilteringLevel = 1;
  60491. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60492. this._shadowMap.renderParticles = false;
  60493. this._shadowMap.ignoreCameraViewport = true;
  60494. // Record Face Index before render.
  60495. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60496. _this._currentFaceIndex = faceIndex;
  60497. });
  60498. // Custom render function.
  60499. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60500. // Blur if required afer render.
  60501. this._shadowMap.onAfterUnbindObservable.add(function () {
  60502. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60503. return;
  60504. }
  60505. var shadowMap = _this.getShadowMapForRendering();
  60506. if (shadowMap) {
  60507. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60508. }
  60509. });
  60510. // Clear according to the chosen filter.
  60511. this._shadowMap.onClearObservable.add(function (engine) {
  60512. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60513. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  60514. }
  60515. else {
  60516. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  60517. }
  60518. });
  60519. };
  60520. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60521. var _this = this;
  60522. var engine = this._scene.getEngine();
  60523. var targetSize = this._mapSize / this.blurScale;
  60524. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60525. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60526. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60527. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60528. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60529. }
  60530. if (this.useKernelBlur) {
  60531. 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);
  60532. this._kernelBlurXPostprocess.width = targetSize;
  60533. this._kernelBlurXPostprocess.height = targetSize;
  60534. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60535. effect.setTexture("textureSampler", _this._shadowMap);
  60536. });
  60537. 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);
  60538. this._kernelBlurXPostprocess.autoClear = false;
  60539. this._kernelBlurYPostprocess.autoClear = false;
  60540. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60541. this._kernelBlurXPostprocess.packedFloat = true;
  60542. this._kernelBlurYPostprocess.packedFloat = true;
  60543. }
  60544. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60545. }
  60546. else {
  60547. 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);
  60548. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60549. effect.setFloat2("screenSize", targetSize, targetSize);
  60550. effect.setTexture("textureSampler", _this._shadowMap);
  60551. });
  60552. this._boxBlurPostprocess.autoClear = false;
  60553. this._blurPostProcesses = [this._boxBlurPostprocess];
  60554. }
  60555. };
  60556. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60557. var index;
  60558. var engine = this._scene.getEngine();
  60559. if (depthOnlySubMeshes.length) {
  60560. engine.setColorWrite(false);
  60561. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60562. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60563. }
  60564. engine.setColorWrite(true);
  60565. }
  60566. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60567. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60568. }
  60569. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60570. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60571. }
  60572. if (this._transparencyShadow) {
  60573. for (index = 0; index < transparentSubMeshes.length; index++) {
  60574. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60575. }
  60576. }
  60577. };
  60578. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60579. var _this = this;
  60580. var mesh = subMesh.getRenderingMesh();
  60581. var scene = this._scene;
  60582. var engine = scene.getEngine();
  60583. var material = subMesh.getMaterial();
  60584. if (!material) {
  60585. return;
  60586. }
  60587. // Culling
  60588. engine.setState(material.backFaceCulling);
  60589. // Managing instances
  60590. var batch = mesh._getInstancesRenderList(subMesh._id);
  60591. if (batch.mustReturn) {
  60592. return;
  60593. }
  60594. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60595. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60596. engine.enableEffect(this._effect);
  60597. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60598. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60599. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60600. this._effect.setVector3("lightPosition", this.getLight().position);
  60601. if (scene.activeCamera) {
  60602. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60603. }
  60604. // Alpha test
  60605. if (material && material.needAlphaTesting()) {
  60606. var alphaTexture = material.getAlphaTestTexture();
  60607. if (alphaTexture) {
  60608. this._effect.setTexture("diffuseSampler", alphaTexture);
  60609. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60610. }
  60611. }
  60612. // Bones
  60613. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60614. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60615. }
  60616. if (this.forceBackFacesOnly) {
  60617. engine.setState(true, 0, false, true);
  60618. }
  60619. // Draw
  60620. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60621. if (this.forceBackFacesOnly) {
  60622. engine.setState(true, 0, false, false);
  60623. }
  60624. }
  60625. else {
  60626. // Need to reset refresh rate of the shadowMap
  60627. if (this._shadowMap) {
  60628. this._shadowMap.resetRefreshCounter();
  60629. }
  60630. }
  60631. };
  60632. ShadowGenerator.prototype._applyFilterValues = function () {
  60633. if (!this._shadowMap) {
  60634. return;
  60635. }
  60636. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60637. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60638. }
  60639. else {
  60640. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60641. }
  60642. };
  60643. /**
  60644. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60645. * @param onCompiled Callback triggered at the and of the effects compilation
  60646. * @param options Sets of optional options forcing the compilation with different modes
  60647. */
  60648. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60649. var _this = this;
  60650. var localOptions = __assign({ useInstances: false }, options);
  60651. var shadowMap = this.getShadowMap();
  60652. if (!shadowMap) {
  60653. if (onCompiled) {
  60654. onCompiled(this);
  60655. }
  60656. return;
  60657. }
  60658. var renderList = shadowMap.renderList;
  60659. if (!renderList) {
  60660. if (onCompiled) {
  60661. onCompiled(this);
  60662. }
  60663. return;
  60664. }
  60665. var subMeshes = new Array();
  60666. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60667. var mesh = renderList_1[_i];
  60668. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60669. }
  60670. if (subMeshes.length === 0) {
  60671. if (onCompiled) {
  60672. onCompiled(this);
  60673. }
  60674. return;
  60675. }
  60676. var currentIndex = 0;
  60677. var checkReady = function () {
  60678. if (!_this._scene || !_this._scene.getEngine()) {
  60679. return;
  60680. }
  60681. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60682. currentIndex++;
  60683. if (currentIndex >= subMeshes.length) {
  60684. if (onCompiled) {
  60685. onCompiled(_this);
  60686. }
  60687. return;
  60688. }
  60689. }
  60690. setTimeout(checkReady, 16);
  60691. };
  60692. checkReady();
  60693. };
  60694. /**
  60695. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60696. * @param options Sets of optional options forcing the compilation with different modes
  60697. * @returns A promise that resolves when the compilation completes
  60698. */
  60699. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60700. var _this = this;
  60701. return new Promise(function (resolve) {
  60702. _this.forceCompilation(function () {
  60703. resolve();
  60704. }, options);
  60705. });
  60706. };
  60707. /**
  60708. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60709. * @param subMesh The submesh we want to render in the shadow map
  60710. * @param useInstances Defines wether will draw in the map using instances
  60711. * @returns true if ready otherwise, false
  60712. */
  60713. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60714. var defines = [];
  60715. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60716. defines.push("#define FLOAT");
  60717. }
  60718. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60719. defines.push("#define ESM");
  60720. }
  60721. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60722. var mesh = subMesh.getMesh();
  60723. var material = subMesh.getMaterial();
  60724. // Alpha test
  60725. if (material && material.needAlphaTesting()) {
  60726. var alphaTexture = material.getAlphaTestTexture();
  60727. if (alphaTexture) {
  60728. defines.push("#define ALPHATEST");
  60729. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60730. attribs.push(BABYLON.VertexBuffer.UVKind);
  60731. defines.push("#define UV1");
  60732. }
  60733. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60734. if (alphaTexture.coordinatesIndex === 1) {
  60735. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60736. defines.push("#define UV2");
  60737. }
  60738. }
  60739. }
  60740. }
  60741. // Bones
  60742. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60743. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60744. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60745. if (mesh.numBoneInfluencers > 4) {
  60746. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60747. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60748. }
  60749. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60750. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60751. }
  60752. else {
  60753. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60754. }
  60755. // Instances
  60756. if (useInstances) {
  60757. defines.push("#define INSTANCES");
  60758. attribs.push("world0");
  60759. attribs.push("world1");
  60760. attribs.push("world2");
  60761. attribs.push("world3");
  60762. }
  60763. // Get correct effect
  60764. var join = defines.join("\n");
  60765. if (this._cachedDefines !== join) {
  60766. this._cachedDefines = join;
  60767. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60768. }
  60769. if (!this._effect.isReady()) {
  60770. return false;
  60771. }
  60772. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60773. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60774. this._initializeBlurRTTAndPostProcesses();
  60775. }
  60776. }
  60777. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60778. return false;
  60779. }
  60780. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60781. return false;
  60782. }
  60783. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60784. return false;
  60785. }
  60786. return true;
  60787. };
  60788. /**
  60789. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60790. * @param defines Defines of the material we want to update
  60791. * @param lightIndex Index of the light in the enabled light list of the material
  60792. */
  60793. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60794. var scene = this._scene;
  60795. var light = this._light;
  60796. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60797. return;
  60798. }
  60799. defines["SHADOW" + lightIndex] = true;
  60800. if (this.usePoissonSampling) {
  60801. defines["SHADOWPCF" + lightIndex] = true;
  60802. }
  60803. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60804. defines["SHADOWESM" + lightIndex] = true;
  60805. }
  60806. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60807. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60808. }
  60809. if (light.needCube()) {
  60810. defines["SHADOWCUBE" + lightIndex] = true;
  60811. }
  60812. };
  60813. /**
  60814. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60815. * defined in the generator but impacting the effect).
  60816. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60817. * @param effect The effect we are binfing the information for
  60818. */
  60819. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60820. var light = this._light;
  60821. var scene = this._scene;
  60822. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60823. return;
  60824. }
  60825. var camera = scene.activeCamera;
  60826. if (!camera) {
  60827. return;
  60828. }
  60829. var shadowMap = this.getShadowMap();
  60830. if (!shadowMap) {
  60831. return;
  60832. }
  60833. if (!light.needCube()) {
  60834. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60835. }
  60836. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60837. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60838. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60839. };
  60840. /**
  60841. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60842. * (eq to shadow prjection matrix * light transform matrix)
  60843. * @returns The transform matrix used to create the shadow map
  60844. */
  60845. ShadowGenerator.prototype.getTransformMatrix = function () {
  60846. var scene = this._scene;
  60847. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60848. return this._transformMatrix;
  60849. }
  60850. this._currentRenderID = scene.getRenderId();
  60851. this._currentFaceIndexCache = this._currentFaceIndex;
  60852. var lightPosition = this._light.position;
  60853. if (this._light.computeTransformedInformation()) {
  60854. lightPosition = this._light.transformedPosition;
  60855. }
  60856. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60857. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60858. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60859. }
  60860. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60861. this._cachedPosition = lightPosition.clone();
  60862. this._cachedDirection = this._lightDirection.clone();
  60863. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60864. var shadowMap = this.getShadowMap();
  60865. if (shadowMap) {
  60866. var renderList = shadowMap.renderList;
  60867. if (renderList) {
  60868. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60869. }
  60870. }
  60871. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60872. }
  60873. return this._transformMatrix;
  60874. };
  60875. /**
  60876. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60877. * Cube and 2D textures for instance.
  60878. */
  60879. ShadowGenerator.prototype.recreateShadowMap = function () {
  60880. var shadowMap = this._shadowMap;
  60881. if (!shadowMap) {
  60882. return;
  60883. }
  60884. // Track render list.
  60885. var renderList = shadowMap.renderList;
  60886. // Clean up existing data.
  60887. this._disposeRTTandPostProcesses();
  60888. // Reinitializes.
  60889. this._initializeGenerator();
  60890. // Reaffect the filter to ensure a correct fallback if necessary.
  60891. this.filter = this.filter;
  60892. // Reaffect the filter.
  60893. this._applyFilterValues();
  60894. // Reaffect Render List.
  60895. this._shadowMap.renderList = renderList;
  60896. };
  60897. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60898. if (this._shadowMap2) {
  60899. this._shadowMap2.dispose();
  60900. this._shadowMap2 = null;
  60901. }
  60902. if (this._boxBlurPostprocess) {
  60903. this._boxBlurPostprocess.dispose();
  60904. this._boxBlurPostprocess = null;
  60905. }
  60906. if (this._kernelBlurXPostprocess) {
  60907. this._kernelBlurXPostprocess.dispose();
  60908. this._kernelBlurXPostprocess = null;
  60909. }
  60910. if (this._kernelBlurYPostprocess) {
  60911. this._kernelBlurYPostprocess.dispose();
  60912. this._kernelBlurYPostprocess = null;
  60913. }
  60914. this._blurPostProcesses = [];
  60915. };
  60916. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60917. if (this._shadowMap) {
  60918. this._shadowMap.dispose();
  60919. this._shadowMap = null;
  60920. }
  60921. this._disposeBlurPostProcesses();
  60922. };
  60923. /**
  60924. * Disposes the ShadowGenerator.
  60925. * Returns nothing.
  60926. */
  60927. ShadowGenerator.prototype.dispose = function () {
  60928. this._disposeRTTandPostProcesses();
  60929. if (this._light) {
  60930. this._light._shadowGenerator = null;
  60931. this._light._markMeshesAsLightDirty();
  60932. }
  60933. };
  60934. /**
  60935. * Serializes the shadow generator setup to a json object.
  60936. * @returns The serialized JSON object
  60937. */
  60938. ShadowGenerator.prototype.serialize = function () {
  60939. var serializationObject = {};
  60940. var shadowMap = this.getShadowMap();
  60941. if (!shadowMap) {
  60942. return serializationObject;
  60943. }
  60944. serializationObject.lightId = this._light.id;
  60945. serializationObject.mapSize = shadowMap.getRenderSize();
  60946. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60947. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60948. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60949. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60950. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60951. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60952. serializationObject.depthScale = this.depthScale;
  60953. serializationObject.darkness = this.getDarkness();
  60954. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60955. serializationObject.blurKernel = this.blurKernel;
  60956. serializationObject.blurScale = this.blurScale;
  60957. serializationObject.useKernelBlur = this.useKernelBlur;
  60958. serializationObject.transparencyShadow = this._transparencyShadow;
  60959. serializationObject.renderList = [];
  60960. if (shadowMap.renderList) {
  60961. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60962. var mesh = shadowMap.renderList[meshIndex];
  60963. serializationObject.renderList.push(mesh.id);
  60964. }
  60965. }
  60966. return serializationObject;
  60967. };
  60968. /**
  60969. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60970. * @param parsedShadowGenerator The JSON object to parse
  60971. * @param scene The scene to create the shadow map for
  60972. * @returns The parsed shadow generator
  60973. */
  60974. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60975. //casting to point light, as light is missing the position attr and typescript complains.
  60976. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60977. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60978. var shadowMap = shadowGenerator.getShadowMap();
  60979. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60980. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60981. meshes.forEach(function (mesh) {
  60982. if (!shadowMap) {
  60983. return;
  60984. }
  60985. if (!shadowMap.renderList) {
  60986. shadowMap.renderList = [];
  60987. }
  60988. shadowMap.renderList.push(mesh);
  60989. });
  60990. }
  60991. if (parsedShadowGenerator.usePoissonSampling) {
  60992. shadowGenerator.usePoissonSampling = true;
  60993. }
  60994. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60995. shadowGenerator.useExponentialShadowMap = true;
  60996. }
  60997. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60998. shadowGenerator.useBlurExponentialShadowMap = true;
  60999. }
  61000. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61001. shadowGenerator.useCloseExponentialShadowMap = true;
  61002. }
  61003. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61004. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61005. }
  61006. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61007. shadowGenerator.useExponentialShadowMap = true;
  61008. }
  61009. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61010. shadowGenerator.useBlurExponentialShadowMap = true;
  61011. }
  61012. if (parsedShadowGenerator.depthScale) {
  61013. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61014. }
  61015. if (parsedShadowGenerator.blurScale) {
  61016. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61017. }
  61018. if (parsedShadowGenerator.blurBoxOffset) {
  61019. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61020. }
  61021. if (parsedShadowGenerator.useKernelBlur) {
  61022. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61023. }
  61024. if (parsedShadowGenerator.blurKernel) {
  61025. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61026. }
  61027. if (parsedShadowGenerator.bias !== undefined) {
  61028. shadowGenerator.bias = parsedShadowGenerator.bias;
  61029. }
  61030. if (parsedShadowGenerator.darkness) {
  61031. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61032. }
  61033. if (parsedShadowGenerator.transparencyShadow) {
  61034. shadowGenerator.setTransparencyShadow(true);
  61035. }
  61036. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61037. return shadowGenerator;
  61038. };
  61039. ShadowGenerator._FILTER_NONE = 0;
  61040. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  61041. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  61042. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61043. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61044. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61045. return ShadowGenerator;
  61046. }());
  61047. BABYLON.ShadowGenerator = ShadowGenerator;
  61048. })(BABYLON || (BABYLON = {}));
  61049. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61050. var BABYLON;
  61051. (function (BABYLON) {
  61052. var DefaultLoadingScreen = /** @class */ (function () {
  61053. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61054. if (_loadingText === void 0) { _loadingText = ""; }
  61055. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61056. var _this = this;
  61057. this._renderingCanvas = _renderingCanvas;
  61058. this._loadingText = _loadingText;
  61059. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61060. // Resize
  61061. this._resizeLoadingUI = function () {
  61062. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61063. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61064. if (!_this._loadingDiv) {
  61065. return;
  61066. }
  61067. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61068. _this._loadingDiv.style.left = canvasRect.left + "px";
  61069. _this._loadingDiv.style.top = canvasRect.top + "px";
  61070. _this._loadingDiv.style.width = canvasRect.width + "px";
  61071. _this._loadingDiv.style.height = canvasRect.height + "px";
  61072. };
  61073. }
  61074. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  61075. if (this._loadingDiv) {
  61076. // Do not add a loading screen if there is already one
  61077. return;
  61078. }
  61079. this._loadingDiv = document.createElement("div");
  61080. this._loadingDiv.id = "babylonjsLoadingDiv";
  61081. this._loadingDiv.style.opacity = "0";
  61082. this._loadingDiv.style.transition = "opacity 1.5s ease";
  61083. this._loadingDiv.style.pointerEvents = "none";
  61084. // Loading text
  61085. this._loadingTextDiv = document.createElement("div");
  61086. this._loadingTextDiv.style.position = "absolute";
  61087. this._loadingTextDiv.style.left = "0";
  61088. this._loadingTextDiv.style.top = "50%";
  61089. this._loadingTextDiv.style.marginTop = "80px";
  61090. this._loadingTextDiv.style.width = "100%";
  61091. this._loadingTextDiv.style.height = "20px";
  61092. this._loadingTextDiv.style.fontFamily = "Arial";
  61093. this._loadingTextDiv.style.fontSize = "14px";
  61094. this._loadingTextDiv.style.color = "white";
  61095. this._loadingTextDiv.style.textAlign = "center";
  61096. this._loadingTextDiv.innerHTML = "Loading";
  61097. this._loadingDiv.appendChild(this._loadingTextDiv);
  61098. //set the predefined text
  61099. this._loadingTextDiv.innerHTML = this._loadingText;
  61100. // Generating keyframes
  61101. var style = document.createElement('style');
  61102. style.type = 'text/css';
  61103. 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 }";
  61104. style.innerHTML = keyFrames;
  61105. document.getElementsByTagName('head')[0].appendChild(style);
  61106. // Loading img
  61107. var imgBack = new Image();
  61108. 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";
  61109. imgBack.style.position = "absolute";
  61110. imgBack.style.left = "50%";
  61111. imgBack.style.top = "50%";
  61112. imgBack.style.marginLeft = "-60px";
  61113. imgBack.style.marginTop = "-60px";
  61114. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  61115. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  61116. imgBack.style.transformOrigin = "50% 50%";
  61117. imgBack.style.webkitTransformOrigin = "50% 50%";
  61118. this._loadingDiv.appendChild(imgBack);
  61119. this._resizeLoadingUI();
  61120. window.addEventListener("resize", this._resizeLoadingUI);
  61121. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61122. document.body.appendChild(this._loadingDiv);
  61123. this._loadingDiv.style.opacity = "1";
  61124. };
  61125. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  61126. var _this = this;
  61127. if (!this._loadingDiv) {
  61128. return;
  61129. }
  61130. var onTransitionEnd = function () {
  61131. if (!_this._loadingDiv) {
  61132. return;
  61133. }
  61134. document.body.removeChild(_this._loadingDiv);
  61135. window.removeEventListener("resize", _this._resizeLoadingUI);
  61136. _this._loadingDiv = null;
  61137. };
  61138. this._loadingDiv.style.opacity = "0";
  61139. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  61140. };
  61141. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  61142. set: function (text) {
  61143. this._loadingText = text;
  61144. if (this._loadingTextDiv) {
  61145. this._loadingTextDiv.innerHTML = this._loadingText;
  61146. }
  61147. },
  61148. enumerable: true,
  61149. configurable: true
  61150. });
  61151. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  61152. get: function () {
  61153. return this._loadingDivBackgroundColor;
  61154. },
  61155. set: function (color) {
  61156. this._loadingDivBackgroundColor = color;
  61157. if (!this._loadingDiv) {
  61158. return;
  61159. }
  61160. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61161. },
  61162. enumerable: true,
  61163. configurable: true
  61164. });
  61165. return DefaultLoadingScreen;
  61166. }());
  61167. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  61168. })(BABYLON || (BABYLON = {}));
  61169. //# sourceMappingURL=babylon.loadingScreen.js.map
  61170. var BABYLON;
  61171. (function (BABYLON) {
  61172. var SceneLoaderProgressEvent = /** @class */ (function () {
  61173. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  61174. this.lengthComputable = lengthComputable;
  61175. this.loaded = loaded;
  61176. this.total = total;
  61177. }
  61178. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  61179. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  61180. };
  61181. return SceneLoaderProgressEvent;
  61182. }());
  61183. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  61184. var SceneLoader = /** @class */ (function () {
  61185. function SceneLoader() {
  61186. }
  61187. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  61188. get: function () {
  61189. return 0;
  61190. },
  61191. enumerable: true,
  61192. configurable: true
  61193. });
  61194. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  61195. get: function () {
  61196. return 1;
  61197. },
  61198. enumerable: true,
  61199. configurable: true
  61200. });
  61201. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  61202. get: function () {
  61203. return 2;
  61204. },
  61205. enumerable: true,
  61206. configurable: true
  61207. });
  61208. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  61209. get: function () {
  61210. return 3;
  61211. },
  61212. enumerable: true,
  61213. configurable: true
  61214. });
  61215. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  61216. get: function () {
  61217. return SceneLoader._ForceFullSceneLoadingForIncremental;
  61218. },
  61219. set: function (value) {
  61220. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  61221. },
  61222. enumerable: true,
  61223. configurable: true
  61224. });
  61225. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  61226. get: function () {
  61227. return SceneLoader._ShowLoadingScreen;
  61228. },
  61229. set: function (value) {
  61230. SceneLoader._ShowLoadingScreen = value;
  61231. },
  61232. enumerable: true,
  61233. configurable: true
  61234. });
  61235. Object.defineProperty(SceneLoader, "loggingLevel", {
  61236. get: function () {
  61237. return SceneLoader._loggingLevel;
  61238. },
  61239. set: function (value) {
  61240. SceneLoader._loggingLevel = value;
  61241. },
  61242. enumerable: true,
  61243. configurable: true
  61244. });
  61245. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61246. get: function () {
  61247. return SceneLoader._CleanBoneMatrixWeights;
  61248. },
  61249. set: function (value) {
  61250. SceneLoader._CleanBoneMatrixWeights = value;
  61251. },
  61252. enumerable: true,
  61253. configurable: true
  61254. });
  61255. SceneLoader._getDefaultPlugin = function () {
  61256. return SceneLoader._registeredPlugins[".babylon"];
  61257. };
  61258. SceneLoader._getPluginForExtension = function (extension) {
  61259. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61260. if (registeredPlugin) {
  61261. return registeredPlugin;
  61262. }
  61263. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61264. return SceneLoader._getDefaultPlugin();
  61265. };
  61266. SceneLoader._getPluginForDirectLoad = function (data) {
  61267. for (var extension in SceneLoader._registeredPlugins) {
  61268. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61269. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61270. return SceneLoader._registeredPlugins[extension];
  61271. }
  61272. }
  61273. return SceneLoader._getDefaultPlugin();
  61274. };
  61275. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61276. if (sceneFilename.name) {
  61277. sceneFilename = sceneFilename.name;
  61278. }
  61279. var queryStringPosition = sceneFilename.indexOf("?");
  61280. if (queryStringPosition !== -1) {
  61281. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61282. }
  61283. var dotPosition = sceneFilename.lastIndexOf(".");
  61284. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61285. return SceneLoader._getPluginForExtension(extension);
  61286. };
  61287. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61288. SceneLoader._getDirectLoad = function (sceneFilename) {
  61289. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61290. return sceneFilename.substr(5);
  61291. }
  61292. return null;
  61293. };
  61294. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61295. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61296. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61297. var plugin;
  61298. if (registeredPlugin.plugin.createPlugin) {
  61299. plugin = registeredPlugin.plugin.createPlugin();
  61300. }
  61301. else {
  61302. plugin = registeredPlugin.plugin;
  61303. }
  61304. var useArrayBuffer = registeredPlugin.isBinary;
  61305. var database;
  61306. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61307. var dataCallback = function (data, responseURL) {
  61308. if (scene.isDisposed) {
  61309. onError("Scene has been disposed");
  61310. return;
  61311. }
  61312. scene.database = database;
  61313. onSuccess(plugin, data, responseURL);
  61314. };
  61315. var request = null;
  61316. var pluginDisposed = false;
  61317. var onDisposeObservable = plugin.onDisposeObservable;
  61318. if (onDisposeObservable) {
  61319. onDisposeObservable.add(function () {
  61320. pluginDisposed = true;
  61321. if (request) {
  61322. request.abort();
  61323. request = null;
  61324. }
  61325. onDispose();
  61326. });
  61327. }
  61328. var manifestChecked = function () {
  61329. if (pluginDisposed) {
  61330. return;
  61331. }
  61332. var url = rootUrl + sceneFilename;
  61333. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61334. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61335. } : undefined, database, useArrayBuffer, function (request, exception) {
  61336. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61337. });
  61338. };
  61339. if (directLoad) {
  61340. dataCallback(directLoad);
  61341. return plugin;
  61342. }
  61343. if (rootUrl.indexOf("file:") === -1) {
  61344. if (scene.getEngine().enableOfflineSupport) {
  61345. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61346. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61347. }
  61348. else {
  61349. manifestChecked();
  61350. }
  61351. }
  61352. else {
  61353. var fileOrString = sceneFilename;
  61354. if (fileOrString.name) {
  61355. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61356. }
  61357. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61358. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61359. }
  61360. else {
  61361. onError("Unable to find file named " + sceneFilename);
  61362. }
  61363. }
  61364. return plugin;
  61365. };
  61366. // Public functions
  61367. SceneLoader.GetPluginForExtension = function (extension) {
  61368. return SceneLoader._getPluginForExtension(extension).plugin;
  61369. };
  61370. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61371. return !!SceneLoader._registeredPlugins[extension];
  61372. };
  61373. SceneLoader.RegisterPlugin = function (plugin) {
  61374. if (typeof plugin.extensions === "string") {
  61375. var extension = plugin.extensions;
  61376. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61377. plugin: plugin,
  61378. isBinary: false
  61379. };
  61380. }
  61381. else {
  61382. var extensions = plugin.extensions;
  61383. Object.keys(extensions).forEach(function (extension) {
  61384. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61385. plugin: plugin,
  61386. isBinary: extensions[extension].isBinary
  61387. };
  61388. });
  61389. }
  61390. };
  61391. /**
  61392. * Import meshes into a scene
  61393. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61394. * @param rootUrl a string that defines the root url for scene and resources
  61395. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61396. * @param scene the instance of BABYLON.Scene to append to
  61397. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61398. * @param onProgress a callback with a progress event for each file being loaded
  61399. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61400. * @param pluginExtension the extension used to determine the plugin
  61401. * @returns The loaded plugin
  61402. */
  61403. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61404. if (onSuccess === void 0) { onSuccess = null; }
  61405. if (onProgress === void 0) { onProgress = null; }
  61406. if (onError === void 0) { onError = null; }
  61407. if (pluginExtension === void 0) { pluginExtension = null; }
  61408. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61409. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61410. return null;
  61411. }
  61412. var loadingToken = {};
  61413. scene._addPendingData(loadingToken);
  61414. var disposeHandler = function () {
  61415. scene._removePendingData(loadingToken);
  61416. };
  61417. var errorHandler = function (message, exception) {
  61418. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61419. if (onError) {
  61420. onError(scene, errorMessage, exception);
  61421. }
  61422. else {
  61423. BABYLON.Tools.Error(errorMessage);
  61424. // should the exception be thrown?
  61425. }
  61426. disposeHandler();
  61427. };
  61428. var progressHandler = onProgress ? function (event) {
  61429. try {
  61430. onProgress(event);
  61431. }
  61432. catch (e) {
  61433. errorHandler("Error in onProgress callback", e);
  61434. }
  61435. } : undefined;
  61436. var successHandler = function (meshes, particleSystems, skeletons) {
  61437. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61438. if (onSuccess) {
  61439. try {
  61440. onSuccess(meshes, particleSystems, skeletons);
  61441. }
  61442. catch (e) {
  61443. errorHandler("Error in onSuccess callback", e);
  61444. }
  61445. }
  61446. scene._removePendingData(loadingToken);
  61447. };
  61448. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61449. if (plugin.rewriteRootURL) {
  61450. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61451. }
  61452. if (sceneFilename === "") {
  61453. if (sceneFilename === "") {
  61454. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61455. }
  61456. }
  61457. if (plugin.importMesh) {
  61458. var syncedPlugin = plugin;
  61459. var meshes = new Array();
  61460. var particleSystems = new Array();
  61461. var skeletons = new Array();
  61462. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61463. return;
  61464. }
  61465. scene.loadingPluginName = plugin.name;
  61466. successHandler(meshes, particleSystems, skeletons);
  61467. }
  61468. else {
  61469. var asyncedPlugin = plugin;
  61470. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61471. scene.loadingPluginName = plugin.name;
  61472. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61473. }).catch(function (error) {
  61474. errorHandler(error.message, error);
  61475. });
  61476. }
  61477. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61478. };
  61479. /**
  61480. * Import meshes into a scene
  61481. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61482. * @param rootUrl a string that defines the root url for scene and resources
  61483. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61484. * @param scene the instance of BABYLON.Scene to append to
  61485. * @param onProgress a callback with a progress event for each file being loaded
  61486. * @param pluginExtension the extension used to determine the plugin
  61487. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61488. */
  61489. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61490. if (onProgress === void 0) { onProgress = null; }
  61491. if (pluginExtension === void 0) { pluginExtension = null; }
  61492. return new Promise(function (resolve, reject) {
  61493. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61494. resolve({
  61495. meshes: meshes,
  61496. particleSystems: particleSystems,
  61497. skeletons: skeletons
  61498. });
  61499. }, onProgress, function (scene, message, exception) {
  61500. reject(exception || new Error(message));
  61501. });
  61502. });
  61503. };
  61504. /**
  61505. * Load a scene
  61506. * @param rootUrl a string that defines the root url for scene and resources
  61507. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61508. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61509. * @param onSuccess a callback with the scene when import succeeds
  61510. * @param onProgress a callback with a progress event for each file being loaded
  61511. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61512. * @param pluginExtension the extension used to determine the plugin
  61513. * @returns The loaded plugin
  61514. */
  61515. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61516. if (onSuccess === void 0) { onSuccess = null; }
  61517. if (onProgress === void 0) { onProgress = null; }
  61518. if (onError === void 0) { onError = null; }
  61519. if (pluginExtension === void 0) { pluginExtension = null; }
  61520. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61521. };
  61522. /**
  61523. * Load a scene
  61524. * @param rootUrl a string that defines the root url for scene and resources
  61525. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61526. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61527. * @param onProgress a callback with a progress event for each file being loaded
  61528. * @param pluginExtension the extension used to determine the plugin
  61529. * @returns The loaded scene
  61530. */
  61531. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61532. if (onProgress === void 0) { onProgress = null; }
  61533. if (pluginExtension === void 0) { pluginExtension = null; }
  61534. return new Promise(function (resolve, reject) {
  61535. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61536. resolve(scene);
  61537. }, onProgress, function (scene, message, exception) {
  61538. reject(exception || new Error(message));
  61539. }, pluginExtension);
  61540. });
  61541. };
  61542. /**
  61543. * Append a scene
  61544. * @param rootUrl a string that defines the root url for scene and resources
  61545. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61546. * @param scene is the instance of BABYLON.Scene to append to
  61547. * @param onSuccess a callback with the scene when import succeeds
  61548. * @param onProgress a callback with a progress event for each file being loaded
  61549. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61550. * @param pluginExtension the extension used to determine the plugin
  61551. * @returns The loaded plugin
  61552. */
  61553. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61554. if (onSuccess === void 0) { onSuccess = null; }
  61555. if (onProgress === void 0) { onProgress = null; }
  61556. if (onError === void 0) { onError = null; }
  61557. if (pluginExtension === void 0) { pluginExtension = null; }
  61558. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61559. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61560. return null;
  61561. }
  61562. if (SceneLoader.ShowLoadingScreen) {
  61563. scene.getEngine().displayLoadingUI();
  61564. }
  61565. var loadingToken = {};
  61566. scene._addPendingData(loadingToken);
  61567. var disposeHandler = function () {
  61568. scene._removePendingData(loadingToken);
  61569. scene.getEngine().hideLoadingUI();
  61570. };
  61571. var errorHandler = function (message, exception) {
  61572. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61573. if (onError) {
  61574. onError(scene, errorMessage, exception);
  61575. }
  61576. else {
  61577. BABYLON.Tools.Error(errorMessage);
  61578. // should the exception be thrown?
  61579. }
  61580. disposeHandler();
  61581. };
  61582. var progressHandler = onProgress ? function (event) {
  61583. try {
  61584. onProgress(event);
  61585. }
  61586. catch (e) {
  61587. errorHandler("Error in onProgress callback", e);
  61588. }
  61589. } : undefined;
  61590. var successHandler = function () {
  61591. if (onSuccess) {
  61592. try {
  61593. onSuccess(scene);
  61594. }
  61595. catch (e) {
  61596. errorHandler("Error in onSuccess callback", e);
  61597. }
  61598. }
  61599. scene._removePendingData(loadingToken);
  61600. };
  61601. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61602. if (sceneFilename === "") {
  61603. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61604. }
  61605. if (plugin.load) {
  61606. var syncedPlugin = plugin;
  61607. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61608. return;
  61609. }
  61610. scene.loadingPluginName = plugin.name;
  61611. successHandler();
  61612. }
  61613. else {
  61614. var asyncedPlugin = plugin;
  61615. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61616. scene.loadingPluginName = plugin.name;
  61617. successHandler();
  61618. }).catch(function (error) {
  61619. errorHandler(error.message, error);
  61620. });
  61621. }
  61622. if (SceneLoader.ShowLoadingScreen) {
  61623. scene.executeWhenReady(function () {
  61624. scene.getEngine().hideLoadingUI();
  61625. });
  61626. }
  61627. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61628. };
  61629. /**
  61630. * Append a scene
  61631. * @param rootUrl a string that defines the root url for scene and resources
  61632. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61633. * @param scene is the instance of BABYLON.Scene to append to
  61634. * @param onProgress a callback with a progress event for each file being loaded
  61635. * @param pluginExtension the extension used to determine the plugin
  61636. * @returns The given scene
  61637. */
  61638. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61639. if (onProgress === void 0) { onProgress = null; }
  61640. if (pluginExtension === void 0) { pluginExtension = null; }
  61641. return new Promise(function (resolve, reject) {
  61642. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61643. resolve(scene);
  61644. }, onProgress, function (scene, message, exception) {
  61645. reject(exception || new Error(message));
  61646. }, pluginExtension);
  61647. });
  61648. };
  61649. /**
  61650. * Load a scene into an asset container
  61651. * @param rootUrl a string that defines the root url for scene and resources
  61652. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61653. * @param scene is the instance of BABYLON.Scene to append to
  61654. * @param onSuccess a callback with the scene when import succeeds
  61655. * @param onProgress a callback with a progress event for each file being loaded
  61656. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61657. * @param pluginExtension the extension used to determine the plugin
  61658. * @returns The loaded plugin
  61659. */
  61660. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61661. if (onSuccess === void 0) { onSuccess = null; }
  61662. if (onProgress === void 0) { onProgress = null; }
  61663. if (onError === void 0) { onError = null; }
  61664. if (pluginExtension === void 0) { pluginExtension = null; }
  61665. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61666. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61667. return null;
  61668. }
  61669. var loadingToken = {};
  61670. scene._addPendingData(loadingToken);
  61671. var disposeHandler = function () {
  61672. scene._removePendingData(loadingToken);
  61673. };
  61674. var errorHandler = function (message, exception) {
  61675. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61676. if (onError) {
  61677. onError(scene, errorMessage, exception);
  61678. }
  61679. else {
  61680. BABYLON.Tools.Error(errorMessage);
  61681. // should the exception be thrown?
  61682. }
  61683. disposeHandler();
  61684. };
  61685. var progressHandler = onProgress ? function (event) {
  61686. try {
  61687. onProgress(event);
  61688. }
  61689. catch (e) {
  61690. errorHandler("Error in onProgress callback", e);
  61691. }
  61692. } : undefined;
  61693. var successHandler = function (assets) {
  61694. if (onSuccess) {
  61695. try {
  61696. onSuccess(assets);
  61697. }
  61698. catch (e) {
  61699. errorHandler("Error in onSuccess callback", e);
  61700. }
  61701. }
  61702. scene._removePendingData(loadingToken);
  61703. };
  61704. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61705. if (plugin.loadAssetContainer) {
  61706. var syncedPlugin = plugin;
  61707. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61708. if (!assetContainer) {
  61709. return;
  61710. }
  61711. scene.loadingPluginName = plugin.name;
  61712. successHandler(assetContainer);
  61713. }
  61714. else if (plugin.loadAssetContainerAsync) {
  61715. var asyncedPlugin = plugin;
  61716. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61717. scene.loadingPluginName = plugin.name;
  61718. successHandler(assetContainer);
  61719. }).catch(function (error) {
  61720. errorHandler(error.message, error);
  61721. });
  61722. }
  61723. else {
  61724. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61725. }
  61726. if (SceneLoader.ShowLoadingScreen) {
  61727. scene.executeWhenReady(function () {
  61728. scene.getEngine().hideLoadingUI();
  61729. });
  61730. }
  61731. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61732. };
  61733. /**
  61734. * Load a scene into an asset container
  61735. * @param rootUrl a string that defines the root url for scene and resources
  61736. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61737. * @param scene is the instance of BABYLON.Scene to append to
  61738. * @param onProgress a callback with a progress event for each file being loaded
  61739. * @param pluginExtension the extension used to determine the plugin
  61740. * @returns The loaded asset container
  61741. */
  61742. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61743. if (onProgress === void 0) { onProgress = null; }
  61744. if (pluginExtension === void 0) { pluginExtension = null; }
  61745. return new Promise(function (resolve, reject) {
  61746. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61747. resolve(assetContainer);
  61748. }, onProgress, function (scene, message, exception) {
  61749. reject(exception || new Error(message));
  61750. }, pluginExtension);
  61751. });
  61752. };
  61753. // Flags
  61754. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61755. SceneLoader._ShowLoadingScreen = true;
  61756. SceneLoader._CleanBoneMatrixWeights = false;
  61757. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61758. // Members
  61759. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61760. SceneLoader._registeredPlugins = {};
  61761. return SceneLoader;
  61762. }());
  61763. BABYLON.SceneLoader = SceneLoader;
  61764. ;
  61765. })(BABYLON || (BABYLON = {}));
  61766. //# sourceMappingURL=babylon.sceneLoader.js.map
  61767. var BABYLON;
  61768. (function (BABYLON) {
  61769. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61770. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61771. var parsedMaterial = parsedData.materials[index];
  61772. if (parsedMaterial.id === id) {
  61773. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61774. }
  61775. }
  61776. return null;
  61777. };
  61778. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61779. for (var i in names) {
  61780. if (mesh.name === names[i]) {
  61781. hierarchyIds.push(mesh.id);
  61782. return true;
  61783. }
  61784. }
  61785. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61786. hierarchyIds.push(mesh.id);
  61787. return true;
  61788. }
  61789. return false;
  61790. };
  61791. var logOperation = function (operation, producer) {
  61792. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61793. };
  61794. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61795. if (addToScene === void 0) { addToScene = false; }
  61796. var container = new BABYLON.AssetContainer(scene);
  61797. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61798. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61799. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61800. // and avoid problems with multiple concurrent .babylon loads.
  61801. var log = "importScene has failed JSON parse";
  61802. try {
  61803. var parsedData = JSON.parse(data);
  61804. log = "";
  61805. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61806. var index;
  61807. var cache;
  61808. // Lights
  61809. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61810. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61811. var parsedLight = parsedData.lights[index];
  61812. var light = BABYLON.Light.Parse(parsedLight, scene);
  61813. if (light) {
  61814. container.lights.push(light);
  61815. log += (index === 0 ? "\n\tLights:" : "");
  61816. log += "\n\t\t" + light.toString(fullDetails);
  61817. }
  61818. }
  61819. }
  61820. // Animations
  61821. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61822. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61823. var parsedAnimation = parsedData.animations[index];
  61824. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61825. scene.animations.push(animation);
  61826. container.animations.push(animation);
  61827. log += (index === 0 ? "\n\tAnimations:" : "");
  61828. log += "\n\t\t" + animation.toString(fullDetails);
  61829. }
  61830. }
  61831. // Materials
  61832. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61833. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61834. var parsedMaterial = parsedData.materials[index];
  61835. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61836. container.materials.push(mat);
  61837. log += (index === 0 ? "\n\tMaterials:" : "");
  61838. log += "\n\t\t" + mat.toString(fullDetails);
  61839. }
  61840. }
  61841. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61842. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61843. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61844. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61845. container.multiMaterials.push(mmat);
  61846. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61847. log += "\n\t\t" + mmat.toString(fullDetails);
  61848. }
  61849. }
  61850. // Morph targets
  61851. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61852. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61853. var managerData = _a[_i];
  61854. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61855. }
  61856. }
  61857. // Skeletons
  61858. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61859. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61860. var parsedSkeleton = parsedData.skeletons[index];
  61861. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61862. container.skeletons.push(skeleton);
  61863. log += (index === 0 ? "\n\tSkeletons:" : "");
  61864. log += "\n\t\t" + skeleton.toString(fullDetails);
  61865. }
  61866. }
  61867. // Geometries
  61868. var geometries = parsedData.geometries;
  61869. if (geometries !== undefined && geometries !== null) {
  61870. var addedGeometry = new Array();
  61871. // Boxes
  61872. var boxes = geometries.boxes;
  61873. if (boxes !== undefined && boxes !== null) {
  61874. for (index = 0, cache = boxes.length; index < cache; index++) {
  61875. var parsedBox = boxes[index];
  61876. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61877. }
  61878. }
  61879. // Spheres
  61880. var spheres = geometries.spheres;
  61881. if (spheres !== undefined && spheres !== null) {
  61882. for (index = 0, cache = spheres.length; index < cache; index++) {
  61883. var parsedSphere = spheres[index];
  61884. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61885. }
  61886. }
  61887. // Cylinders
  61888. var cylinders = geometries.cylinders;
  61889. if (cylinders !== undefined && cylinders !== null) {
  61890. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61891. var parsedCylinder = cylinders[index];
  61892. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61893. }
  61894. }
  61895. // Toruses
  61896. var toruses = geometries.toruses;
  61897. if (toruses !== undefined && toruses !== null) {
  61898. for (index = 0, cache = toruses.length; index < cache; index++) {
  61899. var parsedTorus = toruses[index];
  61900. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61901. }
  61902. }
  61903. // Grounds
  61904. var grounds = geometries.grounds;
  61905. if (grounds !== undefined && grounds !== null) {
  61906. for (index = 0, cache = grounds.length; index < cache; index++) {
  61907. var parsedGround = grounds[index];
  61908. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61909. }
  61910. }
  61911. // Planes
  61912. var planes = geometries.planes;
  61913. if (planes !== undefined && planes !== null) {
  61914. for (index = 0, cache = planes.length; index < cache; index++) {
  61915. var parsedPlane = planes[index];
  61916. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61917. }
  61918. }
  61919. // TorusKnots
  61920. var torusKnots = geometries.torusKnots;
  61921. if (torusKnots !== undefined && torusKnots !== null) {
  61922. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61923. var parsedTorusKnot = torusKnots[index];
  61924. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61925. }
  61926. }
  61927. // VertexData
  61928. var vertexData = geometries.vertexData;
  61929. if (vertexData !== undefined && vertexData !== null) {
  61930. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61931. var parsedVertexData = vertexData[index];
  61932. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61933. }
  61934. }
  61935. addedGeometry.forEach(function (g) {
  61936. if (g) {
  61937. container.geometries.push(g);
  61938. }
  61939. });
  61940. }
  61941. // Transform nodes
  61942. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61943. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61944. var parsedTransformNode = parsedData.transformNodes[index];
  61945. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61946. container.transformNodes.push(node);
  61947. }
  61948. }
  61949. // Meshes
  61950. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61951. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61952. var parsedMesh = parsedData.meshes[index];
  61953. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61954. container.meshes.push(mesh);
  61955. log += (index === 0 ? "\n\tMeshes:" : "");
  61956. log += "\n\t\t" + mesh.toString(fullDetails);
  61957. }
  61958. }
  61959. // Cameras
  61960. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61961. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61962. var parsedCamera = parsedData.cameras[index];
  61963. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61964. container.cameras.push(camera);
  61965. log += (index === 0 ? "\n\tCameras:" : "");
  61966. log += "\n\t\t" + camera.toString(fullDetails);
  61967. }
  61968. }
  61969. // Browsing all the graph to connect the dots
  61970. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61971. var camera = scene.cameras[index];
  61972. if (camera._waitingParentId) {
  61973. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61974. camera._waitingParentId = null;
  61975. }
  61976. }
  61977. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61978. var light_1 = scene.lights[index];
  61979. if (light_1 && light_1._waitingParentId) {
  61980. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61981. light_1._waitingParentId = null;
  61982. }
  61983. }
  61984. // Sounds
  61985. // TODO: add sound
  61986. var loadedSounds = [];
  61987. var loadedSound;
  61988. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61989. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61990. var parsedSound = parsedData.sounds[index];
  61991. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61992. if (!parsedSound.url)
  61993. parsedSound.url = parsedSound.name;
  61994. if (!loadedSounds[parsedSound.url]) {
  61995. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61996. loadedSounds[parsedSound.url] = loadedSound;
  61997. container.sounds.push(loadedSound);
  61998. }
  61999. else {
  62000. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62001. }
  62002. }
  62003. else {
  62004. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62005. }
  62006. }
  62007. }
  62008. loadedSounds = [];
  62009. // Connect parents & children and parse actions
  62010. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62011. var transformNode = scene.transformNodes[index];
  62012. if (transformNode._waitingParentId) {
  62013. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62014. transformNode._waitingParentId = null;
  62015. }
  62016. }
  62017. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62018. var mesh = scene.meshes[index];
  62019. if (mesh._waitingParentId) {
  62020. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62021. mesh._waitingParentId = null;
  62022. }
  62023. if (mesh._waitingActions) {
  62024. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62025. mesh._waitingActions = null;
  62026. }
  62027. }
  62028. // freeze world matrix application
  62029. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62030. var currentMesh = scene.meshes[index];
  62031. if (currentMesh._waitingFreezeWorldMatrix) {
  62032. currentMesh.freezeWorldMatrix();
  62033. currentMesh._waitingFreezeWorldMatrix = null;
  62034. }
  62035. else {
  62036. currentMesh.computeWorldMatrix(true);
  62037. }
  62038. }
  62039. // Particles Systems
  62040. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62041. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62042. var parsedParticleSystem = parsedData.particleSystems[index];
  62043. if (parsedParticleSystem.activeParticleCount) {
  62044. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62045. container.particleSystems.push(ps);
  62046. }
  62047. else {
  62048. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62049. container.particleSystems.push(ps);
  62050. }
  62051. }
  62052. }
  62053. // Lens flares
  62054. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62055. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62056. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62057. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62058. container.lensFlareSystems.push(lf);
  62059. }
  62060. }
  62061. // Shadows
  62062. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62063. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62064. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62065. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62066. container.shadowGenerators.push(sg);
  62067. }
  62068. }
  62069. // Lights exclusions / inclusions
  62070. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62071. var light_2 = scene.lights[index];
  62072. // Excluded check
  62073. if (light_2._excludedMeshesIds.length > 0) {
  62074. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  62075. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  62076. if (excludedMesh) {
  62077. light_2.excludedMeshes.push(excludedMesh);
  62078. }
  62079. }
  62080. light_2._excludedMeshesIds = [];
  62081. }
  62082. // Included check
  62083. if (light_2._includedOnlyMeshesIds.length > 0) {
  62084. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  62085. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  62086. if (includedOnlyMesh) {
  62087. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  62088. }
  62089. }
  62090. light_2._includedOnlyMeshesIds = [];
  62091. }
  62092. }
  62093. // Actions (scene)
  62094. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  62095. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  62096. }
  62097. if (!addToScene) {
  62098. container.removeAllFromScene();
  62099. }
  62100. }
  62101. catch (err) {
  62102. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  62103. if (onError) {
  62104. onError(msg, err);
  62105. }
  62106. else {
  62107. BABYLON.Tools.Log(msg);
  62108. throw err;
  62109. }
  62110. }
  62111. finally {
  62112. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62113. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62114. }
  62115. }
  62116. return container;
  62117. };
  62118. BABYLON.SceneLoader.RegisterPlugin({
  62119. name: "babylon.js",
  62120. extensions: ".babylon",
  62121. canDirectLoad: function (data) {
  62122. if (data.indexOf("babylon") !== -1) {
  62123. return true;
  62124. }
  62125. return false;
  62126. },
  62127. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  62128. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62129. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62130. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62131. // and avoid problems with multiple concurrent .babylon loads.
  62132. var log = "importMesh has failed JSON parse";
  62133. try {
  62134. var parsedData = JSON.parse(data);
  62135. log = "";
  62136. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62137. if (!meshesNames) {
  62138. meshesNames = null;
  62139. }
  62140. else if (!Array.isArray(meshesNames)) {
  62141. meshesNames = [meshesNames];
  62142. }
  62143. var hierarchyIds = new Array();
  62144. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62145. var loadedSkeletonsIds = [];
  62146. var loadedMaterialsIds = [];
  62147. var index;
  62148. var cache;
  62149. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62150. var parsedMesh = parsedData.meshes[index];
  62151. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  62152. if (meshesNames !== null) {
  62153. // Remove found mesh name from list.
  62154. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  62155. }
  62156. //Geometry?
  62157. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  62158. //does the file contain geometries?
  62159. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  62160. //find the correct geometry and add it to the scene
  62161. var found = false;
  62162. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  62163. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  62164. return;
  62165. }
  62166. else {
  62167. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  62168. if (parsedGeometryData.id === parsedMesh.geometryId) {
  62169. switch (geometryType) {
  62170. case "boxes":
  62171. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  62172. break;
  62173. case "spheres":
  62174. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  62175. break;
  62176. case "cylinders":
  62177. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  62178. break;
  62179. case "toruses":
  62180. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  62181. break;
  62182. case "grounds":
  62183. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  62184. break;
  62185. case "planes":
  62186. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  62187. break;
  62188. case "torusKnots":
  62189. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  62190. break;
  62191. case "vertexData":
  62192. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  62193. break;
  62194. }
  62195. found = true;
  62196. }
  62197. });
  62198. }
  62199. });
  62200. if (found === false) {
  62201. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  62202. }
  62203. }
  62204. }
  62205. // Material ?
  62206. if (parsedMesh.materialId) {
  62207. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  62208. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62209. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  62210. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  62211. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  62212. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  62213. var subMatId = parsedMultiMaterial.materials[matIndex];
  62214. loadedMaterialsIds.push(subMatId);
  62215. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  62216. if (mat) {
  62217. log += "\n\tMaterial " + mat.toString(fullDetails);
  62218. }
  62219. }
  62220. loadedMaterialsIds.push(parsedMultiMaterial.id);
  62221. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62222. if (mmat) {
  62223. materialFound = true;
  62224. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  62225. }
  62226. break;
  62227. }
  62228. }
  62229. }
  62230. if (materialFound === false) {
  62231. loadedMaterialsIds.push(parsedMesh.materialId);
  62232. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  62233. if (!mat) {
  62234. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  62235. }
  62236. else {
  62237. log += "\n\tMaterial " + mat.toString(fullDetails);
  62238. }
  62239. }
  62240. }
  62241. // Skeleton ?
  62242. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62243. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62244. if (skeletonAlreadyLoaded === false) {
  62245. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62246. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62247. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62248. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62249. skeletons.push(skeleton);
  62250. loadedSkeletonsIds.push(parsedSkeleton.id);
  62251. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62252. }
  62253. }
  62254. }
  62255. }
  62256. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62257. meshes.push(mesh);
  62258. log += "\n\tMesh " + mesh.toString(fullDetails);
  62259. }
  62260. }
  62261. // Connecting parents
  62262. var currentMesh;
  62263. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62264. currentMesh = scene.meshes[index];
  62265. if (currentMesh._waitingParentId) {
  62266. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62267. currentMesh._waitingParentId = null;
  62268. }
  62269. }
  62270. // freeze and compute world matrix application
  62271. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62272. currentMesh = scene.meshes[index];
  62273. if (currentMesh._waitingFreezeWorldMatrix) {
  62274. currentMesh.freezeWorldMatrix();
  62275. currentMesh._waitingFreezeWorldMatrix = null;
  62276. }
  62277. else {
  62278. currentMesh.computeWorldMatrix(true);
  62279. }
  62280. }
  62281. }
  62282. // Particles
  62283. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62284. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62285. var parsedParticleSystem = parsedData.particleSystems[index];
  62286. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62287. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62288. }
  62289. }
  62290. }
  62291. return true;
  62292. }
  62293. catch (err) {
  62294. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62295. if (onError) {
  62296. onError(msg, err);
  62297. }
  62298. else {
  62299. BABYLON.Tools.Log(msg);
  62300. throw err;
  62301. }
  62302. }
  62303. finally {
  62304. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62305. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62306. }
  62307. }
  62308. return false;
  62309. },
  62310. load: function (scene, data, rootUrl, onError) {
  62311. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62312. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62313. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62314. // and avoid problems with multiple concurrent .babylon loads.
  62315. var log = "importScene has failed JSON parse";
  62316. try {
  62317. var parsedData = JSON.parse(data);
  62318. log = "";
  62319. // Scene
  62320. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62321. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62322. }
  62323. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62324. scene.autoClear = parsedData.autoClear;
  62325. }
  62326. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62327. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62328. }
  62329. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62330. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62331. }
  62332. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62333. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62334. }
  62335. // Fog
  62336. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62337. scene.fogMode = parsedData.fogMode;
  62338. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62339. scene.fogStart = parsedData.fogStart;
  62340. scene.fogEnd = parsedData.fogEnd;
  62341. scene.fogDensity = parsedData.fogDensity;
  62342. log += "\tFog mode for scene: ";
  62343. switch (scene.fogMode) {
  62344. // getters not compiling, so using hardcoded
  62345. case 1:
  62346. log += "exp\n";
  62347. break;
  62348. case 2:
  62349. log += "exp2\n";
  62350. break;
  62351. case 3:
  62352. log += "linear\n";
  62353. break;
  62354. }
  62355. }
  62356. //Physics
  62357. if (parsedData.physicsEnabled) {
  62358. var physicsPlugin;
  62359. if (parsedData.physicsEngine === "cannon") {
  62360. physicsPlugin = new BABYLON.CannonJSPlugin();
  62361. }
  62362. else if (parsedData.physicsEngine === "oimo") {
  62363. physicsPlugin = new BABYLON.OimoJSPlugin();
  62364. }
  62365. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62366. //else - default engine, which is currently oimo
  62367. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62368. scene.enablePhysics(physicsGravity, physicsPlugin);
  62369. }
  62370. // Metadata
  62371. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62372. scene.metadata = parsedData.metadata;
  62373. }
  62374. //collisions, if defined. otherwise, default is true
  62375. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62376. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62377. }
  62378. scene.workerCollisions = !!parsedData.workerCollisions;
  62379. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62380. if (!container) {
  62381. return false;
  62382. }
  62383. if (parsedData.autoAnimate) {
  62384. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62385. }
  62386. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62387. scene.setActiveCameraByID(parsedData.activeCameraID);
  62388. }
  62389. // Environment texture
  62390. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62391. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62392. if (parsedData.createDefaultSkybox === true) {
  62393. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62394. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62395. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62396. }
  62397. }
  62398. // Finish
  62399. return true;
  62400. }
  62401. catch (err) {
  62402. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62403. if (onError) {
  62404. onError(msg, err);
  62405. }
  62406. else {
  62407. BABYLON.Tools.Log(msg);
  62408. throw err;
  62409. }
  62410. }
  62411. finally {
  62412. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62413. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62414. }
  62415. }
  62416. return false;
  62417. },
  62418. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62419. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62420. return container;
  62421. }
  62422. });
  62423. })(BABYLON || (BABYLON = {}));
  62424. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62425. var BABYLON;
  62426. (function (BABYLON) {
  62427. var FilesInput = /** @class */ (function () {
  62428. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62429. this.onProcessFileCallback = function () { return true; };
  62430. this._engine = engine;
  62431. this._currentScene = scene;
  62432. this._sceneLoadedCallback = sceneLoadedCallback;
  62433. this._progressCallback = progressCallback;
  62434. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62435. this._textureLoadingCallback = textureLoadingCallback;
  62436. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62437. this._onReloadCallback = onReloadCallback;
  62438. this._errorCallback = errorCallback;
  62439. }
  62440. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62441. var _this = this;
  62442. if (elementToMonitor) {
  62443. this._elementToMonitor = elementToMonitor;
  62444. this._dragEnterHandler = function (e) { _this.drag(e); };
  62445. this._dragOverHandler = function (e) { _this.drag(e); };
  62446. this._dropHandler = function (e) { _this.drop(e); };
  62447. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62448. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62449. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62450. }
  62451. };
  62452. FilesInput.prototype.dispose = function () {
  62453. if (!this._elementToMonitor) {
  62454. return;
  62455. }
  62456. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62457. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62458. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62459. };
  62460. FilesInput.prototype.renderFunction = function () {
  62461. if (this._additionalRenderLoopLogicCallback) {
  62462. this._additionalRenderLoopLogicCallback();
  62463. }
  62464. if (this._currentScene) {
  62465. if (this._textureLoadingCallback) {
  62466. var remaining = this._currentScene.getWaitingItemsCount();
  62467. if (remaining > 0) {
  62468. this._textureLoadingCallback(remaining);
  62469. }
  62470. }
  62471. this._currentScene.render();
  62472. }
  62473. };
  62474. FilesInput.prototype.drag = function (e) {
  62475. e.stopPropagation();
  62476. e.preventDefault();
  62477. };
  62478. FilesInput.prototype.drop = function (eventDrop) {
  62479. eventDrop.stopPropagation();
  62480. eventDrop.preventDefault();
  62481. this.loadFiles(eventDrop);
  62482. };
  62483. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62484. var _this = this;
  62485. var reader = folder.createReader();
  62486. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62487. reader.readEntries(function (entries) {
  62488. remaining.count += entries.length;
  62489. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62490. var entry = entries_1[_i];
  62491. if (entry.isFile) {
  62492. entry.file(function (file) {
  62493. file.correctName = relativePath + file.name;
  62494. files.push(file);
  62495. if (--remaining.count === 0) {
  62496. callback();
  62497. }
  62498. });
  62499. }
  62500. else if (entry.isDirectory) {
  62501. _this._traverseFolder(entry, files, remaining, callback);
  62502. }
  62503. }
  62504. if (--remaining.count) {
  62505. callback();
  62506. }
  62507. });
  62508. };
  62509. FilesInput.prototype._processFiles = function (files) {
  62510. for (var i = 0; i < files.length; i++) {
  62511. var name = files[i].correctName.toLowerCase();
  62512. var extension = name.split('.').pop();
  62513. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62514. continue;
  62515. }
  62516. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62517. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62518. this._sceneFileToLoad = files[i];
  62519. }
  62520. else {
  62521. FilesInput.FilesToLoad[name] = files[i];
  62522. }
  62523. }
  62524. };
  62525. FilesInput.prototype.loadFiles = function (event) {
  62526. var _this = this;
  62527. if (this._startingProcessingFilesCallback)
  62528. this._startingProcessingFilesCallback();
  62529. // Handling data transfer via drag'n'drop
  62530. if (event && event.dataTransfer && event.dataTransfer.files) {
  62531. this._filesToLoad = event.dataTransfer.files;
  62532. }
  62533. // Handling files from input files
  62534. if (event && event.target && event.target.files) {
  62535. this._filesToLoad = event.target.files;
  62536. }
  62537. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62538. var files_1 = new Array();
  62539. var folders = [];
  62540. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62541. for (var i = 0; i < this._filesToLoad.length; i++) {
  62542. var fileToLoad = this._filesToLoad[i];
  62543. var name_1 = fileToLoad.name.toLowerCase();
  62544. var entry = void 0;
  62545. fileToLoad.correctName = name_1;
  62546. if (items) {
  62547. var item = items[i];
  62548. if (item.getAsEntry) {
  62549. entry = item.getAsEntry();
  62550. }
  62551. else if (item.webkitGetAsEntry) {
  62552. entry = item.webkitGetAsEntry();
  62553. }
  62554. }
  62555. if (!entry) {
  62556. files_1.push(fileToLoad);
  62557. }
  62558. else {
  62559. if (entry.isDirectory) {
  62560. folders.push(entry);
  62561. }
  62562. else {
  62563. files_1.push(fileToLoad);
  62564. }
  62565. }
  62566. }
  62567. if (folders.length === 0) {
  62568. this._processFiles(files_1);
  62569. this._processReload();
  62570. }
  62571. else {
  62572. var remaining = { count: folders.length };
  62573. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62574. var folder = folders_1[_i];
  62575. this._traverseFolder(folder, files_1, remaining, function () {
  62576. _this._processFiles(files_1);
  62577. if (remaining.count === 0) {
  62578. _this._processReload();
  62579. }
  62580. });
  62581. }
  62582. }
  62583. }
  62584. };
  62585. FilesInput.prototype._processReload = function () {
  62586. if (this._onReloadCallback) {
  62587. this._onReloadCallback(this._sceneFileToLoad);
  62588. }
  62589. else {
  62590. this.reload();
  62591. }
  62592. };
  62593. FilesInput.prototype.reload = function () {
  62594. var _this = this;
  62595. // If a scene file has been provided
  62596. if (this._sceneFileToLoad) {
  62597. if (this._currentScene) {
  62598. if (BABYLON.Tools.errorsCount > 0) {
  62599. BABYLON.Tools.ClearLogCache();
  62600. }
  62601. this._engine.stopRenderLoop();
  62602. this._currentScene.dispose();
  62603. }
  62604. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62605. if (_this._progressCallback) {
  62606. _this._progressCallback(progress);
  62607. }
  62608. }).then(function (scene) {
  62609. _this._currentScene = scene;
  62610. if (_this._sceneLoadedCallback) {
  62611. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62612. }
  62613. // Wait for textures and shaders to be ready
  62614. _this._currentScene.executeWhenReady(function () {
  62615. _this._engine.runRenderLoop(function () {
  62616. _this.renderFunction();
  62617. });
  62618. });
  62619. }).catch(function (error) {
  62620. if (_this._errorCallback) {
  62621. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62622. }
  62623. });
  62624. }
  62625. else {
  62626. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62627. }
  62628. };
  62629. FilesInput.FilesToLoad = {};
  62630. return FilesInput;
  62631. }());
  62632. BABYLON.FilesInput = FilesInput;
  62633. })(BABYLON || (BABYLON = {}));
  62634. //# sourceMappingURL=babylon.filesInput.js.map
  62635. var BABYLON;
  62636. (function (BABYLON) {
  62637. /**
  62638. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62639. * The underlying implementation relies on an associative array to ensure the best performances.
  62640. * The value can be anything including 'null' but except 'undefined'
  62641. */
  62642. var StringDictionary = /** @class */ (function () {
  62643. function StringDictionary() {
  62644. this._count = 0;
  62645. this._data = {};
  62646. }
  62647. /**
  62648. * This will clear this dictionary and copy the content from the 'source' one.
  62649. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62650. * @param source the dictionary to take the content from and copy to this dictionary
  62651. */
  62652. StringDictionary.prototype.copyFrom = function (source) {
  62653. var _this = this;
  62654. this.clear();
  62655. source.forEach(function (t, v) { return _this.add(t, v); });
  62656. };
  62657. /**
  62658. * Get a value based from its key
  62659. * @param key the given key to get the matching value from
  62660. * @return the value if found, otherwise undefined is returned
  62661. */
  62662. StringDictionary.prototype.get = function (key) {
  62663. var val = this._data[key];
  62664. if (val !== undefined) {
  62665. return val;
  62666. }
  62667. return undefined;
  62668. };
  62669. /**
  62670. * Get a value from its key or add it if it doesn't exist.
  62671. * This method will ensure you that a given key/data will be present in the dictionary.
  62672. * @param key the given key to get the matching value from
  62673. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62674. * The factory will only be invoked if there's no data for the given key.
  62675. * @return the value corresponding to the key.
  62676. */
  62677. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62678. var val = this.get(key);
  62679. if (val !== undefined) {
  62680. return val;
  62681. }
  62682. val = factory(key);
  62683. if (val) {
  62684. this.add(key, val);
  62685. }
  62686. return val;
  62687. };
  62688. /**
  62689. * Get a value from its key if present in the dictionary otherwise add it
  62690. * @param key the key to get the value from
  62691. * @param val if there's no such key/value pair in the dictionary add it with this value
  62692. * @return the value corresponding to the key
  62693. */
  62694. StringDictionary.prototype.getOrAdd = function (key, val) {
  62695. var curVal = this.get(key);
  62696. if (curVal !== undefined) {
  62697. return curVal;
  62698. }
  62699. this.add(key, val);
  62700. return val;
  62701. };
  62702. /**
  62703. * Check if there's a given key in the dictionary
  62704. * @param key the key to check for
  62705. * @return true if the key is present, false otherwise
  62706. */
  62707. StringDictionary.prototype.contains = function (key) {
  62708. return this._data[key] !== undefined;
  62709. };
  62710. /**
  62711. * Add a new key and its corresponding value
  62712. * @param key the key to add
  62713. * @param value the value corresponding to the key
  62714. * @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
  62715. */
  62716. StringDictionary.prototype.add = function (key, value) {
  62717. if (this._data[key] !== undefined) {
  62718. return false;
  62719. }
  62720. this._data[key] = value;
  62721. ++this._count;
  62722. return true;
  62723. };
  62724. StringDictionary.prototype.set = function (key, value) {
  62725. if (this._data[key] === undefined) {
  62726. return false;
  62727. }
  62728. this._data[key] = value;
  62729. return true;
  62730. };
  62731. /**
  62732. * Get the element of the given key and remove it from the dictionary
  62733. * @param key
  62734. */
  62735. StringDictionary.prototype.getAndRemove = function (key) {
  62736. var val = this.get(key);
  62737. if (val !== undefined) {
  62738. delete this._data[key];
  62739. --this._count;
  62740. return val;
  62741. }
  62742. return null;
  62743. };
  62744. /**
  62745. * Remove a key/value from the dictionary.
  62746. * @param key the key to remove
  62747. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62748. */
  62749. StringDictionary.prototype.remove = function (key) {
  62750. if (this.contains(key)) {
  62751. delete this._data[key];
  62752. --this._count;
  62753. return true;
  62754. }
  62755. return false;
  62756. };
  62757. /**
  62758. * Clear the whole content of the dictionary
  62759. */
  62760. StringDictionary.prototype.clear = function () {
  62761. this._data = {};
  62762. this._count = 0;
  62763. };
  62764. Object.defineProperty(StringDictionary.prototype, "count", {
  62765. get: function () {
  62766. return this._count;
  62767. },
  62768. enumerable: true,
  62769. configurable: true
  62770. });
  62771. /**
  62772. * Execute a callback on each key/val of the dictionary.
  62773. * Note that you can remove any element in this dictionary in the callback implementation
  62774. * @param callback the callback to execute on a given key/value pair
  62775. */
  62776. StringDictionary.prototype.forEach = function (callback) {
  62777. for (var cur in this._data) {
  62778. var val = this._data[cur];
  62779. callback(cur, val);
  62780. }
  62781. };
  62782. /**
  62783. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62784. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62785. * Note that you can remove any element in this dictionary in the callback implementation
  62786. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62787. */
  62788. StringDictionary.prototype.first = function (callback) {
  62789. for (var cur in this._data) {
  62790. var val = this._data[cur];
  62791. var res = callback(cur, val);
  62792. if (res) {
  62793. return res;
  62794. }
  62795. }
  62796. return null;
  62797. };
  62798. return StringDictionary;
  62799. }());
  62800. BABYLON.StringDictionary = StringDictionary;
  62801. })(BABYLON || (BABYLON = {}));
  62802. //# sourceMappingURL=babylon.stringDictionary.js.map
  62803. var BABYLON;
  62804. (function (BABYLON) {
  62805. var Tags = /** @class */ (function () {
  62806. function Tags() {
  62807. }
  62808. Tags.EnableFor = function (obj) {
  62809. obj._tags = obj._tags || {};
  62810. obj.hasTags = function () {
  62811. return Tags.HasTags(obj);
  62812. };
  62813. obj.addTags = function (tagsString) {
  62814. return Tags.AddTagsTo(obj, tagsString);
  62815. };
  62816. obj.removeTags = function (tagsString) {
  62817. return Tags.RemoveTagsFrom(obj, tagsString);
  62818. };
  62819. obj.matchesTagsQuery = function (tagsQuery) {
  62820. return Tags.MatchesQuery(obj, tagsQuery);
  62821. };
  62822. };
  62823. Tags.DisableFor = function (obj) {
  62824. delete obj._tags;
  62825. delete obj.hasTags;
  62826. delete obj.addTags;
  62827. delete obj.removeTags;
  62828. delete obj.matchesTagsQuery;
  62829. };
  62830. Tags.HasTags = function (obj) {
  62831. if (!obj._tags) {
  62832. return false;
  62833. }
  62834. return !BABYLON.Tools.IsEmpty(obj._tags);
  62835. };
  62836. Tags.GetTags = function (obj, asString) {
  62837. if (asString === void 0) { asString = true; }
  62838. if (!obj._tags) {
  62839. return null;
  62840. }
  62841. if (asString) {
  62842. var tagsArray = [];
  62843. for (var tag in obj._tags) {
  62844. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62845. tagsArray.push(tag);
  62846. }
  62847. }
  62848. return tagsArray.join(" ");
  62849. }
  62850. else {
  62851. return obj._tags;
  62852. }
  62853. };
  62854. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62855. // a tag cannot start with '||', '&&', and '!'
  62856. // it cannot contain whitespaces
  62857. Tags.AddTagsTo = function (obj, tagsString) {
  62858. if (!tagsString) {
  62859. return;
  62860. }
  62861. if (typeof tagsString !== "string") {
  62862. return;
  62863. }
  62864. var tags = tagsString.split(" ");
  62865. tags.forEach(function (tag, index, array) {
  62866. Tags._AddTagTo(obj, tag);
  62867. });
  62868. };
  62869. Tags._AddTagTo = function (obj, tag) {
  62870. tag = tag.trim();
  62871. if (tag === "" || tag === "true" || tag === "false") {
  62872. return;
  62873. }
  62874. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62875. return;
  62876. }
  62877. Tags.EnableFor(obj);
  62878. obj._tags[tag] = true;
  62879. };
  62880. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62881. if (!Tags.HasTags(obj)) {
  62882. return;
  62883. }
  62884. var tags = tagsString.split(" ");
  62885. for (var t in tags) {
  62886. Tags._RemoveTagFrom(obj, tags[t]);
  62887. }
  62888. };
  62889. Tags._RemoveTagFrom = function (obj, tag) {
  62890. delete obj._tags[tag];
  62891. };
  62892. Tags.MatchesQuery = function (obj, tagsQuery) {
  62893. if (tagsQuery === undefined) {
  62894. return true;
  62895. }
  62896. if (tagsQuery === "") {
  62897. return Tags.HasTags(obj);
  62898. }
  62899. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62900. };
  62901. return Tags;
  62902. }());
  62903. BABYLON.Tags = Tags;
  62904. })(BABYLON || (BABYLON = {}));
  62905. //# sourceMappingURL=babylon.tags.js.map
  62906. var BABYLON;
  62907. (function (BABYLON) {
  62908. var AndOrNotEvaluator = /** @class */ (function () {
  62909. function AndOrNotEvaluator() {
  62910. }
  62911. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62912. if (!query.match(/\([^\(\)]*\)/g)) {
  62913. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62914. }
  62915. else {
  62916. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62917. // remove parenthesis
  62918. r = r.slice(1, r.length - 1);
  62919. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62920. });
  62921. }
  62922. if (query === "true") {
  62923. return true;
  62924. }
  62925. if (query === "false") {
  62926. return false;
  62927. }
  62928. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62929. };
  62930. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62931. evaluateCallback = evaluateCallback || (function (r) {
  62932. return r === "true" ? true : false;
  62933. });
  62934. var result;
  62935. var or = parenthesisContent.split("||");
  62936. for (var i in or) {
  62937. if (or.hasOwnProperty(i)) {
  62938. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62939. var and = ori.split("&&");
  62940. if (and.length > 1) {
  62941. for (var j = 0; j < and.length; ++j) {
  62942. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62943. if (andj !== "true" && andj !== "false") {
  62944. if (andj[0] === "!") {
  62945. result = !evaluateCallback(andj.substring(1));
  62946. }
  62947. else {
  62948. result = evaluateCallback(andj);
  62949. }
  62950. }
  62951. else {
  62952. result = andj === "true" ? true : false;
  62953. }
  62954. if (!result) {
  62955. ori = "false";
  62956. break;
  62957. }
  62958. }
  62959. }
  62960. if (result || ori === "true") {
  62961. result = true;
  62962. break;
  62963. }
  62964. // result equals false (or undefined)
  62965. if (ori !== "true" && ori !== "false") {
  62966. if (ori[0] === "!") {
  62967. result = !evaluateCallback(ori.substring(1));
  62968. }
  62969. else {
  62970. result = evaluateCallback(ori);
  62971. }
  62972. }
  62973. else {
  62974. result = ori === "true" ? true : false;
  62975. }
  62976. }
  62977. }
  62978. // the whole parenthesis scope is replaced by 'true' or 'false'
  62979. return result ? "true" : "false";
  62980. };
  62981. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62982. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62983. // remove whitespaces
  62984. r = r.replace(/[\s]/g, function () { return ""; });
  62985. return r.length % 2 ? "!" : "";
  62986. });
  62987. booleanString = booleanString.trim();
  62988. if (booleanString === "!true") {
  62989. booleanString = "false";
  62990. }
  62991. else if (booleanString === "!false") {
  62992. booleanString = "true";
  62993. }
  62994. return booleanString;
  62995. };
  62996. return AndOrNotEvaluator;
  62997. }());
  62998. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62999. })(BABYLON || (BABYLON = {}));
  63000. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63001. var BABYLON;
  63002. (function (BABYLON) {
  63003. var Database = /** @class */ (function () {
  63004. function Database(urlToScene, callbackManifestChecked) {
  63005. // Handling various flavors of prefixed version of IndexedDB
  63006. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63007. this.callbackManifestChecked = callbackManifestChecked;
  63008. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63009. this.db = null;
  63010. this._enableSceneOffline = false;
  63011. this._enableTexturesOffline = false;
  63012. this.manifestVersionFound = 0;
  63013. this.mustUpdateRessources = false;
  63014. this.hasReachedQuota = false;
  63015. if (!Database.IDBStorageEnabled) {
  63016. this.callbackManifestChecked(true);
  63017. }
  63018. else {
  63019. this.checkManifestFile();
  63020. }
  63021. }
  63022. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63023. get: function () {
  63024. return this._enableSceneOffline;
  63025. },
  63026. enumerable: true,
  63027. configurable: true
  63028. });
  63029. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63030. get: function () {
  63031. return this._enableTexturesOffline;
  63032. },
  63033. enumerable: true,
  63034. configurable: true
  63035. });
  63036. Database.prototype.checkManifestFile = function () {
  63037. var _this = this;
  63038. var noManifestFile = function () {
  63039. _this._enableSceneOffline = false;
  63040. _this._enableTexturesOffline = false;
  63041. _this.callbackManifestChecked(false);
  63042. };
  63043. var timeStampUsed = false;
  63044. var manifestURL = this.currentSceneUrl + ".manifest";
  63045. var xhr = new XMLHttpRequest();
  63046. if (navigator.onLine) {
  63047. // Adding a timestamp to by-pass browsers' cache
  63048. timeStampUsed = true;
  63049. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63050. }
  63051. xhr.open("GET", manifestURL, true);
  63052. xhr.addEventListener("load", function () {
  63053. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63054. try {
  63055. var manifestFile = JSON.parse(xhr.response);
  63056. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63057. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63058. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63059. _this.manifestVersionFound = manifestFile.version;
  63060. }
  63061. if (_this.callbackManifestChecked) {
  63062. _this.callbackManifestChecked(true);
  63063. }
  63064. }
  63065. catch (ex) {
  63066. noManifestFile();
  63067. }
  63068. }
  63069. else {
  63070. noManifestFile();
  63071. }
  63072. }, false);
  63073. xhr.addEventListener("error", function (event) {
  63074. if (timeStampUsed) {
  63075. timeStampUsed = false;
  63076. // Let's retry without the timeStamp
  63077. // It could fail when coupled with HTML5 Offline API
  63078. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  63079. xhr.open("GET", retryManifestURL, true);
  63080. xhr.send();
  63081. }
  63082. else {
  63083. noManifestFile();
  63084. }
  63085. }, false);
  63086. try {
  63087. xhr.send();
  63088. }
  63089. catch (ex) {
  63090. BABYLON.Tools.Error("Error on XHR send request.");
  63091. this.callbackManifestChecked(false);
  63092. }
  63093. };
  63094. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63095. var _this = this;
  63096. var handleError = function () {
  63097. _this.isSupported = false;
  63098. if (errorCallback)
  63099. errorCallback();
  63100. };
  63101. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  63102. // Your browser doesn't support IndexedDB
  63103. this.isSupported = false;
  63104. if (errorCallback)
  63105. errorCallback();
  63106. }
  63107. else {
  63108. // If the DB hasn't been opened or created yet
  63109. if (!this.db) {
  63110. this.hasReachedQuota = false;
  63111. this.isSupported = true;
  63112. var request = this.idbFactory.open("babylonjs", 1);
  63113. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  63114. request.onerror = function (event) {
  63115. handleError();
  63116. };
  63117. // executes when a version change transaction cannot complete due to other active transactions
  63118. request.onblocked = function (event) {
  63119. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  63120. handleError();
  63121. };
  63122. // DB has been opened successfully
  63123. request.onsuccess = function (event) {
  63124. _this.db = request.result;
  63125. successCallback();
  63126. };
  63127. // Initialization of the DB. Creating Scenes & Textures stores
  63128. request.onupgradeneeded = function (event) {
  63129. _this.db = (event.target).result;
  63130. if (_this.db) {
  63131. try {
  63132. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  63133. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  63134. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  63135. }
  63136. catch (ex) {
  63137. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  63138. handleError();
  63139. }
  63140. }
  63141. };
  63142. }
  63143. else {
  63144. if (successCallback)
  63145. successCallback();
  63146. }
  63147. }
  63148. };
  63149. Database.prototype.loadImageFromDB = function (url, image) {
  63150. var _this = this;
  63151. var completeURL = Database.ReturnFullUrlLocation(url);
  63152. var saveAndLoadImage = function () {
  63153. if (!_this.hasReachedQuota && _this.db !== null) {
  63154. // the texture is not yet in the DB, let's try to save it
  63155. _this._saveImageIntoDBAsync(completeURL, image);
  63156. }
  63157. else {
  63158. image.src = url;
  63159. }
  63160. };
  63161. if (!this.mustUpdateRessources) {
  63162. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  63163. }
  63164. else {
  63165. saveAndLoadImage();
  63166. }
  63167. };
  63168. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  63169. if (this.isSupported && this.db !== null) {
  63170. var texture;
  63171. var transaction = this.db.transaction(["textures"]);
  63172. transaction.onabort = function (event) {
  63173. image.src = url;
  63174. };
  63175. transaction.oncomplete = function (event) {
  63176. var blobTextureURL;
  63177. if (texture) {
  63178. var URL = window.URL || window.webkitURL;
  63179. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  63180. image.onerror = function () {
  63181. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  63182. image.src = url;
  63183. };
  63184. image.src = blobTextureURL;
  63185. }
  63186. else {
  63187. notInDBCallback();
  63188. }
  63189. };
  63190. var getRequest = transaction.objectStore("textures").get(url);
  63191. getRequest.onsuccess = function (event) {
  63192. texture = (event.target).result;
  63193. };
  63194. getRequest.onerror = function (event) {
  63195. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  63196. image.src = url;
  63197. };
  63198. }
  63199. else {
  63200. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63201. image.src = url;
  63202. }
  63203. };
  63204. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  63205. var _this = this;
  63206. if (this.isSupported) {
  63207. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  63208. var generateBlobUrl = function () {
  63209. var blobTextureURL;
  63210. if (blob) {
  63211. var URL = window.URL || window.webkitURL;
  63212. try {
  63213. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  63214. }
  63215. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  63216. catch (ex) {
  63217. blobTextureURL = URL.createObjectURL(blob);
  63218. }
  63219. }
  63220. if (blobTextureURL) {
  63221. image.src = blobTextureURL;
  63222. }
  63223. };
  63224. if (Database.IsUASupportingBlobStorage) {
  63225. var xhr = new XMLHttpRequest(), blob;
  63226. xhr.open("GET", url, true);
  63227. xhr.responseType = "blob";
  63228. xhr.addEventListener("load", function () {
  63229. if (xhr.status === 200 && _this.db) {
  63230. // Blob as response (XHR2)
  63231. blob = xhr.response;
  63232. var transaction = _this.db.transaction(["textures"], "readwrite");
  63233. // the transaction could abort because of a QuotaExceededError error
  63234. transaction.onabort = function (event) {
  63235. try {
  63236. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63237. var srcElement = (event.srcElement || event.target);
  63238. var error = srcElement.error;
  63239. if (error && error.name === "QuotaExceededError") {
  63240. _this.hasReachedQuota = true;
  63241. }
  63242. }
  63243. catch (ex) { }
  63244. generateBlobUrl();
  63245. };
  63246. transaction.oncomplete = function (event) {
  63247. generateBlobUrl();
  63248. };
  63249. var newTexture = { textureUrl: url, data: blob };
  63250. try {
  63251. // Put the blob into the dabase
  63252. var addRequest = transaction.objectStore("textures").put(newTexture);
  63253. addRequest.onsuccess = function (event) {
  63254. };
  63255. addRequest.onerror = function (event) {
  63256. generateBlobUrl();
  63257. };
  63258. }
  63259. catch (ex) {
  63260. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63261. if (ex.code === 25) {
  63262. Database.IsUASupportingBlobStorage = false;
  63263. }
  63264. image.src = url;
  63265. }
  63266. }
  63267. else {
  63268. image.src = url;
  63269. }
  63270. }, false);
  63271. xhr.addEventListener("error", function (event) {
  63272. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63273. image.src = url;
  63274. }, false);
  63275. xhr.send();
  63276. }
  63277. else {
  63278. image.src = url;
  63279. }
  63280. }
  63281. else {
  63282. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63283. image.src = url;
  63284. }
  63285. };
  63286. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63287. var _this = this;
  63288. var updateVersion = function () {
  63289. // the version is not yet in the DB or we need to update it
  63290. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63291. };
  63292. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63293. };
  63294. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63295. var _this = this;
  63296. if (this.isSupported && this.db) {
  63297. var version;
  63298. try {
  63299. var transaction = this.db.transaction(["versions"]);
  63300. transaction.oncomplete = function (event) {
  63301. if (version) {
  63302. // If the version in the JSON file is > than the version in DB
  63303. if (_this.manifestVersionFound > version.data) {
  63304. _this.mustUpdateRessources = true;
  63305. updateInDBCallback();
  63306. }
  63307. else {
  63308. callback(version.data);
  63309. }
  63310. }
  63311. else {
  63312. _this.mustUpdateRessources = true;
  63313. updateInDBCallback();
  63314. }
  63315. };
  63316. transaction.onabort = function (event) {
  63317. callback(-1);
  63318. };
  63319. var getRequest = transaction.objectStore("versions").get(url);
  63320. getRequest.onsuccess = function (event) {
  63321. version = (event.target).result;
  63322. };
  63323. getRequest.onerror = function (event) {
  63324. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63325. callback(-1);
  63326. };
  63327. }
  63328. catch (ex) {
  63329. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63330. callback(-1);
  63331. }
  63332. }
  63333. else {
  63334. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63335. callback(-1);
  63336. }
  63337. };
  63338. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63339. var _this = this;
  63340. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63341. try {
  63342. // Open a transaction to the database
  63343. var transaction = this.db.transaction(["versions"], "readwrite");
  63344. // the transaction could abort because of a QuotaExceededError error
  63345. transaction.onabort = function (event) {
  63346. try {
  63347. var error = event.srcElement['error'];
  63348. if (error && error.name === "QuotaExceededError") {
  63349. _this.hasReachedQuota = true;
  63350. }
  63351. }
  63352. catch (ex) { }
  63353. callback(-1);
  63354. };
  63355. transaction.oncomplete = function (event) {
  63356. callback(_this.manifestVersionFound);
  63357. };
  63358. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63359. // Put the scene into the database
  63360. var addRequest = transaction.objectStore("versions").put(newVersion);
  63361. addRequest.onsuccess = function (event) {
  63362. };
  63363. addRequest.onerror = function (event) {
  63364. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63365. };
  63366. }
  63367. catch (ex) {
  63368. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63369. callback(-1);
  63370. }
  63371. }
  63372. else {
  63373. callback(-1);
  63374. }
  63375. };
  63376. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63377. var _this = this;
  63378. var completeUrl = Database.ReturnFullUrlLocation(url);
  63379. var saveAndLoadFile = function () {
  63380. // the scene is not yet in the DB, let's try to save it
  63381. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63382. };
  63383. this._checkVersionFromDB(completeUrl, function (version) {
  63384. if (version !== -1) {
  63385. if (!_this.mustUpdateRessources) {
  63386. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63387. }
  63388. else {
  63389. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63390. }
  63391. }
  63392. else {
  63393. if (errorCallback) {
  63394. errorCallback();
  63395. }
  63396. }
  63397. });
  63398. };
  63399. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63400. if (this.isSupported && this.db) {
  63401. var targetStore;
  63402. if (url.indexOf(".babylon") !== -1) {
  63403. targetStore = "scenes";
  63404. }
  63405. else {
  63406. targetStore = "textures";
  63407. }
  63408. var file;
  63409. var transaction = this.db.transaction([targetStore]);
  63410. transaction.oncomplete = function (event) {
  63411. if (file) {
  63412. callback(file.data);
  63413. }
  63414. else {
  63415. notInDBCallback();
  63416. }
  63417. };
  63418. transaction.onabort = function (event) {
  63419. notInDBCallback();
  63420. };
  63421. var getRequest = transaction.objectStore(targetStore).get(url);
  63422. getRequest.onsuccess = function (event) {
  63423. file = (event.target).result;
  63424. };
  63425. getRequest.onerror = function (event) {
  63426. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63427. notInDBCallback();
  63428. };
  63429. }
  63430. else {
  63431. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63432. callback();
  63433. }
  63434. };
  63435. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63436. var _this = this;
  63437. if (this.isSupported) {
  63438. var targetStore;
  63439. if (url.indexOf(".babylon") !== -1) {
  63440. targetStore = "scenes";
  63441. }
  63442. else {
  63443. targetStore = "textures";
  63444. }
  63445. // Create XHR
  63446. var xhr = new XMLHttpRequest();
  63447. var fileData;
  63448. xhr.open("GET", url, true);
  63449. if (useArrayBuffer) {
  63450. xhr.responseType = "arraybuffer";
  63451. }
  63452. if (progressCallback) {
  63453. xhr.onprogress = progressCallback;
  63454. }
  63455. xhr.addEventListener("load", function () {
  63456. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63457. // Blob as response (XHR2)
  63458. //fileData = xhr.responseText;
  63459. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63460. if (!_this.hasReachedQuota && _this.db) {
  63461. // Open a transaction to the database
  63462. var transaction = _this.db.transaction([targetStore], "readwrite");
  63463. // the transaction could abort because of a QuotaExceededError error
  63464. transaction.onabort = function (event) {
  63465. try {
  63466. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63467. var error = event.srcElement['error'];
  63468. if (error && error.name === "QuotaExceededError") {
  63469. _this.hasReachedQuota = true;
  63470. }
  63471. }
  63472. catch (ex) { }
  63473. callback(fileData);
  63474. };
  63475. transaction.oncomplete = function (event) {
  63476. callback(fileData);
  63477. };
  63478. var newFile;
  63479. if (targetStore === "scenes") {
  63480. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63481. }
  63482. else {
  63483. newFile = { textureUrl: url, data: fileData };
  63484. }
  63485. try {
  63486. // Put the scene into the database
  63487. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63488. addRequest.onsuccess = function (event) {
  63489. };
  63490. addRequest.onerror = function (event) {
  63491. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63492. };
  63493. }
  63494. catch (ex) {
  63495. callback(fileData);
  63496. }
  63497. }
  63498. else {
  63499. callback(fileData);
  63500. }
  63501. }
  63502. else {
  63503. callback();
  63504. }
  63505. }, false);
  63506. xhr.addEventListener("error", function (event) {
  63507. BABYLON.Tools.Error("error on XHR request.");
  63508. callback();
  63509. }, false);
  63510. xhr.send();
  63511. }
  63512. else {
  63513. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63514. callback();
  63515. }
  63516. };
  63517. Database.IsUASupportingBlobStorage = true;
  63518. Database.IDBStorageEnabled = true;
  63519. Database.parseURL = function (url) {
  63520. var a = document.createElement('a');
  63521. a.href = url;
  63522. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63523. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63524. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63525. return absLocation;
  63526. };
  63527. Database.ReturnFullUrlLocation = function (url) {
  63528. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63529. return (Database.parseURL(window.location.href) + url);
  63530. }
  63531. else {
  63532. return url;
  63533. }
  63534. };
  63535. return Database;
  63536. }());
  63537. BABYLON.Database = Database;
  63538. })(BABYLON || (BABYLON = {}));
  63539. //# sourceMappingURL=babylon.database.js.map
  63540. var BABYLON;
  63541. (function (BABYLON) {
  63542. var FresnelParameters = /** @class */ (function () {
  63543. function FresnelParameters() {
  63544. this._isEnabled = true;
  63545. this.leftColor = BABYLON.Color3.White();
  63546. this.rightColor = BABYLON.Color3.Black();
  63547. this.bias = 0;
  63548. this.power = 1;
  63549. }
  63550. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63551. get: function () {
  63552. return this._isEnabled;
  63553. },
  63554. set: function (value) {
  63555. if (this._isEnabled === value) {
  63556. return;
  63557. }
  63558. this._isEnabled = value;
  63559. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63560. },
  63561. enumerable: true,
  63562. configurable: true
  63563. });
  63564. FresnelParameters.prototype.clone = function () {
  63565. var newFresnelParameters = new FresnelParameters();
  63566. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63567. return newFresnelParameters;
  63568. };
  63569. FresnelParameters.prototype.serialize = function () {
  63570. var serializationObject = {};
  63571. serializationObject.isEnabled = this.isEnabled;
  63572. serializationObject.leftColor = this.leftColor;
  63573. serializationObject.rightColor = this.rightColor;
  63574. serializationObject.bias = this.bias;
  63575. serializationObject.power = this.power;
  63576. return serializationObject;
  63577. };
  63578. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63579. var fresnelParameters = new FresnelParameters();
  63580. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63581. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63582. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63583. fresnelParameters.bias = parsedFresnelParameters.bias;
  63584. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63585. return fresnelParameters;
  63586. };
  63587. return FresnelParameters;
  63588. }());
  63589. BABYLON.FresnelParameters = FresnelParameters;
  63590. })(BABYLON || (BABYLON = {}));
  63591. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63592. var BABYLON;
  63593. (function (BABYLON) {
  63594. var MultiMaterial = /** @class */ (function (_super) {
  63595. __extends(MultiMaterial, _super);
  63596. function MultiMaterial(name, scene) {
  63597. var _this = _super.call(this, name, scene, true) || this;
  63598. scene.multiMaterials.push(_this);
  63599. _this.subMaterials = new Array();
  63600. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63601. return _this;
  63602. }
  63603. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63604. get: function () {
  63605. return this._subMaterials;
  63606. },
  63607. set: function (value) {
  63608. this._subMaterials = value;
  63609. this._hookArray(value);
  63610. },
  63611. enumerable: true,
  63612. configurable: true
  63613. });
  63614. MultiMaterial.prototype._hookArray = function (array) {
  63615. var _this = this;
  63616. var oldPush = array.push;
  63617. array.push = function () {
  63618. var items = [];
  63619. for (var _i = 0; _i < arguments.length; _i++) {
  63620. items[_i] = arguments[_i];
  63621. }
  63622. var result = oldPush.apply(array, items);
  63623. _this._markAllSubMeshesAsTexturesDirty();
  63624. return result;
  63625. };
  63626. var oldSplice = array.splice;
  63627. array.splice = function (index, deleteCount) {
  63628. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63629. _this._markAllSubMeshesAsTexturesDirty();
  63630. return deleted;
  63631. };
  63632. };
  63633. // Properties
  63634. MultiMaterial.prototype.getSubMaterial = function (index) {
  63635. if (index < 0 || index >= this.subMaterials.length) {
  63636. return this.getScene().defaultMaterial;
  63637. }
  63638. return this.subMaterials[index];
  63639. };
  63640. MultiMaterial.prototype.getActiveTextures = function () {
  63641. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63642. if (subMaterial) {
  63643. return subMaterial.getActiveTextures();
  63644. }
  63645. else {
  63646. return [];
  63647. }
  63648. }));
  63649. var _a;
  63650. };
  63651. // Methods
  63652. MultiMaterial.prototype.getClassName = function () {
  63653. return "MultiMaterial";
  63654. };
  63655. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63656. for (var index = 0; index < this.subMaterials.length; index++) {
  63657. var subMaterial = this.subMaterials[index];
  63658. if (subMaterial) {
  63659. if (subMaterial.storeEffectOnSubMeshes) {
  63660. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63661. return false;
  63662. }
  63663. continue;
  63664. }
  63665. if (!subMaterial.isReady(mesh)) {
  63666. return false;
  63667. }
  63668. }
  63669. }
  63670. return true;
  63671. };
  63672. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63673. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63674. for (var index = 0; index < this.subMaterials.length; index++) {
  63675. var subMaterial = null;
  63676. var current = this.subMaterials[index];
  63677. if (cloneChildren && current) {
  63678. subMaterial = current.clone(name + "-" + current.name);
  63679. }
  63680. else {
  63681. subMaterial = this.subMaterials[index];
  63682. }
  63683. newMultiMaterial.subMaterials.push(subMaterial);
  63684. }
  63685. return newMultiMaterial;
  63686. };
  63687. MultiMaterial.prototype.serialize = function () {
  63688. var serializationObject = {};
  63689. serializationObject.name = this.name;
  63690. serializationObject.id = this.id;
  63691. if (BABYLON.Tags) {
  63692. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63693. }
  63694. serializationObject.materials = [];
  63695. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63696. var subMat = this.subMaterials[matIndex];
  63697. if (subMat) {
  63698. serializationObject.materials.push(subMat.id);
  63699. }
  63700. else {
  63701. serializationObject.materials.push(null);
  63702. }
  63703. }
  63704. return serializationObject;
  63705. };
  63706. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63707. var scene = this.getScene();
  63708. if (!scene) {
  63709. return;
  63710. }
  63711. var index = scene.multiMaterials.indexOf(this);
  63712. if (index >= 0) {
  63713. scene.multiMaterials.splice(index, 1);
  63714. }
  63715. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63716. };
  63717. return MultiMaterial;
  63718. }(BABYLON.Material));
  63719. BABYLON.MultiMaterial = MultiMaterial;
  63720. })(BABYLON || (BABYLON = {}));
  63721. //# sourceMappingURL=babylon.multiMaterial.js.map
  63722. var BABYLON;
  63723. (function (BABYLON) {
  63724. var FreeCameraTouchInput = /** @class */ (function () {
  63725. function FreeCameraTouchInput() {
  63726. this._offsetX = null;
  63727. this._offsetY = null;
  63728. this._pointerPressed = new Array();
  63729. this.touchAngularSensibility = 200000.0;
  63730. this.touchMoveSensibility = 250.0;
  63731. }
  63732. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63733. var _this = this;
  63734. var previousPosition = null;
  63735. if (this._pointerInput === undefined) {
  63736. this._onLostFocus = function (evt) {
  63737. _this._offsetX = null;
  63738. _this._offsetY = null;
  63739. };
  63740. this._pointerInput = function (p, s) {
  63741. var evt = p.event;
  63742. if (evt.pointerType === "mouse") {
  63743. return;
  63744. }
  63745. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63746. if (!noPreventDefault) {
  63747. evt.preventDefault();
  63748. }
  63749. _this._pointerPressed.push(evt.pointerId);
  63750. if (_this._pointerPressed.length !== 1) {
  63751. return;
  63752. }
  63753. previousPosition = {
  63754. x: evt.clientX,
  63755. y: evt.clientY
  63756. };
  63757. }
  63758. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63759. if (!noPreventDefault) {
  63760. evt.preventDefault();
  63761. }
  63762. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63763. if (index === -1) {
  63764. return;
  63765. }
  63766. _this._pointerPressed.splice(index, 1);
  63767. if (index != 0) {
  63768. return;
  63769. }
  63770. previousPosition = null;
  63771. _this._offsetX = null;
  63772. _this._offsetY = null;
  63773. }
  63774. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63775. if (!noPreventDefault) {
  63776. evt.preventDefault();
  63777. }
  63778. if (!previousPosition) {
  63779. return;
  63780. }
  63781. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63782. if (index != 0) {
  63783. return;
  63784. }
  63785. _this._offsetX = evt.clientX - previousPosition.x;
  63786. _this._offsetY = -(evt.clientY - previousPosition.y);
  63787. }
  63788. };
  63789. }
  63790. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63791. if (this._onLostFocus) {
  63792. element.addEventListener("blur", this._onLostFocus);
  63793. }
  63794. };
  63795. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63796. if (this._pointerInput && element) {
  63797. if (this._observer) {
  63798. this.camera.getScene().onPointerObservable.remove(this._observer);
  63799. this._observer = null;
  63800. }
  63801. if (this._onLostFocus) {
  63802. element.removeEventListener("blur", this._onLostFocus);
  63803. this._onLostFocus = null;
  63804. }
  63805. this._pointerPressed = [];
  63806. this._offsetX = null;
  63807. this._offsetY = null;
  63808. }
  63809. };
  63810. FreeCameraTouchInput.prototype.checkInputs = function () {
  63811. if (this._offsetX && this._offsetY) {
  63812. var camera = this.camera;
  63813. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63814. if (this._pointerPressed.length > 1) {
  63815. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63816. }
  63817. else {
  63818. var speed = camera._computeLocalCameraSpeed();
  63819. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63820. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63821. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63822. }
  63823. }
  63824. };
  63825. FreeCameraTouchInput.prototype.getClassName = function () {
  63826. return "FreeCameraTouchInput";
  63827. };
  63828. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63829. return "touch";
  63830. };
  63831. __decorate([
  63832. BABYLON.serialize()
  63833. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63834. __decorate([
  63835. BABYLON.serialize()
  63836. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63837. return FreeCameraTouchInput;
  63838. }());
  63839. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63840. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63841. })(BABYLON || (BABYLON = {}));
  63842. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63843. var BABYLON;
  63844. (function (BABYLON) {
  63845. // We're mainly based on the logic defined into the FreeCamera code
  63846. var TouchCamera = /** @class */ (function (_super) {
  63847. __extends(TouchCamera, _super);
  63848. //-- end properties for backward compatibility for inputs
  63849. function TouchCamera(name, position, scene) {
  63850. var _this = _super.call(this, name, position, scene) || this;
  63851. _this.inputs.addTouch();
  63852. _this._setupInputs();
  63853. return _this;
  63854. }
  63855. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63856. //-- Begin properties for backward compatibility for inputs
  63857. get: function () {
  63858. var touch = this.inputs.attached["touch"];
  63859. if (touch)
  63860. return touch.touchAngularSensibility;
  63861. return 0;
  63862. },
  63863. set: function (value) {
  63864. var touch = this.inputs.attached["touch"];
  63865. if (touch)
  63866. touch.touchAngularSensibility = value;
  63867. },
  63868. enumerable: true,
  63869. configurable: true
  63870. });
  63871. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63872. get: function () {
  63873. var touch = this.inputs.attached["touch"];
  63874. if (touch)
  63875. return touch.touchMoveSensibility;
  63876. return 0;
  63877. },
  63878. set: function (value) {
  63879. var touch = this.inputs.attached["touch"];
  63880. if (touch)
  63881. touch.touchMoveSensibility = value;
  63882. },
  63883. enumerable: true,
  63884. configurable: true
  63885. });
  63886. TouchCamera.prototype.getClassName = function () {
  63887. return "TouchCamera";
  63888. };
  63889. TouchCamera.prototype._setupInputs = function () {
  63890. var mouse = this.inputs.attached["mouse"];
  63891. if (mouse) {
  63892. mouse.touchEnabled = false;
  63893. }
  63894. };
  63895. return TouchCamera;
  63896. }(BABYLON.FreeCamera));
  63897. BABYLON.TouchCamera = TouchCamera;
  63898. })(BABYLON || (BABYLON = {}));
  63899. //# sourceMappingURL=babylon.touchCamera.js.map
  63900. var BABYLON;
  63901. (function (BABYLON) {
  63902. var ProceduralTexture = /** @class */ (function (_super) {
  63903. __extends(ProceduralTexture, _super);
  63904. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63905. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63906. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63907. if (isCube === void 0) { isCube = false; }
  63908. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63909. _this.isCube = isCube;
  63910. _this.isEnabled = true;
  63911. _this._currentRefreshId = -1;
  63912. _this._refreshRate = 1;
  63913. _this._vertexBuffers = {};
  63914. _this._uniforms = new Array();
  63915. _this._samplers = new Array();
  63916. _this._textures = {};
  63917. _this._floats = {};
  63918. _this._floatsArrays = {};
  63919. _this._colors3 = {};
  63920. _this._colors4 = {};
  63921. _this._vectors2 = {};
  63922. _this._vectors3 = {};
  63923. _this._matrices = {};
  63924. _this._fallbackTextureUsed = false;
  63925. scene._proceduralTextures.push(_this);
  63926. _this._engine = scene.getEngine();
  63927. _this.name = name;
  63928. _this.isRenderTarget = true;
  63929. _this._size = size;
  63930. _this._generateMipMaps = generateMipMaps;
  63931. _this.setFragment(fragment);
  63932. _this._fallbackTexture = fallbackTexture;
  63933. if (isCube) {
  63934. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63935. _this.setFloat("face", 0);
  63936. }
  63937. else {
  63938. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63939. }
  63940. // VBO
  63941. var vertices = [];
  63942. vertices.push(1, 1);
  63943. vertices.push(-1, 1);
  63944. vertices.push(-1, -1);
  63945. vertices.push(1, -1);
  63946. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63947. _this._createIndexBuffer();
  63948. return _this;
  63949. }
  63950. ProceduralTexture.prototype._createIndexBuffer = function () {
  63951. var engine = this._engine;
  63952. // Indices
  63953. var indices = [];
  63954. indices.push(0);
  63955. indices.push(1);
  63956. indices.push(2);
  63957. indices.push(0);
  63958. indices.push(2);
  63959. indices.push(3);
  63960. this._indexBuffer = engine.createIndexBuffer(indices);
  63961. };
  63962. ProceduralTexture.prototype._rebuild = function () {
  63963. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63964. if (vb) {
  63965. vb._rebuild();
  63966. }
  63967. this._createIndexBuffer();
  63968. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63969. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63970. }
  63971. };
  63972. ProceduralTexture.prototype.reset = function () {
  63973. if (this._effect === undefined) {
  63974. return;
  63975. }
  63976. var engine = this._engine;
  63977. engine._releaseEffect(this._effect);
  63978. };
  63979. ProceduralTexture.prototype.isReady = function () {
  63980. var _this = this;
  63981. var engine = this._engine;
  63982. var shaders;
  63983. if (!this._fragment) {
  63984. return false;
  63985. }
  63986. if (this._fallbackTextureUsed) {
  63987. return true;
  63988. }
  63989. if (this._fragment.fragmentElement !== undefined) {
  63990. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63991. }
  63992. else {
  63993. shaders = { vertex: "procedural", fragment: this._fragment };
  63994. }
  63995. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63996. _this.releaseInternalTexture();
  63997. if (_this._fallbackTexture) {
  63998. _this._texture = _this._fallbackTexture._texture;
  63999. if (_this._texture) {
  64000. _this._texture.incrementReferences();
  64001. }
  64002. }
  64003. _this._fallbackTextureUsed = true;
  64004. });
  64005. return this._effect.isReady();
  64006. };
  64007. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64008. this._currentRefreshId = -1;
  64009. };
  64010. ProceduralTexture.prototype.setFragment = function (fragment) {
  64011. this._fragment = fragment;
  64012. };
  64013. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64014. get: function () {
  64015. return this._refreshRate;
  64016. },
  64017. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64018. set: function (value) {
  64019. this._refreshRate = value;
  64020. this.resetRefreshCounter();
  64021. },
  64022. enumerable: true,
  64023. configurable: true
  64024. });
  64025. ProceduralTexture.prototype._shouldRender = function () {
  64026. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64027. return false;
  64028. }
  64029. if (this._fallbackTextureUsed) {
  64030. return false;
  64031. }
  64032. if (this._currentRefreshId === -1) {
  64033. this._currentRefreshId = 1;
  64034. return true;
  64035. }
  64036. if (this.refreshRate === this._currentRefreshId) {
  64037. this._currentRefreshId = 1;
  64038. return true;
  64039. }
  64040. this._currentRefreshId++;
  64041. return false;
  64042. };
  64043. ProceduralTexture.prototype.getRenderSize = function () {
  64044. return this._size;
  64045. };
  64046. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64047. if (this._fallbackTextureUsed) {
  64048. return;
  64049. }
  64050. this.releaseInternalTexture();
  64051. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64052. };
  64053. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64054. if (this._uniforms.indexOf(uniformName) === -1) {
  64055. this._uniforms.push(uniformName);
  64056. }
  64057. };
  64058. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64059. if (this._samplers.indexOf(name) === -1) {
  64060. this._samplers.push(name);
  64061. }
  64062. this._textures[name] = texture;
  64063. return this;
  64064. };
  64065. ProceduralTexture.prototype.setFloat = function (name, value) {
  64066. this._checkUniform(name);
  64067. this._floats[name] = value;
  64068. return this;
  64069. };
  64070. ProceduralTexture.prototype.setFloats = function (name, value) {
  64071. this._checkUniform(name);
  64072. this._floatsArrays[name] = value;
  64073. return this;
  64074. };
  64075. ProceduralTexture.prototype.setColor3 = function (name, value) {
  64076. this._checkUniform(name);
  64077. this._colors3[name] = value;
  64078. return this;
  64079. };
  64080. ProceduralTexture.prototype.setColor4 = function (name, value) {
  64081. this._checkUniform(name);
  64082. this._colors4[name] = value;
  64083. return this;
  64084. };
  64085. ProceduralTexture.prototype.setVector2 = function (name, value) {
  64086. this._checkUniform(name);
  64087. this._vectors2[name] = value;
  64088. return this;
  64089. };
  64090. ProceduralTexture.prototype.setVector3 = function (name, value) {
  64091. this._checkUniform(name);
  64092. this._vectors3[name] = value;
  64093. return this;
  64094. };
  64095. ProceduralTexture.prototype.setMatrix = function (name, value) {
  64096. this._checkUniform(name);
  64097. this._matrices[name] = value;
  64098. return this;
  64099. };
  64100. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64101. var scene = this.getScene();
  64102. if (!scene) {
  64103. return;
  64104. }
  64105. var engine = this._engine;
  64106. // Render
  64107. engine.enableEffect(this._effect);
  64108. engine.setState(false);
  64109. // Texture
  64110. for (var name in this._textures) {
  64111. this._effect.setTexture(name, this._textures[name]);
  64112. }
  64113. // Float
  64114. for (name in this._floats) {
  64115. this._effect.setFloat(name, this._floats[name]);
  64116. }
  64117. // Floats
  64118. for (name in this._floatsArrays) {
  64119. this._effect.setArray(name, this._floatsArrays[name]);
  64120. }
  64121. // Color3
  64122. for (name in this._colors3) {
  64123. this._effect.setColor3(name, this._colors3[name]);
  64124. }
  64125. // Color4
  64126. for (name in this._colors4) {
  64127. var color = this._colors4[name];
  64128. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64129. }
  64130. // Vector2
  64131. for (name in this._vectors2) {
  64132. this._effect.setVector2(name, this._vectors2[name]);
  64133. }
  64134. // Vector3
  64135. for (name in this._vectors3) {
  64136. this._effect.setVector3(name, this._vectors3[name]);
  64137. }
  64138. // Matrix
  64139. for (name in this._matrices) {
  64140. this._effect.setMatrix(name, this._matrices[name]);
  64141. }
  64142. if (!this._texture) {
  64143. return;
  64144. }
  64145. if (this.isCube) {
  64146. for (var face = 0; face < 6; face++) {
  64147. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  64148. // VBOs
  64149. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64150. this._effect.setFloat("face", face);
  64151. // Clear
  64152. engine.clear(scene.clearColor, true, true, true);
  64153. // Draw order
  64154. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64155. // Mipmaps
  64156. if (face === 5) {
  64157. engine.generateMipMapsForCubemap(this._texture);
  64158. }
  64159. }
  64160. }
  64161. else {
  64162. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  64163. // VBOs
  64164. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64165. // Clear
  64166. engine.clear(scene.clearColor, true, true, true);
  64167. // Draw order
  64168. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64169. }
  64170. // Unbind
  64171. engine.unBindFramebuffer(this._texture, this.isCube);
  64172. if (this.onGenerated) {
  64173. this.onGenerated();
  64174. }
  64175. };
  64176. ProceduralTexture.prototype.clone = function () {
  64177. var textureSize = this.getSize();
  64178. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  64179. // Base texture
  64180. newTexture.hasAlpha = this.hasAlpha;
  64181. newTexture.level = this.level;
  64182. // RenderTarget Texture
  64183. newTexture.coordinatesMode = this.coordinatesMode;
  64184. return newTexture;
  64185. };
  64186. ProceduralTexture.prototype.dispose = function () {
  64187. var scene = this.getScene();
  64188. if (!scene) {
  64189. return;
  64190. }
  64191. var index = scene._proceduralTextures.indexOf(this);
  64192. if (index >= 0) {
  64193. scene._proceduralTextures.splice(index, 1);
  64194. }
  64195. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64196. if (vertexBuffer) {
  64197. vertexBuffer.dispose();
  64198. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64199. }
  64200. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  64201. this._indexBuffer = null;
  64202. }
  64203. _super.prototype.dispose.call(this);
  64204. };
  64205. return ProceduralTexture;
  64206. }(BABYLON.Texture));
  64207. BABYLON.ProceduralTexture = ProceduralTexture;
  64208. })(BABYLON || (BABYLON = {}));
  64209. //# sourceMappingURL=babylon.proceduralTexture.js.map
  64210. var BABYLON;
  64211. (function (BABYLON) {
  64212. var CustomProceduralTexture = /** @class */ (function (_super) {
  64213. __extends(CustomProceduralTexture, _super);
  64214. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  64215. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  64216. _this._animate = true;
  64217. _this._time = 0;
  64218. _this._texturePath = texturePath;
  64219. //Try to load json
  64220. _this.loadJson(texturePath);
  64221. _this.refreshRate = 1;
  64222. return _this;
  64223. }
  64224. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  64225. var _this = this;
  64226. var noConfigFile = function () {
  64227. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  64228. try {
  64229. _this.setFragment(_this._texturePath);
  64230. }
  64231. catch (ex) {
  64232. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  64233. }
  64234. };
  64235. var configFileUrl = jsonUrl + "/config.json";
  64236. var xhr = new XMLHttpRequest();
  64237. xhr.open("GET", configFileUrl, true);
  64238. xhr.addEventListener("load", function () {
  64239. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64240. try {
  64241. _this._config = JSON.parse(xhr.response);
  64242. _this.updateShaderUniforms();
  64243. _this.updateTextures();
  64244. _this.setFragment(_this._texturePath + "/custom");
  64245. _this._animate = _this._config.animate;
  64246. _this.refreshRate = _this._config.refreshrate;
  64247. }
  64248. catch (ex) {
  64249. noConfigFile();
  64250. }
  64251. }
  64252. else {
  64253. noConfigFile();
  64254. }
  64255. }, false);
  64256. xhr.addEventListener("error", function () {
  64257. noConfigFile();
  64258. }, false);
  64259. try {
  64260. xhr.send();
  64261. }
  64262. catch (ex) {
  64263. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64264. }
  64265. };
  64266. CustomProceduralTexture.prototype.isReady = function () {
  64267. if (!_super.prototype.isReady.call(this)) {
  64268. return false;
  64269. }
  64270. for (var name in this._textures) {
  64271. var texture = this._textures[name];
  64272. if (!texture.isReady()) {
  64273. return false;
  64274. }
  64275. }
  64276. return true;
  64277. };
  64278. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64279. var scene = this.getScene();
  64280. if (this._animate && scene) {
  64281. this._time += scene.getAnimationRatio() * 0.03;
  64282. this.updateShaderUniforms();
  64283. }
  64284. _super.prototype.render.call(this, useCameraPostProcess);
  64285. };
  64286. CustomProceduralTexture.prototype.updateTextures = function () {
  64287. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64288. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64289. }
  64290. };
  64291. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64292. if (this._config) {
  64293. for (var j = 0; j < this._config.uniforms.length; j++) {
  64294. var uniform = this._config.uniforms[j];
  64295. switch (uniform.type) {
  64296. case "float":
  64297. this.setFloat(uniform.name, uniform.value);
  64298. break;
  64299. case "color3":
  64300. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64301. break;
  64302. case "color4":
  64303. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64304. break;
  64305. case "vector2":
  64306. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64307. break;
  64308. case "vector3":
  64309. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64310. break;
  64311. }
  64312. }
  64313. }
  64314. this.setFloat("time", this._time);
  64315. };
  64316. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64317. get: function () {
  64318. return this._animate;
  64319. },
  64320. set: function (value) {
  64321. this._animate = value;
  64322. },
  64323. enumerable: true,
  64324. configurable: true
  64325. });
  64326. return CustomProceduralTexture;
  64327. }(BABYLON.ProceduralTexture));
  64328. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64329. })(BABYLON || (BABYLON = {}));
  64330. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64331. var BABYLON;
  64332. (function (BABYLON) {
  64333. var FreeCameraGamepadInput = /** @class */ (function () {
  64334. function FreeCameraGamepadInput() {
  64335. this.gamepadAngularSensibility = 200;
  64336. this.gamepadMoveSensibility = 40;
  64337. // private members
  64338. this._cameraTransform = BABYLON.Matrix.Identity();
  64339. this._deltaTransform = BABYLON.Vector3.Zero();
  64340. this._vector3 = BABYLON.Vector3.Zero();
  64341. this._vector2 = BABYLON.Vector2.Zero();
  64342. }
  64343. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64344. var _this = this;
  64345. var manager = this.camera.getScene().gamepadManager;
  64346. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64347. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64348. // prioritize XBOX gamepads.
  64349. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64350. _this.gamepad = gamepad;
  64351. }
  64352. }
  64353. });
  64354. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64355. if (_this.gamepad === gamepad) {
  64356. _this.gamepad = null;
  64357. }
  64358. });
  64359. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64360. };
  64361. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64362. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64363. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64364. this.gamepad = null;
  64365. };
  64366. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64367. if (this.gamepad && this.gamepad.leftStick) {
  64368. var camera = this.camera;
  64369. var LSValues = this.gamepad.leftStick;
  64370. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64371. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64372. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64373. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64374. var RSValues = this.gamepad.rightStick;
  64375. if (RSValues) {
  64376. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64377. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64378. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64379. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64380. }
  64381. else {
  64382. RSValues = { x: 0, y: 0 };
  64383. }
  64384. if (!camera.rotationQuaternion) {
  64385. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64386. }
  64387. else {
  64388. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64389. }
  64390. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64391. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64392. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64393. camera.cameraDirection.addInPlace(this._deltaTransform);
  64394. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64395. camera.cameraRotation.addInPlace(this._vector2);
  64396. }
  64397. };
  64398. FreeCameraGamepadInput.prototype.getClassName = function () {
  64399. return "FreeCameraGamepadInput";
  64400. };
  64401. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64402. return "gamepad";
  64403. };
  64404. __decorate([
  64405. BABYLON.serialize()
  64406. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64407. __decorate([
  64408. BABYLON.serialize()
  64409. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64410. return FreeCameraGamepadInput;
  64411. }());
  64412. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64413. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64414. })(BABYLON || (BABYLON = {}));
  64415. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64416. var BABYLON;
  64417. (function (BABYLON) {
  64418. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64419. function ArcRotateCameraGamepadInput() {
  64420. this.gamepadRotationSensibility = 80;
  64421. this.gamepadMoveSensibility = 40;
  64422. }
  64423. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64424. var _this = this;
  64425. var manager = this.camera.getScene().gamepadManager;
  64426. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64427. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64428. // prioritize XBOX gamepads.
  64429. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64430. _this.gamepad = gamepad;
  64431. }
  64432. }
  64433. });
  64434. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64435. if (_this.gamepad === gamepad) {
  64436. _this.gamepad = null;
  64437. }
  64438. });
  64439. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64440. };
  64441. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64442. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64443. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64444. this.gamepad = null;
  64445. };
  64446. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64447. if (this.gamepad) {
  64448. var camera = this.camera;
  64449. var RSValues = this.gamepad.rightStick;
  64450. if (RSValues) {
  64451. if (RSValues.x != 0) {
  64452. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64453. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64454. camera.inertialAlphaOffset += normalizedRX;
  64455. }
  64456. }
  64457. if (RSValues.y != 0) {
  64458. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64459. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64460. camera.inertialBetaOffset += normalizedRY;
  64461. }
  64462. }
  64463. }
  64464. var LSValues = this.gamepad.leftStick;
  64465. if (LSValues && LSValues.y != 0) {
  64466. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64467. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64468. this.camera.inertialRadiusOffset -= normalizedLY;
  64469. }
  64470. }
  64471. }
  64472. };
  64473. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64474. return "ArcRotateCameraGamepadInput";
  64475. };
  64476. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64477. return "gamepad";
  64478. };
  64479. __decorate([
  64480. BABYLON.serialize()
  64481. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64482. __decorate([
  64483. BABYLON.serialize()
  64484. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64485. return ArcRotateCameraGamepadInput;
  64486. }());
  64487. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64488. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64489. })(BABYLON || (BABYLON = {}));
  64490. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64491. var BABYLON;
  64492. (function (BABYLON) {
  64493. var GamepadManager = /** @class */ (function () {
  64494. function GamepadManager(_scene) {
  64495. var _this = this;
  64496. this._scene = _scene;
  64497. this._babylonGamepads = [];
  64498. this._oneGamepadConnected = false;
  64499. this._isMonitoring = false;
  64500. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64501. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64502. this._gamepadEventSupported = false;
  64503. }
  64504. else {
  64505. this._gamepadEventSupported = 'GamepadEvent' in window;
  64506. this._gamepadSupport = (navigator.getGamepads ||
  64507. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64508. }
  64509. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64510. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64511. for (var i in _this._babylonGamepads) {
  64512. var gamepad = _this._babylonGamepads[i];
  64513. if (gamepad && gamepad._isConnected) {
  64514. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64515. }
  64516. }
  64517. });
  64518. this._onGamepadConnectedEvent = function (evt) {
  64519. var gamepad = evt.gamepad;
  64520. if (gamepad.index in _this._babylonGamepads) {
  64521. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64522. return;
  64523. }
  64524. }
  64525. var newGamepad;
  64526. if (_this._babylonGamepads[gamepad.index]) {
  64527. newGamepad = _this._babylonGamepads[gamepad.index];
  64528. newGamepad.browserGamepad = gamepad;
  64529. newGamepad._isConnected = true;
  64530. }
  64531. else {
  64532. newGamepad = _this._addNewGamepad(gamepad);
  64533. }
  64534. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64535. _this._startMonitoringGamepads();
  64536. };
  64537. this._onGamepadDisconnectedEvent = function (evt) {
  64538. var gamepad = evt.gamepad;
  64539. // Remove the gamepad from the list of gamepads to monitor.
  64540. for (var i in _this._babylonGamepads) {
  64541. if (_this._babylonGamepads[i].index === gamepad.index) {
  64542. var disconnectedGamepad = _this._babylonGamepads[i];
  64543. disconnectedGamepad._isConnected = false;
  64544. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64545. break;
  64546. }
  64547. }
  64548. };
  64549. if (this._gamepadSupport) {
  64550. //first add already-connected gamepads
  64551. this._updateGamepadObjects();
  64552. if (this._babylonGamepads.length) {
  64553. this._startMonitoringGamepads();
  64554. }
  64555. // Checking if the gamepad connected event is supported (like in Firefox)
  64556. if (this._gamepadEventSupported) {
  64557. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64558. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64559. }
  64560. else {
  64561. this._startMonitoringGamepads();
  64562. }
  64563. }
  64564. }
  64565. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64566. get: function () {
  64567. return this._babylonGamepads;
  64568. },
  64569. enumerable: true,
  64570. configurable: true
  64571. });
  64572. GamepadManager.prototype.getGamepadByType = function (type) {
  64573. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64574. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64575. var gamepad = _a[_i];
  64576. if (gamepad && gamepad.type === type) {
  64577. return gamepad;
  64578. }
  64579. }
  64580. return null;
  64581. };
  64582. GamepadManager.prototype.dispose = function () {
  64583. if (this._gamepadEventSupported) {
  64584. if (this._onGamepadConnectedEvent) {
  64585. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64586. }
  64587. if (this._onGamepadDisconnectedEvent) {
  64588. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64589. }
  64590. this._onGamepadConnectedEvent = null;
  64591. this._onGamepadDisconnectedEvent = null;
  64592. }
  64593. this._babylonGamepads.forEach(function (gamepad) {
  64594. gamepad.dispose();
  64595. });
  64596. this.onGamepadConnectedObservable.clear();
  64597. this.onGamepadDisconnectedObservable.clear();
  64598. this._oneGamepadConnected = false;
  64599. this._stopMonitoringGamepads();
  64600. this._babylonGamepads = [];
  64601. };
  64602. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64603. if (!this._oneGamepadConnected) {
  64604. this._oneGamepadConnected = true;
  64605. }
  64606. var newGamepad;
  64607. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64608. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64609. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64610. }
  64611. else if (gamepad.pose) {
  64612. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64613. }
  64614. else {
  64615. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64616. }
  64617. this._babylonGamepads[newGamepad.index] = newGamepad;
  64618. return newGamepad;
  64619. };
  64620. GamepadManager.prototype._startMonitoringGamepads = function () {
  64621. if (!this._isMonitoring) {
  64622. this._isMonitoring = true;
  64623. //back-comp
  64624. if (!this._scene) {
  64625. this._checkGamepadsStatus();
  64626. }
  64627. }
  64628. };
  64629. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64630. this._isMonitoring = false;
  64631. };
  64632. GamepadManager.prototype._checkGamepadsStatus = function () {
  64633. var _this = this;
  64634. // Hack to be compatible Chrome
  64635. this._updateGamepadObjects();
  64636. for (var i in this._babylonGamepads) {
  64637. var gamepad = this._babylonGamepads[i];
  64638. if (!gamepad || !gamepad.isConnected) {
  64639. continue;
  64640. }
  64641. gamepad.update();
  64642. }
  64643. if (this._isMonitoring && !this._scene) {
  64644. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64645. }
  64646. };
  64647. // This function is called only on Chrome, which does not properly support
  64648. // connection/disconnection events and forces you to recopy again the gamepad object
  64649. GamepadManager.prototype._updateGamepadObjects = function () {
  64650. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64651. for (var i = 0; i < gamepads.length; i++) {
  64652. if (gamepads[i]) {
  64653. if (!this._babylonGamepads[gamepads[i].index]) {
  64654. var newGamepad = this._addNewGamepad(gamepads[i]);
  64655. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64656. }
  64657. else {
  64658. // Forced to copy again this object for Chrome for unknown reason
  64659. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64660. if (!this._babylonGamepads[i].isConnected) {
  64661. this._babylonGamepads[i]._isConnected = true;
  64662. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64663. }
  64664. }
  64665. }
  64666. }
  64667. };
  64668. return GamepadManager;
  64669. }());
  64670. BABYLON.GamepadManager = GamepadManager;
  64671. })(BABYLON || (BABYLON = {}));
  64672. //# sourceMappingURL=babylon.gamepadManager.js.map
  64673. var BABYLON;
  64674. (function (BABYLON) {
  64675. var StickValues = /** @class */ (function () {
  64676. function StickValues(x, y) {
  64677. this.x = x;
  64678. this.y = y;
  64679. }
  64680. return StickValues;
  64681. }());
  64682. BABYLON.StickValues = StickValues;
  64683. var Gamepad = /** @class */ (function () {
  64684. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64685. if (leftStickX === void 0) { leftStickX = 0; }
  64686. if (leftStickY === void 0) { leftStickY = 1; }
  64687. if (rightStickX === void 0) { rightStickX = 2; }
  64688. if (rightStickY === void 0) { rightStickY = 3; }
  64689. this.id = id;
  64690. this.index = index;
  64691. this.browserGamepad = browserGamepad;
  64692. this._isConnected = true;
  64693. this._invertLeftStickY = false;
  64694. this.type = Gamepad.GAMEPAD;
  64695. this._leftStickAxisX = leftStickX;
  64696. this._leftStickAxisY = leftStickY;
  64697. this._rightStickAxisX = rightStickX;
  64698. this._rightStickAxisY = rightStickY;
  64699. if (this.browserGamepad.axes.length >= 2) {
  64700. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64701. }
  64702. if (this.browserGamepad.axes.length >= 4) {
  64703. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64704. }
  64705. }
  64706. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64707. get: function () {
  64708. return this._isConnected;
  64709. },
  64710. enumerable: true,
  64711. configurable: true
  64712. });
  64713. Gamepad.prototype.onleftstickchanged = function (callback) {
  64714. this._onleftstickchanged = callback;
  64715. };
  64716. Gamepad.prototype.onrightstickchanged = function (callback) {
  64717. this._onrightstickchanged = callback;
  64718. };
  64719. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64720. get: function () {
  64721. return this._leftStick;
  64722. },
  64723. set: function (newValues) {
  64724. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64725. this._onleftstickchanged(newValues);
  64726. }
  64727. this._leftStick = newValues;
  64728. },
  64729. enumerable: true,
  64730. configurable: true
  64731. });
  64732. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64733. get: function () {
  64734. return this._rightStick;
  64735. },
  64736. set: function (newValues) {
  64737. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64738. this._onrightstickchanged(newValues);
  64739. }
  64740. this._rightStick = newValues;
  64741. },
  64742. enumerable: true,
  64743. configurable: true
  64744. });
  64745. Gamepad.prototype.update = function () {
  64746. if (this._leftStick) {
  64747. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64748. if (this._invertLeftStickY) {
  64749. this.leftStick.y *= -1;
  64750. }
  64751. }
  64752. if (this._rightStick) {
  64753. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64754. }
  64755. };
  64756. Gamepad.prototype.dispose = function () {
  64757. };
  64758. Gamepad.GAMEPAD = 0;
  64759. Gamepad.GENERIC = 1;
  64760. Gamepad.XBOX = 2;
  64761. Gamepad.POSE_ENABLED = 3;
  64762. return Gamepad;
  64763. }());
  64764. BABYLON.Gamepad = Gamepad;
  64765. var GenericPad = /** @class */ (function (_super) {
  64766. __extends(GenericPad, _super);
  64767. function GenericPad(id, index, browserGamepad) {
  64768. var _this = _super.call(this, id, index, browserGamepad) || this;
  64769. _this.onButtonDownObservable = new BABYLON.Observable();
  64770. _this.onButtonUpObservable = new BABYLON.Observable();
  64771. _this.type = Gamepad.GENERIC;
  64772. _this._buttons = new Array(browserGamepad.buttons.length);
  64773. return _this;
  64774. }
  64775. GenericPad.prototype.onbuttondown = function (callback) {
  64776. this._onbuttondown = callback;
  64777. };
  64778. GenericPad.prototype.onbuttonup = function (callback) {
  64779. this._onbuttonup = callback;
  64780. };
  64781. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64782. if (newValue !== currentValue) {
  64783. if (newValue === 1) {
  64784. if (this._onbuttondown) {
  64785. this._onbuttondown(buttonIndex);
  64786. }
  64787. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64788. }
  64789. if (newValue === 0) {
  64790. if (this._onbuttonup) {
  64791. this._onbuttonup(buttonIndex);
  64792. }
  64793. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64794. }
  64795. }
  64796. return newValue;
  64797. };
  64798. GenericPad.prototype.update = function () {
  64799. _super.prototype.update.call(this);
  64800. for (var index = 0; index < this._buttons.length; index++) {
  64801. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64802. }
  64803. };
  64804. GenericPad.prototype.dispose = function () {
  64805. _super.prototype.dispose.call(this);
  64806. this.onButtonDownObservable.clear();
  64807. this.onButtonUpObservable.clear();
  64808. };
  64809. return GenericPad;
  64810. }(Gamepad));
  64811. BABYLON.GenericPad = GenericPad;
  64812. })(BABYLON || (BABYLON = {}));
  64813. //# sourceMappingURL=babylon.gamepad.js.map
  64814. var BABYLON;
  64815. (function (BABYLON) {
  64816. var Xbox360Button;
  64817. (function (Xbox360Button) {
  64818. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64819. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64820. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64821. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64822. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64823. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64824. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64825. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64826. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64827. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64828. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64829. var Xbox360Dpad;
  64830. (function (Xbox360Dpad) {
  64831. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64832. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64833. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64834. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64835. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64836. var Xbox360Pad = /** @class */ (function (_super) {
  64837. __extends(Xbox360Pad, _super);
  64838. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64839. if (xboxOne === void 0) { xboxOne = false; }
  64840. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64841. _this._leftTrigger = 0;
  64842. _this._rightTrigger = 0;
  64843. _this.onButtonDownObservable = new BABYLON.Observable();
  64844. _this.onButtonUpObservable = new BABYLON.Observable();
  64845. _this.onPadDownObservable = new BABYLON.Observable();
  64846. _this.onPadUpObservable = new BABYLON.Observable();
  64847. _this._buttonA = 0;
  64848. _this._buttonB = 0;
  64849. _this._buttonX = 0;
  64850. _this._buttonY = 0;
  64851. _this._buttonBack = 0;
  64852. _this._buttonStart = 0;
  64853. _this._buttonLB = 0;
  64854. _this._buttonRB = 0;
  64855. _this._buttonLeftStick = 0;
  64856. _this._buttonRightStick = 0;
  64857. _this._dPadUp = 0;
  64858. _this._dPadDown = 0;
  64859. _this._dPadLeft = 0;
  64860. _this._dPadRight = 0;
  64861. _this._isXboxOnePad = false;
  64862. _this.type = BABYLON.Gamepad.XBOX;
  64863. _this._isXboxOnePad = xboxOne;
  64864. return _this;
  64865. }
  64866. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64867. this._onlefttriggerchanged = callback;
  64868. };
  64869. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64870. this._onrighttriggerchanged = callback;
  64871. };
  64872. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64873. get: function () {
  64874. return this._leftTrigger;
  64875. },
  64876. set: function (newValue) {
  64877. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64878. this._onlefttriggerchanged(newValue);
  64879. }
  64880. this._leftTrigger = newValue;
  64881. },
  64882. enumerable: true,
  64883. configurable: true
  64884. });
  64885. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64886. get: function () {
  64887. return this._rightTrigger;
  64888. },
  64889. set: function (newValue) {
  64890. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64891. this._onrighttriggerchanged(newValue);
  64892. }
  64893. this._rightTrigger = newValue;
  64894. },
  64895. enumerable: true,
  64896. configurable: true
  64897. });
  64898. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64899. this._onbuttondown = callback;
  64900. };
  64901. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64902. this._onbuttonup = callback;
  64903. };
  64904. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64905. this._ondpaddown = callback;
  64906. };
  64907. Xbox360Pad.prototype.ondpadup = function (callback) {
  64908. this._ondpadup = callback;
  64909. };
  64910. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64911. if (newValue !== currentValue) {
  64912. if (newValue === 1) {
  64913. if (this._onbuttondown) {
  64914. this._onbuttondown(buttonType);
  64915. }
  64916. this.onButtonDownObservable.notifyObservers(buttonType);
  64917. }
  64918. if (newValue === 0) {
  64919. if (this._onbuttonup) {
  64920. this._onbuttonup(buttonType);
  64921. }
  64922. this.onButtonUpObservable.notifyObservers(buttonType);
  64923. }
  64924. }
  64925. return newValue;
  64926. };
  64927. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64928. if (newValue !== currentValue) {
  64929. if (newValue === 1) {
  64930. if (this._ondpaddown) {
  64931. this._ondpaddown(buttonType);
  64932. }
  64933. this.onPadDownObservable.notifyObservers(buttonType);
  64934. }
  64935. if (newValue === 0) {
  64936. if (this._ondpadup) {
  64937. this._ondpadup(buttonType);
  64938. }
  64939. this.onPadUpObservable.notifyObservers(buttonType);
  64940. }
  64941. }
  64942. return newValue;
  64943. };
  64944. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64945. get: function () {
  64946. return this._buttonA;
  64947. },
  64948. set: function (value) {
  64949. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64950. },
  64951. enumerable: true,
  64952. configurable: true
  64953. });
  64954. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64955. get: function () {
  64956. return this._buttonB;
  64957. },
  64958. set: function (value) {
  64959. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64960. },
  64961. enumerable: true,
  64962. configurable: true
  64963. });
  64964. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64965. get: function () {
  64966. return this._buttonX;
  64967. },
  64968. set: function (value) {
  64969. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64970. },
  64971. enumerable: true,
  64972. configurable: true
  64973. });
  64974. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64975. get: function () {
  64976. return this._buttonY;
  64977. },
  64978. set: function (value) {
  64979. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64980. },
  64981. enumerable: true,
  64982. configurable: true
  64983. });
  64984. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64985. get: function () {
  64986. return this._buttonStart;
  64987. },
  64988. set: function (value) {
  64989. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64990. },
  64991. enumerable: true,
  64992. configurable: true
  64993. });
  64994. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64995. get: function () {
  64996. return this._buttonBack;
  64997. },
  64998. set: function (value) {
  64999. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65000. },
  65001. enumerable: true,
  65002. configurable: true
  65003. });
  65004. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65005. get: function () {
  65006. return this._buttonLB;
  65007. },
  65008. set: function (value) {
  65009. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65010. },
  65011. enumerable: true,
  65012. configurable: true
  65013. });
  65014. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65015. get: function () {
  65016. return this._buttonRB;
  65017. },
  65018. set: function (value) {
  65019. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65020. },
  65021. enumerable: true,
  65022. configurable: true
  65023. });
  65024. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65025. get: function () {
  65026. return this._buttonLeftStick;
  65027. },
  65028. set: function (value) {
  65029. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65030. },
  65031. enumerable: true,
  65032. configurable: true
  65033. });
  65034. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65035. get: function () {
  65036. return this._buttonRightStick;
  65037. },
  65038. set: function (value) {
  65039. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65040. },
  65041. enumerable: true,
  65042. configurable: true
  65043. });
  65044. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65045. get: function () {
  65046. return this._dPadUp;
  65047. },
  65048. set: function (value) {
  65049. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65050. },
  65051. enumerable: true,
  65052. configurable: true
  65053. });
  65054. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65055. get: function () {
  65056. return this._dPadDown;
  65057. },
  65058. set: function (value) {
  65059. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65060. },
  65061. enumerable: true,
  65062. configurable: true
  65063. });
  65064. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65065. get: function () {
  65066. return this._dPadLeft;
  65067. },
  65068. set: function (value) {
  65069. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65070. },
  65071. enumerable: true,
  65072. configurable: true
  65073. });
  65074. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  65075. get: function () {
  65076. return this._dPadRight;
  65077. },
  65078. set: function (value) {
  65079. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  65080. },
  65081. enumerable: true,
  65082. configurable: true
  65083. });
  65084. Xbox360Pad.prototype.update = function () {
  65085. _super.prototype.update.call(this);
  65086. if (this._isXboxOnePad) {
  65087. this.buttonA = this.browserGamepad.buttons[0].value;
  65088. this.buttonB = this.browserGamepad.buttons[1].value;
  65089. this.buttonX = this.browserGamepad.buttons[2].value;
  65090. this.buttonY = this.browserGamepad.buttons[3].value;
  65091. this.buttonLB = this.browserGamepad.buttons[4].value;
  65092. this.buttonRB = this.browserGamepad.buttons[5].value;
  65093. this.leftTrigger = this.browserGamepad.axes[2];
  65094. this.rightTrigger = this.browserGamepad.axes[5];
  65095. this.buttonBack = this.browserGamepad.buttons[9].value;
  65096. this.buttonStart = this.browserGamepad.buttons[8].value;
  65097. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  65098. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  65099. this.dPadUp = this.browserGamepad.buttons[11].value;
  65100. this.dPadDown = this.browserGamepad.buttons[12].value;
  65101. this.dPadLeft = this.browserGamepad.buttons[13].value;
  65102. this.dPadRight = this.browserGamepad.buttons[14].value;
  65103. }
  65104. else {
  65105. this.buttonA = this.browserGamepad.buttons[0].value;
  65106. this.buttonB = this.browserGamepad.buttons[1].value;
  65107. this.buttonX = this.browserGamepad.buttons[2].value;
  65108. this.buttonY = this.browserGamepad.buttons[3].value;
  65109. this.buttonLB = this.browserGamepad.buttons[4].value;
  65110. this.buttonRB = this.browserGamepad.buttons[5].value;
  65111. this.leftTrigger = this.browserGamepad.buttons[6].value;
  65112. this.rightTrigger = this.browserGamepad.buttons[7].value;
  65113. this.buttonBack = this.browserGamepad.buttons[8].value;
  65114. this.buttonStart = this.browserGamepad.buttons[9].value;
  65115. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  65116. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  65117. this.dPadUp = this.browserGamepad.buttons[12].value;
  65118. this.dPadDown = this.browserGamepad.buttons[13].value;
  65119. this.dPadLeft = this.browserGamepad.buttons[14].value;
  65120. this.dPadRight = this.browserGamepad.buttons[15].value;
  65121. }
  65122. };
  65123. Xbox360Pad.prototype.dispose = function () {
  65124. _super.prototype.dispose.call(this);
  65125. this.onButtonDownObservable.clear();
  65126. this.onButtonUpObservable.clear();
  65127. this.onPadDownObservable.clear();
  65128. this.onPadUpObservable.clear();
  65129. };
  65130. return Xbox360Pad;
  65131. }(BABYLON.Gamepad));
  65132. BABYLON.Xbox360Pad = Xbox360Pad;
  65133. })(BABYLON || (BABYLON = {}));
  65134. //# sourceMappingURL=babylon.xboxGamepad.js.map
  65135. var BABYLON;
  65136. (function (BABYLON) {
  65137. var PoseEnabledControllerType;
  65138. (function (PoseEnabledControllerType) {
  65139. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  65140. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  65141. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  65142. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  65143. /**
  65144. * Google Daydream
  65145. */
  65146. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  65147. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  65148. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  65149. var PoseEnabledControllerHelper = /** @class */ (function () {
  65150. function PoseEnabledControllerHelper() {
  65151. }
  65152. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  65153. // Oculus Touch
  65154. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  65155. return new BABYLON.OculusTouchController(vrGamepad);
  65156. }
  65157. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  65158. return new BABYLON.WindowsMotionController(vrGamepad);
  65159. }
  65160. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  65161. return new BABYLON.ViveController(vrGamepad);
  65162. }
  65163. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  65164. return new BABYLON.GearVRController(vrGamepad);
  65165. }
  65166. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  65167. return new BABYLON.DaydreamController(vrGamepad);
  65168. }
  65169. else {
  65170. return new BABYLON.GenericController(vrGamepad);
  65171. }
  65172. };
  65173. return PoseEnabledControllerHelper;
  65174. }());
  65175. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  65176. var PoseEnabledController = /** @class */ (function (_super) {
  65177. __extends(PoseEnabledController, _super);
  65178. function PoseEnabledController(browserGamepad) {
  65179. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  65180. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  65181. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  65182. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  65183. // Represents device position and rotation in babylon space
  65184. _this.devicePosition = BABYLON.Vector3.Zero();
  65185. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65186. _this.deviceScaleFactor = 1;
  65187. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  65188. _this._deviceToWorld = BABYLON.Matrix.Identity();
  65189. /**
  65190. * Node to be used when casting a ray from the controller
  65191. */
  65192. _this._pointingPoseNode = null;
  65193. _this._workingMatrix = BABYLON.Matrix.Identity();
  65194. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  65195. _this.controllerType = PoseEnabledControllerType.GENERIC;
  65196. _this.position = BABYLON.Vector3.Zero();
  65197. _this.rotationQuaternion = new BABYLON.Quaternion();
  65198. _this._calculatedPosition = BABYLON.Vector3.Zero();
  65199. _this._calculatedRotation = new BABYLON.Quaternion();
  65200. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  65201. return _this;
  65202. }
  65203. PoseEnabledController.prototype.update = function () {
  65204. _super.prototype.update.call(this);
  65205. var pose = this.browserGamepad.pose;
  65206. this.updateFromDevice(pose);
  65207. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  65208. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  65209. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  65210. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  65211. if (this._mesh) {
  65212. this._mesh.position.copyFrom(this.devicePosition);
  65213. if (this._mesh.rotationQuaternion) {
  65214. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65215. }
  65216. }
  65217. };
  65218. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  65219. if (poseData) {
  65220. this.rawPose = poseData;
  65221. if (poseData.position) {
  65222. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  65223. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  65224. this._deviceRoomPosition.z *= -1;
  65225. }
  65226. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  65227. this._calculatedPosition.addInPlace(this.position);
  65228. }
  65229. var pose = this.rawPose;
  65230. if (poseData.orientation && pose.orientation) {
  65231. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  65232. if (this._mesh) {
  65233. if (this._mesh.getScene().useRightHandedSystem) {
  65234. this._deviceRoomRotationQuaternion.z *= -1;
  65235. this._deviceRoomRotationQuaternion.w *= -1;
  65236. }
  65237. else {
  65238. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  65239. }
  65240. }
  65241. // if the camera is set, rotate to the camera's rotation
  65242. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  65243. }
  65244. }
  65245. };
  65246. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  65247. if (this._mesh) {
  65248. this._mesh.parent = null;
  65249. }
  65250. this._mesh = mesh;
  65251. if (this._poseControlledCamera) {
  65252. this._mesh.parent = this._poseControlledCamera;
  65253. }
  65254. if (!this._mesh.rotationQuaternion) {
  65255. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65256. }
  65257. };
  65258. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65259. this._poseControlledCamera = camera;
  65260. if (this._mesh) {
  65261. this._mesh.parent = this._poseControlledCamera;
  65262. }
  65263. };
  65264. PoseEnabledController.prototype.dispose = function () {
  65265. if (this._mesh) {
  65266. this._mesh.dispose();
  65267. }
  65268. this._mesh = null;
  65269. _super.prototype.dispose.call(this);
  65270. };
  65271. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65272. get: function () {
  65273. return this._mesh;
  65274. },
  65275. enumerable: true,
  65276. configurable: true
  65277. });
  65278. PoseEnabledController.prototype.getForwardRay = function (length) {
  65279. if (length === void 0) { length = 100; }
  65280. if (!this.mesh) {
  65281. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65282. }
  65283. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  65284. var origin = m.getTranslation();
  65285. var forward = new BABYLON.Vector3(0, 0, -1);
  65286. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65287. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65288. return new BABYLON.Ray(origin, direction, length);
  65289. };
  65290. /**
  65291. * Name of the child mesh that can be used to cast a ray from the controller
  65292. */
  65293. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  65294. return PoseEnabledController;
  65295. }(BABYLON.Gamepad));
  65296. BABYLON.PoseEnabledController = PoseEnabledController;
  65297. })(BABYLON || (BABYLON = {}));
  65298. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65299. var BABYLON;
  65300. (function (BABYLON) {
  65301. var WebVRController = /** @class */ (function (_super) {
  65302. __extends(WebVRController, _super);
  65303. function WebVRController(vrGamepad) {
  65304. var _this = _super.call(this, vrGamepad) || this;
  65305. // Observables
  65306. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65307. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65308. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65309. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65310. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65311. _this.pad = { x: 0, y: 0 };
  65312. // avoid GC, store state in a tmp object
  65313. _this._changes = {
  65314. pressChanged: false,
  65315. touchChanged: false,
  65316. valueChanged: false,
  65317. changed: false
  65318. };
  65319. _this._buttons = new Array(vrGamepad.buttons.length);
  65320. _this.hand = vrGamepad.hand;
  65321. return _this;
  65322. }
  65323. WebVRController.prototype.onButtonStateChange = function (callback) {
  65324. this._onButtonStateChange = callback;
  65325. };
  65326. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65327. get: function () {
  65328. return this._defaultModel;
  65329. },
  65330. enumerable: true,
  65331. configurable: true
  65332. });
  65333. WebVRController.prototype.update = function () {
  65334. _super.prototype.update.call(this);
  65335. for (var index = 0; index < this._buttons.length; index++) {
  65336. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65337. }
  65338. ;
  65339. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65340. this.pad.x = this.leftStick.x;
  65341. this.pad.y = this.leftStick.y;
  65342. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65343. }
  65344. };
  65345. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65346. if (!newState) {
  65347. newState = {
  65348. pressed: false,
  65349. touched: false,
  65350. value: 0
  65351. };
  65352. }
  65353. if (!currentState) {
  65354. this._buttons[buttonIndex] = {
  65355. pressed: newState.pressed,
  65356. touched: newState.touched,
  65357. value: newState.value
  65358. };
  65359. return;
  65360. }
  65361. this._checkChanges(newState, currentState);
  65362. if (this._changes.changed) {
  65363. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65364. this._handleButtonChange(buttonIndex, newState, this._changes);
  65365. }
  65366. this._buttons[buttonIndex].pressed = newState.pressed;
  65367. this._buttons[buttonIndex].touched = newState.touched;
  65368. // oculus triggers are never 0, thou not touched.
  65369. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65370. };
  65371. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65372. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65373. this._changes.touchChanged = newState.touched !== currentState.touched;
  65374. this._changes.valueChanged = newState.value !== currentState.value;
  65375. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65376. return this._changes;
  65377. };
  65378. WebVRController.prototype.dispose = function () {
  65379. _super.prototype.dispose.call(this);
  65380. this.onTriggerStateChangedObservable.clear();
  65381. this.onMainButtonStateChangedObservable.clear();
  65382. this.onSecondaryButtonStateChangedObservable.clear();
  65383. this.onPadStateChangedObservable.clear();
  65384. this.onPadValuesChangedObservable.clear();
  65385. };
  65386. return WebVRController;
  65387. }(BABYLON.PoseEnabledController));
  65388. BABYLON.WebVRController = WebVRController;
  65389. })(BABYLON || (BABYLON = {}));
  65390. //# sourceMappingURL=babylon.webVRController.js.map
  65391. var BABYLON;
  65392. (function (BABYLON) {
  65393. var OculusTouchController = /** @class */ (function (_super) {
  65394. __extends(OculusTouchController, _super);
  65395. function OculusTouchController(vrGamepad) {
  65396. var _this = _super.call(this, vrGamepad) || this;
  65397. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65398. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65399. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65400. return _this;
  65401. }
  65402. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65403. var _this = this;
  65404. var meshName;
  65405. // Hand
  65406. if (this.hand === 'left') {
  65407. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65408. }
  65409. else {
  65410. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65411. }
  65412. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65413. /*
  65414. Parent Mesh name: oculus_touch_left
  65415. - body
  65416. - trigger
  65417. - thumbstick
  65418. - grip
  65419. - button_y
  65420. - button_x
  65421. - button_enter
  65422. */
  65423. _this._defaultModel = newMeshes[1];
  65424. _this.attachToMesh(_this._defaultModel);
  65425. if (meshLoaded) {
  65426. meshLoaded(_this._defaultModel);
  65427. }
  65428. });
  65429. };
  65430. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65431. // helper getters for left and right hand.
  65432. get: function () {
  65433. if (this.hand === 'right') {
  65434. return this.onMainButtonStateChangedObservable;
  65435. }
  65436. else {
  65437. throw new Error('No A button on left hand');
  65438. }
  65439. },
  65440. enumerable: true,
  65441. configurable: true
  65442. });
  65443. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65444. get: function () {
  65445. if (this.hand === 'right') {
  65446. return this.onSecondaryButtonStateChangedObservable;
  65447. }
  65448. else {
  65449. throw new Error('No B button on left hand');
  65450. }
  65451. },
  65452. enumerable: true,
  65453. configurable: true
  65454. });
  65455. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65456. get: function () {
  65457. if (this.hand === 'left') {
  65458. return this.onMainButtonStateChangedObservable;
  65459. }
  65460. else {
  65461. throw new Error('No X button on right hand');
  65462. }
  65463. },
  65464. enumerable: true,
  65465. configurable: true
  65466. });
  65467. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65468. get: function () {
  65469. if (this.hand === 'left') {
  65470. return this.onSecondaryButtonStateChangedObservable;
  65471. }
  65472. else {
  65473. throw new Error('No Y button on right hand');
  65474. }
  65475. },
  65476. enumerable: true,
  65477. configurable: true
  65478. });
  65479. /*
  65480. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65481. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65482. 2) secondary trigger (same)
  65483. 3) A (right) X (left), touch, pressed = value
  65484. 4) B / Y
  65485. 5) thumb rest
  65486. */
  65487. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65488. var notifyObject = state; //{ state: state, changes: changes };
  65489. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65490. switch (buttonIdx) {
  65491. case 0:
  65492. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65493. return;
  65494. case 1:// index trigger
  65495. if (this._defaultModel) {
  65496. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65497. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65498. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65499. }
  65500. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65501. return;
  65502. case 2:// secondary trigger
  65503. if (this._defaultModel) {
  65504. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65505. }
  65506. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65507. return;
  65508. case 3:
  65509. if (this._defaultModel) {
  65510. if (notifyObject.pressed) {
  65511. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65512. }
  65513. else {
  65514. (this._defaultModel.getChildren()[1]).position.y = 0;
  65515. }
  65516. }
  65517. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65518. return;
  65519. case 4:
  65520. if (this._defaultModel) {
  65521. if (notifyObject.pressed) {
  65522. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65523. }
  65524. else {
  65525. (this._defaultModel.getChildren()[2]).position.y = 0;
  65526. }
  65527. }
  65528. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65529. return;
  65530. case 5:
  65531. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65532. return;
  65533. }
  65534. };
  65535. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65536. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65537. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65538. return OculusTouchController;
  65539. }(BABYLON.WebVRController));
  65540. BABYLON.OculusTouchController = OculusTouchController;
  65541. })(BABYLON || (BABYLON = {}));
  65542. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65543. var BABYLON;
  65544. (function (BABYLON) {
  65545. var ViveController = /** @class */ (function (_super) {
  65546. __extends(ViveController, _super);
  65547. function ViveController(vrGamepad) {
  65548. var _this = _super.call(this, vrGamepad) || this;
  65549. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65550. _this._invertLeftStickY = true;
  65551. return _this;
  65552. }
  65553. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65554. var _this = this;
  65555. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65556. /*
  65557. Parent Mesh name: ViveWand
  65558. - body
  65559. - r_gripper
  65560. - l_gripper
  65561. - menu_button
  65562. - system_button
  65563. - trackpad
  65564. - trigger
  65565. - LED
  65566. */
  65567. _this._defaultModel = newMeshes[1];
  65568. _this.attachToMesh(_this._defaultModel);
  65569. if (meshLoaded) {
  65570. meshLoaded(_this._defaultModel);
  65571. }
  65572. });
  65573. };
  65574. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65575. get: function () {
  65576. return this.onMainButtonStateChangedObservable;
  65577. },
  65578. enumerable: true,
  65579. configurable: true
  65580. });
  65581. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65582. get: function () {
  65583. return this.onMainButtonStateChangedObservable;
  65584. },
  65585. enumerable: true,
  65586. configurable: true
  65587. });
  65588. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65589. get: function () {
  65590. return this.onSecondaryButtonStateChangedObservable;
  65591. },
  65592. enumerable: true,
  65593. configurable: true
  65594. });
  65595. /**
  65596. * Vive mapping:
  65597. * 0: touchpad
  65598. * 1: trigger
  65599. * 2: left AND right buttons
  65600. * 3: menu button
  65601. */
  65602. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65603. var notifyObject = state; //{ state: state, changes: changes };
  65604. switch (buttonIdx) {
  65605. case 0:
  65606. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65607. return;
  65608. case 1:// index trigger
  65609. if (this._defaultModel) {
  65610. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65611. }
  65612. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65613. return;
  65614. case 2:// left AND right button
  65615. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65616. return;
  65617. case 3:
  65618. if (this._defaultModel) {
  65619. if (notifyObject.pressed) {
  65620. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65621. }
  65622. else {
  65623. (this._defaultModel.getChildren()[2]).position.y = 0;
  65624. }
  65625. }
  65626. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65627. return;
  65628. }
  65629. };
  65630. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65631. ViveController.MODEL_FILENAME = 'wand.babylon';
  65632. return ViveController;
  65633. }(BABYLON.WebVRController));
  65634. BABYLON.ViveController = ViveController;
  65635. })(BABYLON || (BABYLON = {}));
  65636. //# sourceMappingURL=babylon.viveController.js.map
  65637. var BABYLON;
  65638. (function (BABYLON) {
  65639. var GenericController = /** @class */ (function (_super) {
  65640. __extends(GenericController, _super);
  65641. function GenericController(vrGamepad) {
  65642. return _super.call(this, vrGamepad) || this;
  65643. }
  65644. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65645. var _this = this;
  65646. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65647. _this._defaultModel = newMeshes[1];
  65648. _this.attachToMesh(_this._defaultModel);
  65649. if (meshLoaded) {
  65650. meshLoaded(_this._defaultModel);
  65651. }
  65652. });
  65653. };
  65654. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65655. console.log("Button id: " + buttonIdx + "state: ");
  65656. console.dir(state);
  65657. };
  65658. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65659. GenericController.MODEL_FILENAME = 'generic.babylon';
  65660. return GenericController;
  65661. }(BABYLON.WebVRController));
  65662. BABYLON.GenericController = GenericController;
  65663. })(BABYLON || (BABYLON = {}));
  65664. //# sourceMappingURL=babylon.genericController.js.map
  65665. var BABYLON;
  65666. (function (BABYLON) {
  65667. var LoadedMeshInfo = /** @class */ (function () {
  65668. function LoadedMeshInfo() {
  65669. this.buttonMeshes = {};
  65670. this.axisMeshes = {};
  65671. }
  65672. return LoadedMeshInfo;
  65673. }());
  65674. var WindowsMotionController = /** @class */ (function (_super) {
  65675. __extends(WindowsMotionController, _super);
  65676. function WindowsMotionController(vrGamepad) {
  65677. var _this = _super.call(this, vrGamepad) || this;
  65678. _this._mapping = {
  65679. // Semantic button names
  65680. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65681. // A mapping of the button name to glTF model node name
  65682. // that should be transformed by button value.
  65683. buttonMeshNames: {
  65684. 'trigger': 'SELECT',
  65685. 'menu': 'MENU',
  65686. 'grip': 'GRASP',
  65687. 'thumbstick': 'THUMBSTICK_PRESS',
  65688. 'trackpad': 'TOUCHPAD_PRESS'
  65689. },
  65690. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65691. buttonObservableNames: {
  65692. 'trigger': 'onTriggerStateChangedObservable',
  65693. 'menu': 'onSecondaryButtonStateChangedObservable',
  65694. 'grip': 'onMainButtonStateChangedObservable',
  65695. 'thumbstick': 'onPadStateChangedObservable',
  65696. 'trackpad': 'onTrackpadChangedObservable'
  65697. },
  65698. // A mapping of the axis name to glTF model node name
  65699. // that should be transformed by axis value.
  65700. // This array mirrors the browserGamepad.axes array, such that
  65701. // the mesh corresponding to axis 0 is in this array index 0.
  65702. axisMeshNames: [
  65703. 'THUMBSTICK_X',
  65704. 'THUMBSTICK_Y',
  65705. 'TOUCHPAD_TOUCH_X',
  65706. 'TOUCHPAD_TOUCH_Y'
  65707. ],
  65708. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  65709. };
  65710. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65711. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65712. _this.trackpad = { x: 0, y: 0 };
  65713. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65714. _this._loadedMeshInfo = null;
  65715. return _this;
  65716. }
  65717. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65718. get: function () {
  65719. return this.onTriggerStateChangedObservable;
  65720. },
  65721. enumerable: true,
  65722. configurable: true
  65723. });
  65724. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65725. get: function () {
  65726. return this.onSecondaryButtonStateChangedObservable;
  65727. },
  65728. enumerable: true,
  65729. configurable: true
  65730. });
  65731. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65732. get: function () {
  65733. return this.onMainButtonStateChangedObservable;
  65734. },
  65735. enumerable: true,
  65736. configurable: true
  65737. });
  65738. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65739. get: function () {
  65740. return this.onPadStateChangedObservable;
  65741. },
  65742. enumerable: true,
  65743. configurable: true
  65744. });
  65745. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65746. get: function () {
  65747. return this.onTrackpadChangedObservable;
  65748. },
  65749. enumerable: true,
  65750. configurable: true
  65751. });
  65752. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65753. get: function () {
  65754. return this.onTrackpadValuesChangedObservable;
  65755. },
  65756. enumerable: true,
  65757. configurable: true
  65758. });
  65759. /**
  65760. * Called once per frame by the engine.
  65761. */
  65762. WindowsMotionController.prototype.update = function () {
  65763. _super.prototype.update.call(this);
  65764. if (this.browserGamepad.axes) {
  65765. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65766. this.trackpad.x = this.browserGamepad["axes"][2];
  65767. this.trackpad.y = this.browserGamepad["axes"][3];
  65768. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65769. }
  65770. // Only need to animate axes if there is a loaded mesh
  65771. if (this._loadedMeshInfo) {
  65772. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65773. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65774. }
  65775. }
  65776. }
  65777. };
  65778. /**
  65779. * Called once for each button that changed state since the last frame
  65780. * @param buttonIdx Which button index changed
  65781. * @param state New state of the button
  65782. * @param changes Which properties on the state changed since last frame
  65783. */
  65784. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65785. var buttonName = this._mapping.buttons[buttonIdx];
  65786. if (!buttonName) {
  65787. return;
  65788. }
  65789. // Only emit events for buttons that we know how to map from index to name
  65790. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65791. if (observable) {
  65792. observable.notifyObservers(state);
  65793. }
  65794. this.lerpButtonTransform(buttonName, state.value);
  65795. };
  65796. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65797. // If there is no loaded mesh, there is nothing to transform.
  65798. if (!this._loadedMeshInfo) {
  65799. return;
  65800. }
  65801. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65802. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65803. return;
  65804. }
  65805. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65806. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65807. };
  65808. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65809. if (!this._loadedMeshInfo) {
  65810. return;
  65811. }
  65812. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65813. if (!meshInfo) {
  65814. return;
  65815. }
  65816. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65817. return;
  65818. }
  65819. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65820. var lerpValue = axisValue * 0.5 + 0.5;
  65821. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65822. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65823. };
  65824. /**
  65825. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65826. * @param scene scene in which to add meshes
  65827. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65828. */
  65829. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65830. var _this = this;
  65831. if (forceDefault === void 0) { forceDefault = false; }
  65832. var path;
  65833. var filename;
  65834. // Checking if GLB loader is present
  65835. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65836. // Determine the device specific folder based on the ID suffix
  65837. var device = 'default';
  65838. if (this.id && !forceDefault) {
  65839. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65840. device = ((match && match[0]) || device);
  65841. }
  65842. // Hand
  65843. if (this.hand === 'left') {
  65844. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65845. }
  65846. else {
  65847. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65848. }
  65849. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65850. }
  65851. else {
  65852. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65853. path = BABYLON.GenericController.MODEL_BASE_URL;
  65854. filename = BABYLON.GenericController.MODEL_FILENAME;
  65855. }
  65856. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65857. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65858. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65859. if (!_this._loadedMeshInfo) {
  65860. return;
  65861. }
  65862. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65863. _this.attachToMesh(_this._defaultModel);
  65864. if (meshLoaded) {
  65865. meshLoaded(_this._defaultModel);
  65866. }
  65867. }, null, function (scene, message) {
  65868. BABYLON.Tools.Log(message);
  65869. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65870. if (!forceDefault) {
  65871. _this.initControllerMesh(scene, meshLoaded, true);
  65872. }
  65873. });
  65874. };
  65875. /**
  65876. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65877. * can be transformed by button presses and axes values, based on this._mapping.
  65878. *
  65879. * @param scene scene in which the meshes exist
  65880. * @param meshes list of meshes that make up the controller model to process
  65881. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65882. */
  65883. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65884. var loadedMeshInfo = null;
  65885. // Create a new mesh to contain the glTF hierarchy
  65886. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65887. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65888. var childMesh = null;
  65889. for (var i = 0; i < meshes.length; i++) {
  65890. var mesh = meshes[i];
  65891. if (!mesh.parent) {
  65892. // Exclude controller meshes from picking results
  65893. mesh.isPickable = false;
  65894. // Handle root node, attach to the new parentMesh
  65895. childMesh = mesh;
  65896. break;
  65897. }
  65898. }
  65899. if (childMesh) {
  65900. childMesh.setParent(parentMesh);
  65901. // Create our mesh info. Note that this method will always return non-null.
  65902. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65903. }
  65904. else {
  65905. BABYLON.Tools.Warn('Could not find root node in model file.');
  65906. }
  65907. return loadedMeshInfo;
  65908. };
  65909. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65910. var loadedMeshInfo = new LoadedMeshInfo();
  65911. var i;
  65912. loadedMeshInfo.rootNode = rootNode;
  65913. // Reset the caches
  65914. loadedMeshInfo.buttonMeshes = {};
  65915. loadedMeshInfo.axisMeshes = {};
  65916. // Button Meshes
  65917. for (i = 0; i < this._mapping.buttons.length; i++) {
  65918. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65919. if (!buttonMeshName) {
  65920. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65921. continue;
  65922. }
  65923. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65924. if (!buttonMesh) {
  65925. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65926. continue;
  65927. }
  65928. var buttonMeshInfo = {
  65929. index: i,
  65930. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65931. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65932. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65933. };
  65934. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65935. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65936. }
  65937. else {
  65938. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65939. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65940. '(VALUE: ' + !!buttonMeshInfo.value +
  65941. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65942. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65943. ')');
  65944. }
  65945. }
  65946. // Axis Meshes
  65947. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65948. var axisMeshName = this._mapping.axisMeshNames[i];
  65949. if (!axisMeshName) {
  65950. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65951. continue;
  65952. }
  65953. var axisMesh = getChildByName(rootNode, axisMeshName);
  65954. if (!axisMesh) {
  65955. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65956. continue;
  65957. }
  65958. var axisMeshInfo = {
  65959. index: i,
  65960. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65961. min: getImmediateChildByName(axisMesh, 'MIN'),
  65962. max: getImmediateChildByName(axisMesh, 'MAX')
  65963. };
  65964. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65965. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65966. }
  65967. else {
  65968. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65969. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65970. '(VALUE: ' + !!axisMeshInfo.value +
  65971. ', MIN: ' + !!axisMeshInfo.min +
  65972. ', MAX:' + !!axisMeshInfo.max +
  65973. ')');
  65974. }
  65975. }
  65976. // Pointing Ray
  65977. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65978. if (!loadedMeshInfo.pointingPoseNode) {
  65979. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65980. }
  65981. return loadedMeshInfo;
  65982. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65983. function getChildByName(node, name) {
  65984. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65985. }
  65986. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65987. function getImmediateChildByName(node, name) {
  65988. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65989. }
  65990. };
  65991. WindowsMotionController.prototype.getForwardRay = function (length) {
  65992. if (length === void 0) { length = 100; }
  65993. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65994. return _super.prototype.getForwardRay.call(this, length);
  65995. }
  65996. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65997. var origin = m.getTranslation();
  65998. var forward = new BABYLON.Vector3(0, 0, -1);
  65999. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66000. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66001. return new BABYLON.Ray(origin, direction, length);
  66002. };
  66003. WindowsMotionController.prototype.dispose = function () {
  66004. _super.prototype.dispose.call(this);
  66005. this.onTrackpadChangedObservable.clear();
  66006. };
  66007. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66008. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66009. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66010. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66011. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66012. return WindowsMotionController;
  66013. }(BABYLON.WebVRController));
  66014. BABYLON.WindowsMotionController = WindowsMotionController;
  66015. })(BABYLON || (BABYLON = {}));
  66016. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66017. var BABYLON;
  66018. (function (BABYLON) {
  66019. var GearVRController = /** @class */ (function (_super) {
  66020. __extends(GearVRController, _super);
  66021. function GearVRController(vrGamepad) {
  66022. var _this = _super.call(this, vrGamepad) || this;
  66023. _this._buttonIndexToObservableNameMap = [
  66024. 'onTrackpadChangedObservable',
  66025. 'onTriggerStateChangedObservable' // Trigger
  66026. ];
  66027. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66028. return _this;
  66029. }
  66030. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66031. var _this = this;
  66032. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66033. _this._defaultModel = newMeshes[1];
  66034. _this.attachToMesh(_this._defaultModel);
  66035. if (meshLoaded) {
  66036. meshLoaded(_this._defaultModel);
  66037. }
  66038. });
  66039. };
  66040. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66041. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66042. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66043. // Only emit events for buttons that we know how to map from index to observable
  66044. var observable = this[observableName];
  66045. if (observable) {
  66046. observable.notifyObservers(state);
  66047. }
  66048. }
  66049. };
  66050. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66051. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66052. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66053. return GearVRController;
  66054. }(BABYLON.WebVRController));
  66055. BABYLON.GearVRController = GearVRController;
  66056. })(BABYLON || (BABYLON = {}));
  66057. //# sourceMappingURL=babylon.gearVRController.js.map
  66058. var BABYLON;
  66059. (function (BABYLON) {
  66060. /**
  66061. * Google Daydream controller
  66062. */
  66063. var DaydreamController = /** @class */ (function (_super) {
  66064. __extends(DaydreamController, _super);
  66065. function DaydreamController(vrGamepad) {
  66066. var _this = _super.call(this, vrGamepad) || this;
  66067. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66068. return _this;
  66069. }
  66070. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66071. var _this = this;
  66072. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  66073. _this._defaultModel = newMeshes[1];
  66074. _this.attachToMesh(_this._defaultModel);
  66075. if (meshLoaded) {
  66076. meshLoaded(_this._defaultModel);
  66077. }
  66078. });
  66079. };
  66080. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66081. // Daydream controller only has 1 GamepadButton (on the trackpad).
  66082. if (buttonIdx === 0) {
  66083. var observable = this.onTriggerStateChangedObservable;
  66084. if (observable) {
  66085. observable.notifyObservers(state);
  66086. }
  66087. }
  66088. else {
  66089. // If the app or home buttons are ever made available
  66090. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  66091. }
  66092. };
  66093. /**
  66094. * Base Url for the controller model.
  66095. */
  66096. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66097. /**
  66098. * File name for the controller model.
  66099. */
  66100. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  66101. /**
  66102. * Gamepad Id prefix used to identify Daydream Controller.
  66103. */
  66104. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  66105. return DaydreamController;
  66106. }(BABYLON.WebVRController));
  66107. BABYLON.DaydreamController = DaydreamController;
  66108. })(BABYLON || (BABYLON = {}));
  66109. //# sourceMappingURL=babylon.daydreamController.js.map
  66110. var BABYLON;
  66111. (function (BABYLON) {
  66112. var FollowCamera = /** @class */ (function (_super) {
  66113. __extends(FollowCamera, _super);
  66114. function FollowCamera(name, position, scene, lockedTarget) {
  66115. if (lockedTarget === void 0) { lockedTarget = null; }
  66116. var _this = _super.call(this, name, position, scene) || this;
  66117. _this.radius = 12;
  66118. _this.rotationOffset = 0;
  66119. _this.heightOffset = 4;
  66120. _this.cameraAcceleration = 0.05;
  66121. _this.maxCameraSpeed = 20;
  66122. _this.lockedTarget = lockedTarget;
  66123. return _this;
  66124. }
  66125. FollowCamera.prototype.getRadians = function (degrees) {
  66126. return degrees * Math.PI / 180;
  66127. };
  66128. FollowCamera.prototype.follow = function (cameraTarget) {
  66129. if (!cameraTarget)
  66130. return;
  66131. var yRotation;
  66132. if (cameraTarget.rotationQuaternion) {
  66133. var rotMatrix = new BABYLON.Matrix();
  66134. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  66135. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  66136. }
  66137. else {
  66138. yRotation = cameraTarget.rotation.y;
  66139. }
  66140. var radians = this.getRadians(this.rotationOffset) + yRotation;
  66141. var targetPosition = cameraTarget.getAbsolutePosition();
  66142. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  66143. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  66144. var dx = targetX - this.position.x;
  66145. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  66146. var dz = (targetZ) - this.position.z;
  66147. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  66148. var vy = dy * this.cameraAcceleration;
  66149. var vz = dz * this.cameraAcceleration * 2;
  66150. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  66151. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66152. }
  66153. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  66154. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66155. }
  66156. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  66157. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66158. }
  66159. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  66160. this.setTarget(targetPosition);
  66161. };
  66162. FollowCamera.prototype._checkInputs = function () {
  66163. _super.prototype._checkInputs.call(this);
  66164. if (this.lockedTarget) {
  66165. this.follow(this.lockedTarget);
  66166. }
  66167. };
  66168. FollowCamera.prototype.getClassName = function () {
  66169. return "FollowCamera";
  66170. };
  66171. __decorate([
  66172. BABYLON.serialize()
  66173. ], FollowCamera.prototype, "radius", void 0);
  66174. __decorate([
  66175. BABYLON.serialize()
  66176. ], FollowCamera.prototype, "rotationOffset", void 0);
  66177. __decorate([
  66178. BABYLON.serialize()
  66179. ], FollowCamera.prototype, "heightOffset", void 0);
  66180. __decorate([
  66181. BABYLON.serialize()
  66182. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  66183. __decorate([
  66184. BABYLON.serialize()
  66185. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  66186. __decorate([
  66187. BABYLON.serializeAsMeshReference("lockedTargetId")
  66188. ], FollowCamera.prototype, "lockedTarget", void 0);
  66189. return FollowCamera;
  66190. }(BABYLON.TargetCamera));
  66191. BABYLON.FollowCamera = FollowCamera;
  66192. var ArcFollowCamera = /** @class */ (function (_super) {
  66193. __extends(ArcFollowCamera, _super);
  66194. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  66195. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  66196. _this.alpha = alpha;
  66197. _this.beta = beta;
  66198. _this.radius = radius;
  66199. _this.target = target;
  66200. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  66201. _this.follow();
  66202. return _this;
  66203. }
  66204. ArcFollowCamera.prototype.follow = function () {
  66205. if (!this.target) {
  66206. return;
  66207. }
  66208. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  66209. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  66210. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  66211. var targetPosition = this.target.getAbsolutePosition();
  66212. this.position = targetPosition.add(this._cartesianCoordinates);
  66213. this.setTarget(targetPosition);
  66214. };
  66215. ArcFollowCamera.prototype._checkInputs = function () {
  66216. _super.prototype._checkInputs.call(this);
  66217. this.follow();
  66218. };
  66219. ArcFollowCamera.prototype.getClassName = function () {
  66220. return "ArcFollowCamera";
  66221. };
  66222. return ArcFollowCamera;
  66223. }(BABYLON.TargetCamera));
  66224. BABYLON.ArcFollowCamera = ArcFollowCamera;
  66225. })(BABYLON || (BABYLON = {}));
  66226. //# sourceMappingURL=babylon.followCamera.js.map
  66227. var BABYLON;
  66228. (function (BABYLON) {
  66229. // We're mainly based on the logic defined into the FreeCamera code
  66230. var UniversalCamera = /** @class */ (function (_super) {
  66231. __extends(UniversalCamera, _super);
  66232. //-- end properties for backward compatibility for inputs
  66233. function UniversalCamera(name, position, scene) {
  66234. var _this = _super.call(this, name, position, scene) || this;
  66235. _this.inputs.addGamepad();
  66236. return _this;
  66237. }
  66238. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  66239. //-- Begin properties for backward compatibility for inputs
  66240. get: function () {
  66241. var gamepad = this.inputs.attached["gamepad"];
  66242. if (gamepad)
  66243. return gamepad.gamepadAngularSensibility;
  66244. return 0;
  66245. },
  66246. set: function (value) {
  66247. var gamepad = this.inputs.attached["gamepad"];
  66248. if (gamepad)
  66249. gamepad.gamepadAngularSensibility = value;
  66250. },
  66251. enumerable: true,
  66252. configurable: true
  66253. });
  66254. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  66255. get: function () {
  66256. var gamepad = this.inputs.attached["gamepad"];
  66257. if (gamepad)
  66258. return gamepad.gamepadMoveSensibility;
  66259. return 0;
  66260. },
  66261. set: function (value) {
  66262. var gamepad = this.inputs.attached["gamepad"];
  66263. if (gamepad)
  66264. gamepad.gamepadMoveSensibility = value;
  66265. },
  66266. enumerable: true,
  66267. configurable: true
  66268. });
  66269. UniversalCamera.prototype.getClassName = function () {
  66270. return "UniversalCamera";
  66271. };
  66272. return UniversalCamera;
  66273. }(BABYLON.TouchCamera));
  66274. BABYLON.UniversalCamera = UniversalCamera;
  66275. })(BABYLON || (BABYLON = {}));
  66276. //# sourceMappingURL=babylon.universalCamera.js.map
  66277. var BABYLON;
  66278. (function (BABYLON) {
  66279. // We're mainly based on the logic defined into the FreeCamera code
  66280. var GamepadCamera = /** @class */ (function (_super) {
  66281. __extends(GamepadCamera, _super);
  66282. //-- end properties for backward compatibility for inputs
  66283. function GamepadCamera(name, position, scene) {
  66284. return _super.call(this, name, position, scene) || this;
  66285. }
  66286. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  66287. //-- Begin properties for backward compatibility for inputs
  66288. get: function () {
  66289. var gamepad = this.inputs.attached["gamepad"];
  66290. if (gamepad)
  66291. return gamepad.gamepadAngularSensibility;
  66292. return 0;
  66293. },
  66294. set: function (value) {
  66295. var gamepad = this.inputs.attached["gamepad"];
  66296. if (gamepad)
  66297. gamepad.gamepadAngularSensibility = value;
  66298. },
  66299. enumerable: true,
  66300. configurable: true
  66301. });
  66302. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  66303. get: function () {
  66304. var gamepad = this.inputs.attached["gamepad"];
  66305. if (gamepad)
  66306. return gamepad.gamepadMoveSensibility;
  66307. return 0;
  66308. },
  66309. set: function (value) {
  66310. var gamepad = this.inputs.attached["gamepad"];
  66311. if (gamepad)
  66312. gamepad.gamepadMoveSensibility = value;
  66313. },
  66314. enumerable: true,
  66315. configurable: true
  66316. });
  66317. GamepadCamera.prototype.getClassName = function () {
  66318. return "GamepadCamera";
  66319. };
  66320. return GamepadCamera;
  66321. }(BABYLON.UniversalCamera));
  66322. BABYLON.GamepadCamera = GamepadCamera;
  66323. })(BABYLON || (BABYLON = {}));
  66324. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66325. var BABYLON;
  66326. (function (BABYLON) {
  66327. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66328. function PostProcessRenderPipelineManager() {
  66329. this._renderPipelines = {};
  66330. }
  66331. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66332. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66333. };
  66334. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66335. if (unique === void 0) { unique = false; }
  66336. var renderPipeline = this._renderPipelines[renderPipelineName];
  66337. if (!renderPipeline) {
  66338. return;
  66339. }
  66340. renderPipeline._attachCameras(cameras, unique);
  66341. };
  66342. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66343. var renderPipeline = this._renderPipelines[renderPipelineName];
  66344. if (!renderPipeline) {
  66345. return;
  66346. }
  66347. renderPipeline._detachCameras(cameras);
  66348. };
  66349. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66350. var renderPipeline = this._renderPipelines[renderPipelineName];
  66351. if (!renderPipeline) {
  66352. return;
  66353. }
  66354. renderPipeline._enableEffect(renderEffectName, cameras);
  66355. };
  66356. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66357. var renderPipeline = this._renderPipelines[renderPipelineName];
  66358. if (!renderPipeline) {
  66359. return;
  66360. }
  66361. renderPipeline._disableEffect(renderEffectName, cameras);
  66362. };
  66363. PostProcessRenderPipelineManager.prototype.update = function () {
  66364. for (var renderPipelineName in this._renderPipelines) {
  66365. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66366. var pipeline = this._renderPipelines[renderPipelineName];
  66367. if (!pipeline.isSupported) {
  66368. pipeline.dispose();
  66369. delete this._renderPipelines[renderPipelineName];
  66370. }
  66371. else {
  66372. pipeline._update();
  66373. }
  66374. }
  66375. }
  66376. };
  66377. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66378. for (var renderPipelineName in this._renderPipelines) {
  66379. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66380. var pipeline = this._renderPipelines[renderPipelineName];
  66381. pipeline._rebuild();
  66382. }
  66383. }
  66384. };
  66385. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66386. for (var renderPipelineName in this._renderPipelines) {
  66387. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66388. var pipeline = this._renderPipelines[renderPipelineName];
  66389. pipeline.dispose();
  66390. }
  66391. }
  66392. };
  66393. return PostProcessRenderPipelineManager;
  66394. }());
  66395. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66396. })(BABYLON || (BABYLON = {}));
  66397. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66398. var BABYLON;
  66399. (function (BABYLON) {
  66400. /**
  66401. * This represents a set of one or more post processes in Babylon.
  66402. * A post process can be used to apply a shader to a texture after it is rendered.
  66403. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66404. */
  66405. var PostProcessRenderEffect = /** @class */ (function () {
  66406. /**
  66407. * Instantiates a post process render effect.
  66408. * A post process can be used to apply a shader to a texture after it is rendered.
  66409. * @param engine The engine the effect is tied to
  66410. * @param name The name of the effect
  66411. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66412. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66413. */
  66414. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66415. this._name = name;
  66416. this._singleInstance = singleInstance || true;
  66417. this._getPostProcesses = getPostProcesses;
  66418. this._cameras = {};
  66419. this._indicesForCamera = {};
  66420. this._postProcesses = {};
  66421. }
  66422. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66423. /**
  66424. * Checks if all the post processes in the effect are supported.
  66425. */
  66426. get: function () {
  66427. for (var index in this._postProcesses) {
  66428. for (var ppIndex in this._postProcesses[index]) {
  66429. if (!this._postProcesses[index][ppIndex].isSupported) {
  66430. return false;
  66431. }
  66432. }
  66433. }
  66434. return true;
  66435. },
  66436. enumerable: true,
  66437. configurable: true
  66438. });
  66439. /**
  66440. * Updates the current state of the effect
  66441. */
  66442. PostProcessRenderEffect.prototype._update = function () {
  66443. };
  66444. /**
  66445. * Attaches the effect on cameras
  66446. * @param cameras The camera to attach to.
  66447. */
  66448. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66449. var _this = this;
  66450. var cameraKey;
  66451. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66452. if (!cams) {
  66453. return;
  66454. }
  66455. for (var i = 0; i < cams.length; i++) {
  66456. var camera = cams[i];
  66457. var cameraName = camera.name;
  66458. if (this._singleInstance) {
  66459. cameraKey = 0;
  66460. }
  66461. else {
  66462. cameraKey = cameraName;
  66463. }
  66464. if (!this._postProcesses[cameraKey]) {
  66465. var postProcess = this._getPostProcesses();
  66466. if (postProcess) {
  66467. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66468. }
  66469. }
  66470. if (!this._indicesForCamera[cameraName]) {
  66471. this._indicesForCamera[cameraName] = [];
  66472. }
  66473. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66474. var index = camera.attachPostProcess(postProcess);
  66475. _this._indicesForCamera[cameraName].push(index);
  66476. });
  66477. if (!this._cameras[cameraName]) {
  66478. this._cameras[cameraName] = camera;
  66479. }
  66480. }
  66481. };
  66482. /**
  66483. * Detatches the effect on cameras
  66484. * @param cameras The camera to detatch from.
  66485. */
  66486. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  66487. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66488. if (!cams) {
  66489. return;
  66490. }
  66491. for (var i = 0; i < cams.length; i++) {
  66492. var camera = cams[i];
  66493. var cameraName = camera.name;
  66494. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66495. camera.detachPostProcess(postProcess);
  66496. });
  66497. if (this._cameras[cameraName]) {
  66498. //this._indicesForCamera.splice(index, 1);
  66499. this._cameras[cameraName] = null;
  66500. }
  66501. }
  66502. };
  66503. /**
  66504. * Enables the effect on given cameras
  66505. * @param cameras The camera to enable.
  66506. */
  66507. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66508. var _this = this;
  66509. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66510. if (!cams) {
  66511. return;
  66512. }
  66513. for (var i = 0; i < cams.length; i++) {
  66514. var camera = cams[i];
  66515. var cameraName = camera.name;
  66516. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66517. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  66518. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66519. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66520. });
  66521. }
  66522. }
  66523. }
  66524. };
  66525. /**
  66526. * Disables the effect on the given cameras
  66527. * @param cameras The camera to disable.
  66528. */
  66529. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66530. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66531. if (!cams) {
  66532. return;
  66533. }
  66534. for (var i = 0; i < cams.length; i++) {
  66535. var camera = cams[i];
  66536. var cameraName = camera.name;
  66537. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66538. camera.detachPostProcess(postProcess);
  66539. });
  66540. }
  66541. };
  66542. /**
  66543. * Gets a list of the post processes contained in the effect.
  66544. * @param camera The camera to get the post processes on.
  66545. * @returns The list of the post processes in the effect.
  66546. */
  66547. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66548. if (this._singleInstance) {
  66549. return this._postProcesses[0];
  66550. }
  66551. else {
  66552. if (!camera) {
  66553. return null;
  66554. }
  66555. return this._postProcesses[camera.name];
  66556. }
  66557. };
  66558. return PostProcessRenderEffect;
  66559. }());
  66560. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66561. })(BABYLON || (BABYLON = {}));
  66562. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66563. var BABYLON;
  66564. (function (BABYLON) {
  66565. var PostProcessRenderPipeline = /** @class */ (function () {
  66566. function PostProcessRenderPipeline(engine, name) {
  66567. this.engine = engine;
  66568. this._name = name;
  66569. this._renderEffects = {};
  66570. this._renderEffectsForIsolatedPass = new Array();
  66571. this._cameras = [];
  66572. }
  66573. PostProcessRenderPipeline.prototype.getClassName = function () {
  66574. return "PostProcessRenderPipeline";
  66575. };
  66576. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66577. get: function () {
  66578. for (var renderEffectName in this._renderEffects) {
  66579. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66580. if (!this._renderEffects[renderEffectName].isSupported) {
  66581. return false;
  66582. }
  66583. }
  66584. }
  66585. return true;
  66586. },
  66587. enumerable: true,
  66588. configurable: true
  66589. });
  66590. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66591. this._renderEffects[renderEffect._name] = renderEffect;
  66592. };
  66593. // private
  66594. PostProcessRenderPipeline.prototype._rebuild = function () {
  66595. };
  66596. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66597. var renderEffects = this._renderEffects[renderEffectName];
  66598. if (!renderEffects) {
  66599. return;
  66600. }
  66601. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66602. };
  66603. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66604. var renderEffects = this._renderEffects[renderEffectName];
  66605. if (!renderEffects) {
  66606. return;
  66607. }
  66608. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66609. };
  66610. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66611. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66612. if (!cams) {
  66613. return;
  66614. }
  66615. var indicesToDelete = [];
  66616. var i;
  66617. for (i = 0; i < cams.length; i++) {
  66618. var camera = cams[i];
  66619. var cameraName = camera.name;
  66620. if (this._cameras.indexOf(camera) === -1) {
  66621. this._cameras[cameraName] = camera;
  66622. }
  66623. else if (unique) {
  66624. indicesToDelete.push(i);
  66625. }
  66626. }
  66627. for (i = 0; i < indicesToDelete.length; i++) {
  66628. cameras.splice(indicesToDelete[i], 1);
  66629. }
  66630. for (var renderEffectName in this._renderEffects) {
  66631. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66632. this._renderEffects[renderEffectName]._attachCameras(cams);
  66633. }
  66634. }
  66635. };
  66636. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66637. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66638. if (!cams) {
  66639. return;
  66640. }
  66641. for (var renderEffectName in this._renderEffects) {
  66642. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66643. this._renderEffects[renderEffectName]._detachCameras(cams);
  66644. }
  66645. }
  66646. for (var i = 0; i < cams.length; i++) {
  66647. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66648. }
  66649. };
  66650. PostProcessRenderPipeline.prototype._update = function () {
  66651. for (var renderEffectName in this._renderEffects) {
  66652. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66653. this._renderEffects[renderEffectName]._update();
  66654. }
  66655. }
  66656. for (var i = 0; i < this._cameras.length; i++) {
  66657. var cameraName = this._cameras[i].name;
  66658. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66659. this._renderEffectsForIsolatedPass[cameraName]._update();
  66660. }
  66661. }
  66662. };
  66663. PostProcessRenderPipeline.prototype._reset = function () {
  66664. this._renderEffects = {};
  66665. this._renderEffectsForIsolatedPass = new Array();
  66666. };
  66667. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66668. // 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)
  66669. var effectKeys = Object.keys(this._renderEffects);
  66670. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66671. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66672. if (postProcesses) {
  66673. postProcesses[0].samples = 4;
  66674. return true;
  66675. }
  66676. }
  66677. return false;
  66678. };
  66679. PostProcessRenderPipeline.prototype.dispose = function () {
  66680. // Must be implemented by children
  66681. };
  66682. __decorate([
  66683. BABYLON.serialize()
  66684. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66685. return PostProcessRenderPipeline;
  66686. }());
  66687. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66688. })(BABYLON || (BABYLON = {}));
  66689. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66690. var BABYLON;
  66691. (function (BABYLON) {
  66692. /**
  66693. * This represents a depth renderer in Babylon.
  66694. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66695. */
  66696. var DepthRenderer = /** @class */ (function () {
  66697. /**
  66698. * Instantiates a depth renderer
  66699. * @param scene The scene the renderer belongs to
  66700. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66701. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66702. */
  66703. function DepthRenderer(scene, type, camera) {
  66704. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66705. if (camera === void 0) { camera = null; }
  66706. var _this = this;
  66707. this._scene = scene;
  66708. this._camera = camera;
  66709. var engine = scene.getEngine();
  66710. // Render target
  66711. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66712. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66713. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66714. this._depthMap.refreshRate = 1;
  66715. this._depthMap.renderParticles = false;
  66716. this._depthMap.renderList = null;
  66717. // Camera to get depth map from to support multiple concurrent cameras
  66718. this._depthMap.activeCamera = this._camera;
  66719. this._depthMap.ignoreCameraViewport = true;
  66720. this._depthMap.useCameraPostProcesses = false;
  66721. // set default depth value to 1.0 (far away)
  66722. this._depthMap.onClearObservable.add(function (engine) {
  66723. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66724. });
  66725. // Custom render function
  66726. var renderSubMesh = function (subMesh) {
  66727. var mesh = subMesh.getRenderingMesh();
  66728. var scene = _this._scene;
  66729. var engine = scene.getEngine();
  66730. var material = subMesh.getMaterial();
  66731. if (!material) {
  66732. return;
  66733. }
  66734. // Culling and reverse (right handed system)
  66735. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66736. // Managing instances
  66737. var batch = mesh._getInstancesRenderList(subMesh._id);
  66738. if (batch.mustReturn) {
  66739. return;
  66740. }
  66741. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66742. var camera = _this._camera || scene.activeCamera;
  66743. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66744. engine.enableEffect(_this._effect);
  66745. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66746. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66747. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66748. // Alpha test
  66749. if (material && material.needAlphaTesting()) {
  66750. var alphaTexture = material.getAlphaTestTexture();
  66751. if (alphaTexture) {
  66752. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66753. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66754. }
  66755. }
  66756. // Bones
  66757. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66758. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66759. }
  66760. // Draw
  66761. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66762. }
  66763. };
  66764. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66765. var index;
  66766. if (depthOnlySubMeshes.length) {
  66767. engine.setColorWrite(false);
  66768. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66769. renderSubMesh(depthOnlySubMeshes.data[index]);
  66770. }
  66771. engine.setColorWrite(true);
  66772. }
  66773. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66774. renderSubMesh(opaqueSubMeshes.data[index]);
  66775. }
  66776. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66777. renderSubMesh(alphaTestSubMeshes.data[index]);
  66778. }
  66779. };
  66780. }
  66781. /**
  66782. * Creates the depth rendering effect and checks if the effect is ready.
  66783. * @param subMesh The submesh to be used to render the depth map of
  66784. * @param useInstances If multiple world instances should be used
  66785. * @returns if the depth renderer is ready to render the depth map
  66786. */
  66787. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66788. var material = subMesh.getMaterial();
  66789. if (material.disableDepthWrite) {
  66790. return false;
  66791. }
  66792. var defines = [];
  66793. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66794. var mesh = subMesh.getMesh();
  66795. // Alpha test
  66796. if (material && material.needAlphaTesting()) {
  66797. defines.push("#define ALPHATEST");
  66798. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66799. attribs.push(BABYLON.VertexBuffer.UVKind);
  66800. defines.push("#define UV1");
  66801. }
  66802. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66803. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66804. defines.push("#define UV2");
  66805. }
  66806. }
  66807. // Bones
  66808. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66809. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66810. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66811. if (mesh.numBoneInfluencers > 4) {
  66812. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66813. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66814. }
  66815. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66816. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66817. }
  66818. else {
  66819. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66820. }
  66821. // Instances
  66822. if (useInstances) {
  66823. defines.push("#define INSTANCES");
  66824. attribs.push("world0");
  66825. attribs.push("world1");
  66826. attribs.push("world2");
  66827. attribs.push("world3");
  66828. }
  66829. // Get correct effect
  66830. var join = defines.join("\n");
  66831. if (this._cachedDefines !== join) {
  66832. this._cachedDefines = join;
  66833. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66834. }
  66835. return this._effect.isReady();
  66836. };
  66837. /**
  66838. * Gets the texture which the depth map will be written to.
  66839. * @returns The depth map texture
  66840. */
  66841. DepthRenderer.prototype.getDepthMap = function () {
  66842. return this._depthMap;
  66843. };
  66844. /**
  66845. * Disposes of the depth renderer.
  66846. */
  66847. DepthRenderer.prototype.dispose = function () {
  66848. this._depthMap.dispose();
  66849. };
  66850. return DepthRenderer;
  66851. }());
  66852. BABYLON.DepthRenderer = DepthRenderer;
  66853. })(BABYLON || (BABYLON = {}));
  66854. //# sourceMappingURL=babylon.depthRenderer.js.map
  66855. var BABYLON;
  66856. (function (BABYLON) {
  66857. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66858. __extends(SSAORenderingPipeline, _super);
  66859. /**
  66860. * @constructor
  66861. * @param {string} name - The rendering pipeline name
  66862. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66863. * @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 }
  66864. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66865. */
  66866. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66867. var _this = _super.call(this, scene.getEngine(), name) || this;
  66868. // Members
  66869. /**
  66870. * The PassPostProcess id in the pipeline that contains the original scene color
  66871. * @type {string}
  66872. */
  66873. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66874. /**
  66875. * The SSAO PostProcess id in the pipeline
  66876. * @type {string}
  66877. */
  66878. _this.SSAORenderEffect = "SSAORenderEffect";
  66879. /**
  66880. * The horizontal blur PostProcess id in the pipeline
  66881. * @type {string}
  66882. */
  66883. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66884. /**
  66885. * The vertical blur PostProcess id in the pipeline
  66886. * @type {string}
  66887. */
  66888. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66889. /**
  66890. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66891. * @type {string}
  66892. */
  66893. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66894. /**
  66895. * The output strength of the SSAO post-process. Default value is 1.0.
  66896. * @type {number}
  66897. */
  66898. _this.totalStrength = 1.0;
  66899. /**
  66900. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66901. * @type {number}
  66902. */
  66903. _this.radius = 0.0001;
  66904. /**
  66905. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66906. * Must not be equal to fallOff and superior to fallOff.
  66907. * Default value is 0.975
  66908. * @type {number}
  66909. */
  66910. _this.area = 0.0075;
  66911. /**
  66912. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66913. * Must not be equal to area and inferior to area.
  66914. * Default value is 0.0
  66915. * @type {number}
  66916. */
  66917. _this.fallOff = 0.000001;
  66918. /**
  66919. * The base color of the SSAO post-process
  66920. * The final result is "base + ssao" between [0, 1]
  66921. * @type {number}
  66922. */
  66923. _this.base = 0.5;
  66924. _this._firstUpdate = true;
  66925. _this._scene = scene;
  66926. // Set up assets
  66927. _this._createRandomTexture();
  66928. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66929. var ssaoRatio = ratio.ssaoRatio || ratio;
  66930. var combineRatio = ratio.combineRatio || ratio;
  66931. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66932. _this._createSSAOPostProcess(ssaoRatio);
  66933. _this._createBlurPostProcess(ssaoRatio);
  66934. _this._createSSAOCombinePostProcess(combineRatio);
  66935. // Set up pipeline
  66936. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66937. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66938. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66939. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66940. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66941. // Finish
  66942. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66943. if (cameras)
  66944. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66945. return _this;
  66946. }
  66947. // Public Methods
  66948. /**
  66949. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66950. */
  66951. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66952. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66953. for (var i = 0; i < this._scene.cameras.length; i++) {
  66954. var camera = this._scene.cameras[i];
  66955. this._originalColorPostProcess.dispose(camera);
  66956. this._ssaoPostProcess.dispose(camera);
  66957. this._blurHPostProcess.dispose(camera);
  66958. this._blurVPostProcess.dispose(camera);
  66959. this._ssaoCombinePostProcess.dispose(camera);
  66960. }
  66961. this._randomTexture.dispose();
  66962. if (disableDepthRender)
  66963. this._scene.disableDepthRenderer();
  66964. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66965. _super.prototype.dispose.call(this);
  66966. };
  66967. // Private Methods
  66968. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66969. var _this = this;
  66970. var size = 16;
  66971. 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);
  66972. 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);
  66973. this._blurHPostProcess.onActivateObservable.add(function () {
  66974. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66975. _this._blurHPostProcess.kernel = size * dw;
  66976. });
  66977. this._blurVPostProcess.onActivateObservable.add(function () {
  66978. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66979. _this._blurVPostProcess.kernel = size * dw;
  66980. });
  66981. };
  66982. SSAORenderingPipeline.prototype._rebuild = function () {
  66983. this._firstUpdate = true;
  66984. _super.prototype._rebuild.call(this);
  66985. };
  66986. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66987. var _this = this;
  66988. var numSamples = 16;
  66989. var sampleSphere = [
  66990. 0.5381, 0.1856, -0.4319,
  66991. 0.1379, 0.2486, 0.4430,
  66992. 0.3371, 0.5679, -0.0057,
  66993. -0.6999, -0.0451, -0.0019,
  66994. 0.0689, -0.1598, -0.8547,
  66995. 0.0560, 0.0069, -0.1843,
  66996. -0.0146, 0.1402, 0.0762,
  66997. 0.0100, -0.1924, -0.0344,
  66998. -0.3577, -0.5301, -0.4358,
  66999. -0.3169, 0.1063, 0.0158,
  67000. 0.0103, -0.5869, 0.0046,
  67001. -0.0897, -0.4940, 0.3287,
  67002. 0.7119, -0.0154, -0.0918,
  67003. -0.0533, 0.0596, -0.5411,
  67004. 0.0352, -0.0631, 0.5460,
  67005. -0.4776, 0.2847, -0.0271
  67006. ];
  67007. var samplesFactor = 1.0 / numSamples;
  67008. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67009. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67010. "area", "fallOff", "base", "range", "viewport"
  67011. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67012. this._ssaoPostProcess.onApply = function (effect) {
  67013. if (_this._firstUpdate) {
  67014. effect.setArray3("sampleSphere", sampleSphere);
  67015. effect.setFloat("samplesFactor", samplesFactor);
  67016. effect.setFloat("randTextureTiles", 4.0);
  67017. }
  67018. effect.setFloat("totalStrength", _this.totalStrength);
  67019. effect.setFloat("radius", _this.radius);
  67020. effect.setFloat("area", _this.area);
  67021. effect.setFloat("fallOff", _this.fallOff);
  67022. effect.setFloat("base", _this.base);
  67023. effect.setTexture("textureSampler", _this._depthTexture);
  67024. effect.setTexture("randomSampler", _this._randomTexture);
  67025. };
  67026. };
  67027. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67028. var _this = this;
  67029. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67030. this._ssaoCombinePostProcess.onApply = function (effect) {
  67031. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67032. };
  67033. };
  67034. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67035. var size = 512;
  67036. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67037. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67038. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67039. var context = this._randomTexture.getContext();
  67040. var rand = function (min, max) {
  67041. return Math.random() * (max - min) + min;
  67042. };
  67043. var randVector = BABYLON.Vector3.Zero();
  67044. for (var x = 0; x < size; x++) {
  67045. for (var y = 0; y < size; y++) {
  67046. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67047. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67048. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67049. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67050. context.fillRect(x, y, 1, 1);
  67051. }
  67052. }
  67053. this._randomTexture.update(false);
  67054. };
  67055. __decorate([
  67056. BABYLON.serialize()
  67057. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67058. __decorate([
  67059. BABYLON.serialize()
  67060. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67061. __decorate([
  67062. BABYLON.serialize()
  67063. ], SSAORenderingPipeline.prototype, "area", void 0);
  67064. __decorate([
  67065. BABYLON.serialize()
  67066. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67067. __decorate([
  67068. BABYLON.serialize()
  67069. ], SSAORenderingPipeline.prototype, "base", void 0);
  67070. return SSAORenderingPipeline;
  67071. }(BABYLON.PostProcessRenderPipeline));
  67072. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  67073. })(BABYLON || (BABYLON = {}));
  67074. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  67075. var BABYLON;
  67076. (function (BABYLON) {
  67077. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  67078. __extends(SSAO2RenderingPipeline, _super);
  67079. /**
  67080. * @constructor
  67081. * @param {string} name - The rendering pipeline name
  67082. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67083. * @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 }
  67084. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67085. */
  67086. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  67087. var _this = _super.call(this, scene.getEngine(), name) || this;
  67088. // Members
  67089. /**
  67090. * The PassPostProcess id in the pipeline that contains the original scene color
  67091. * @type {string}
  67092. */
  67093. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67094. /**
  67095. * The SSAO PostProcess id in the pipeline
  67096. * @type {string}
  67097. */
  67098. _this.SSAORenderEffect = "SSAORenderEffect";
  67099. /**
  67100. * The horizontal blur PostProcess id in the pipeline
  67101. * @type {string}
  67102. */
  67103. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67104. /**
  67105. * The vertical blur PostProcess id in the pipeline
  67106. * @type {string}
  67107. */
  67108. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67109. /**
  67110. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67111. * @type {string}
  67112. */
  67113. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67114. /**
  67115. * The output strength of the SSAO post-process. Default value is 1.0.
  67116. * @type {number}
  67117. */
  67118. _this.totalStrength = 1.0;
  67119. /**
  67120. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  67121. * @type {number}
  67122. */
  67123. _this.maxZ = 100.0;
  67124. /**
  67125. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  67126. * @type {number}
  67127. */
  67128. _this.minZAspect = 0.2;
  67129. /**
  67130. * Number of samples used for the SSAO calculations. Default value is 8
  67131. * @type {number}
  67132. */
  67133. _this._samples = 8;
  67134. /**
  67135. * Are we using bilateral blur ?
  67136. * @type {boolean}
  67137. */
  67138. _this._expensiveBlur = true;
  67139. /**
  67140. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  67141. * @type {number}
  67142. */
  67143. _this.radius = 2.0;
  67144. /**
  67145. * The base color of the SSAO post-process
  67146. * The final result is "base + ssao" between [0, 1]
  67147. * @type {number}
  67148. */
  67149. _this.base = 0.1;
  67150. _this._firstUpdate = true;
  67151. _this._scene = scene;
  67152. if (!_this.isSupported) {
  67153. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  67154. return _this;
  67155. }
  67156. var ssaoRatio = ratio.ssaoRatio || ratio;
  67157. var blurRatio = ratio.blurRatio || ratio;
  67158. // Set up assets
  67159. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  67160. _this._createRandomTexture();
  67161. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  67162. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  67163. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67164. _this._createSSAOPostProcess(1.0);
  67165. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  67166. _this._createSSAOCombinePostProcess(blurRatio);
  67167. // Set up pipeline
  67168. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67169. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67170. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67171. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67172. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67173. // Finish
  67174. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67175. if (cameras)
  67176. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67177. return _this;
  67178. }
  67179. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  67180. get: function () {
  67181. return this._samples;
  67182. },
  67183. set: function (n) {
  67184. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  67185. this._samples = n;
  67186. this._sampleSphere = this._generateHemisphere();
  67187. this._firstUpdate = true;
  67188. },
  67189. enumerable: true,
  67190. configurable: true
  67191. });
  67192. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  67193. get: function () {
  67194. return this._expensiveBlur;
  67195. },
  67196. set: function (b) {
  67197. 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"]);
  67198. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  67199. this._expensiveBlur = b;
  67200. this._firstUpdate = true;
  67201. },
  67202. enumerable: true,
  67203. configurable: true
  67204. });
  67205. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  67206. /**
  67207. * Support test.
  67208. * @type {boolean}
  67209. */
  67210. get: function () {
  67211. var engine = BABYLON.Engine.LastCreatedEngine;
  67212. if (!engine) {
  67213. return false;
  67214. }
  67215. return engine.getCaps().drawBuffersExtension;
  67216. },
  67217. enumerable: true,
  67218. configurable: true
  67219. });
  67220. // Public Methods
  67221. /**
  67222. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67223. */
  67224. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  67225. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  67226. for (var i = 0; i < this._scene.cameras.length; i++) {
  67227. var camera = this._scene.cameras[i];
  67228. this._originalColorPostProcess.dispose(camera);
  67229. this._ssaoPostProcess.dispose(camera);
  67230. this._blurHPostProcess.dispose(camera);
  67231. this._blurVPostProcess.dispose(camera);
  67232. this._ssaoCombinePostProcess.dispose(camera);
  67233. }
  67234. this._randomTexture.dispose();
  67235. if (disableGeometryBufferRenderer)
  67236. this._scene.disableGeometryBufferRenderer();
  67237. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67238. _super.prototype.dispose.call(this);
  67239. };
  67240. // Private Methods
  67241. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  67242. var _this = this;
  67243. this._samplerOffsets = [];
  67244. var expensive = this.expensiveBlur;
  67245. for (var i = -8; i < 8; i++) {
  67246. this._samplerOffsets.push(i * 2 + 0.5);
  67247. }
  67248. 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");
  67249. this._blurHPostProcess.onApply = function (effect) {
  67250. if (!_this._scene.activeCamera) {
  67251. return;
  67252. }
  67253. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  67254. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67255. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67256. effect.setFloat("radius", _this.radius);
  67257. effect.setTexture("depthSampler", _this._depthTexture);
  67258. if (_this._firstUpdate) {
  67259. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67260. }
  67261. };
  67262. 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");
  67263. this._blurVPostProcess.onApply = function (effect) {
  67264. if (!_this._scene.activeCamera) {
  67265. return;
  67266. }
  67267. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  67268. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67269. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67270. effect.setFloat("radius", _this.radius);
  67271. effect.setTexture("depthSampler", _this._depthTexture);
  67272. if (_this._firstUpdate) {
  67273. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67274. _this._firstUpdate = false;
  67275. }
  67276. };
  67277. };
  67278. SSAO2RenderingPipeline.prototype._rebuild = function () {
  67279. this._firstUpdate = true;
  67280. _super.prototype._rebuild.call(this);
  67281. };
  67282. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  67283. var numSamples = this.samples;
  67284. var result = [];
  67285. var vector, scale;
  67286. var rand = function (min, max) {
  67287. return Math.random() * (max - min) + min;
  67288. };
  67289. var i = 0;
  67290. while (i < numSamples) {
  67291. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  67292. vector.normalize();
  67293. scale = i / numSamples;
  67294. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  67295. vector.scaleInPlace(scale);
  67296. result.push(vector.x, vector.y, vector.z);
  67297. i++;
  67298. }
  67299. return result;
  67300. };
  67301. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67302. var _this = this;
  67303. var numSamples = this.samples;
  67304. this._sampleSphere = this._generateHemisphere();
  67305. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  67306. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67307. "base", "range", "projection", "near", "far", "texelSize",
  67308. "xViewport", "yViewport", "maxZ", "minZAspect"
  67309. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67310. this._ssaoPostProcess.onApply = function (effect) {
  67311. if (_this._firstUpdate) {
  67312. effect.setArray3("sampleSphere", _this._sampleSphere);
  67313. effect.setFloat("randTextureTiles", 4.0);
  67314. }
  67315. if (!_this._scene.activeCamera) {
  67316. return;
  67317. }
  67318. effect.setFloat("samplesFactor", 1 / _this.samples);
  67319. effect.setFloat("totalStrength", _this.totalStrength);
  67320. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67321. effect.setFloat("radius", _this.radius);
  67322. effect.setFloat("maxZ", _this.maxZ);
  67323. effect.setFloat("minZAspect", _this.minZAspect);
  67324. effect.setFloat("base", _this.base);
  67325. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67326. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67327. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67328. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67329. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67330. effect.setTexture("textureSampler", _this._depthTexture);
  67331. effect.setTexture("normalSampler", _this._normalTexture);
  67332. effect.setTexture("randomSampler", _this._randomTexture);
  67333. };
  67334. };
  67335. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67336. var _this = this;
  67337. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67338. this._ssaoCombinePostProcess.onApply = function (effect) {
  67339. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67340. };
  67341. };
  67342. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67343. var size = 512;
  67344. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67345. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67346. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67347. var context = this._randomTexture.getContext();
  67348. var rand = function (min, max) {
  67349. return Math.random() * (max - min) + min;
  67350. };
  67351. var randVector = BABYLON.Vector3.Zero();
  67352. for (var x = 0; x < size; x++) {
  67353. for (var y = 0; y < size; y++) {
  67354. randVector.x = rand(0.0, 1.0);
  67355. randVector.y = rand(0.0, 1.0);
  67356. randVector.z = 0.0;
  67357. randVector.normalize();
  67358. randVector.scaleInPlace(255);
  67359. randVector.x = Math.floor(randVector.x);
  67360. randVector.y = Math.floor(randVector.y);
  67361. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67362. context.fillRect(x, y, 1, 1);
  67363. }
  67364. }
  67365. this._randomTexture.update(false);
  67366. };
  67367. __decorate([
  67368. BABYLON.serialize()
  67369. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67370. __decorate([
  67371. BABYLON.serialize()
  67372. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67373. __decorate([
  67374. BABYLON.serialize()
  67375. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67376. __decorate([
  67377. BABYLON.serialize("samples")
  67378. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67379. __decorate([
  67380. BABYLON.serialize("expensiveBlur")
  67381. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67382. __decorate([
  67383. BABYLON.serialize()
  67384. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67385. __decorate([
  67386. BABYLON.serialize()
  67387. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67388. return SSAO2RenderingPipeline;
  67389. }(BABYLON.PostProcessRenderPipeline));
  67390. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67391. })(BABYLON || (BABYLON = {}));
  67392. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67393. // BABYLON.JS Chromatic Aberration GLSL Shader
  67394. // Author: Olivier Guyot
  67395. // Separates very slightly R, G and B colors on the edges of the screen
  67396. // Inspired by Francois Tarlier & Martins Upitis
  67397. var BABYLON;
  67398. (function (BABYLON) {
  67399. var LensRenderingPipeline = /** @class */ (function (_super) {
  67400. __extends(LensRenderingPipeline, _super);
  67401. /**
  67402. * @constructor
  67403. *
  67404. * Effect parameters are as follow:
  67405. * {
  67406. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67407. * edge_blur: number; // from 0 to x (1 for realism)
  67408. * distortion: number; // from 0 to x (1 for realism)
  67409. * grain_amount: number; // from 0 to 1
  67410. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67411. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67412. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67413. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67414. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67415. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67416. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67417. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67418. * }
  67419. * Note: if an effect parameter is unset, effect is disabled
  67420. *
  67421. * @param {string} name - The rendering pipeline name
  67422. * @param {object} parameters - An object containing all parameters (see above)
  67423. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67424. * @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)
  67425. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67426. */
  67427. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67428. if (ratio === void 0) { ratio = 1.0; }
  67429. var _this = _super.call(this, scene.getEngine(), name) || this;
  67430. // Lens effects can be of the following:
  67431. // - chromatic aberration (slight shift of RGB colors)
  67432. // - blur on the edge of the lens
  67433. // - lens distortion
  67434. // - depth-of-field blur & highlights enhancing
  67435. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67436. // - grain effect (noise or custom texture)
  67437. // Two additional texture samplers are needed:
  67438. // - depth map (for depth-of-field)
  67439. // - grain texture
  67440. /**
  67441. * The chromatic aberration PostProcess id in the pipeline
  67442. * @type {string}
  67443. */
  67444. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67445. /**
  67446. * The highlights enhancing PostProcess id in the pipeline
  67447. * @type {string}
  67448. */
  67449. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67450. /**
  67451. * The depth-of-field PostProcess id in the pipeline
  67452. * @type {string}
  67453. */
  67454. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67455. _this._scene = scene;
  67456. // Fetch texture samplers
  67457. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67458. if (parameters.grain_texture) {
  67459. _this._grainTexture = parameters.grain_texture;
  67460. }
  67461. else {
  67462. _this._createGrainTexture();
  67463. }
  67464. // save parameters
  67465. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67466. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67467. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67468. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67469. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67470. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67471. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67472. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67473. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67474. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67475. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67476. // Create effects
  67477. _this._createChromaticAberrationPostProcess(ratio);
  67478. _this._createHighlightsPostProcess(ratio);
  67479. _this._createDepthOfFieldPostProcess(ratio / 4);
  67480. // Set up pipeline
  67481. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67482. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67483. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67484. if (_this._highlightsGain === -1) {
  67485. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67486. }
  67487. // Finish
  67488. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67489. if (cameras) {
  67490. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67491. }
  67492. return _this;
  67493. }
  67494. // public methods (self explanatory)
  67495. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67496. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67497. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67498. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67499. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67500. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67501. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67502. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67503. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67504. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67505. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67506. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67507. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67508. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67509. };
  67510. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67511. this._highlightsPostProcess.updateEffect();
  67512. };
  67513. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67514. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67515. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67516. this._highlightsGain = amount;
  67517. };
  67518. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67519. if (this._highlightsGain === -1) {
  67520. this._highlightsGain = 1.0;
  67521. }
  67522. this._highlightsThreshold = amount;
  67523. };
  67524. LensRenderingPipeline.prototype.disableHighlights = function () {
  67525. this._highlightsGain = -1;
  67526. };
  67527. /**
  67528. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67529. */
  67530. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67531. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67532. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67533. this._chromaticAberrationPostProcess = null;
  67534. this._highlightsPostProcess = null;
  67535. this._depthOfFieldPostProcess = null;
  67536. this._grainTexture.dispose();
  67537. if (disableDepthRender)
  67538. this._scene.disableDepthRenderer();
  67539. };
  67540. // colors shifting and distortion
  67541. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67542. var _this = this;
  67543. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67544. [], // samplers
  67545. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67546. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67547. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67548. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67549. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67550. effect.setFloat('radialIntensity', 1);
  67551. effect.setFloat2('direction', 17, 17);
  67552. effect.setFloat2('centerPosition', 0.5, 0.5);
  67553. };
  67554. };
  67555. // highlights enhancing
  67556. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67557. var _this = this;
  67558. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67559. [], // samplers
  67560. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67561. this._highlightsPostProcess.onApply = function (effect) {
  67562. effect.setFloat('gain', _this._highlightsGain);
  67563. effect.setFloat('threshold', _this._highlightsThreshold);
  67564. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67565. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67566. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67567. };
  67568. };
  67569. // colors shifting and distortion
  67570. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67571. var _this = this;
  67572. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67573. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67574. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67575. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67576. this._depthOfFieldPostProcess.onApply = function (effect) {
  67577. effect.setTexture("depthSampler", _this._depthTexture);
  67578. effect.setTexture("grainSampler", _this._grainTexture);
  67579. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67580. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67581. effect.setFloat('grain_amount', _this._grainAmount);
  67582. effect.setBool('blur_noise', _this._blurNoise);
  67583. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67584. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67585. effect.setFloat('distortion', _this._distortion);
  67586. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67587. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67588. effect.setFloat('aperture', _this._dofAperture);
  67589. effect.setFloat('darken', _this._dofDarken);
  67590. effect.setFloat('edge_blur', _this._edgeBlur);
  67591. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67592. if (_this._scene.activeCamera) {
  67593. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67594. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67595. }
  67596. };
  67597. };
  67598. // creates a black and white random noise texture, 512x512
  67599. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67600. var size = 512;
  67601. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67602. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67603. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67604. var context = this._grainTexture.getContext();
  67605. var rand = function (min, max) {
  67606. return Math.random() * (max - min) + min;
  67607. };
  67608. var value;
  67609. for (var x = 0; x < size; x++) {
  67610. for (var y = 0; y < size; y++) {
  67611. value = Math.floor(rand(0.42, 0.58) * 255);
  67612. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67613. context.fillRect(x, y, 1, 1);
  67614. }
  67615. }
  67616. this._grainTexture.update(false);
  67617. };
  67618. return LensRenderingPipeline;
  67619. }(BABYLON.PostProcessRenderPipeline));
  67620. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67621. })(BABYLON || (BABYLON = {}));
  67622. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67623. var BABYLON;
  67624. (function (BABYLON) {
  67625. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67626. __extends(StandardRenderingPipeline, _super);
  67627. /**
  67628. * @constructor
  67629. * @param {string} name - The rendering pipeline name
  67630. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67631. * @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)
  67632. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67633. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67634. */
  67635. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67636. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67637. var _this = _super.call(this, scene.getEngine(), name) || this;
  67638. _this.downSampleX4PostProcess = null;
  67639. _this.brightPassPostProcess = null;
  67640. _this.blurHPostProcesses = [];
  67641. _this.blurVPostProcesses = [];
  67642. _this.textureAdderPostProcess = null;
  67643. _this.volumetricLightPostProcess = null;
  67644. _this.volumetricLightSmoothXPostProcess = null;
  67645. _this.volumetricLightSmoothYPostProcess = null;
  67646. _this.volumetricLightMergePostProces = null;
  67647. _this.volumetricLightFinalPostProcess = null;
  67648. _this.luminancePostProcess = null;
  67649. _this.luminanceDownSamplePostProcesses = [];
  67650. _this.hdrPostProcess = null;
  67651. _this.textureAdderFinalPostProcess = null;
  67652. _this.lensFlareFinalPostProcess = null;
  67653. _this.hdrFinalPostProcess = null;
  67654. _this.lensFlarePostProcess = null;
  67655. _this.lensFlareComposePostProcess = null;
  67656. _this.motionBlurPostProcess = null;
  67657. _this.depthOfFieldPostProcess = null;
  67658. // Values
  67659. _this.brightThreshold = 1.0;
  67660. _this.blurWidth = 512.0;
  67661. _this.horizontalBlur = false;
  67662. _this.exposure = 1.0;
  67663. _this.lensTexture = null;
  67664. _this.volumetricLightCoefficient = 0.2;
  67665. _this.volumetricLightPower = 4.0;
  67666. _this.volumetricLightBlurScale = 64.0;
  67667. _this.sourceLight = null;
  67668. _this.hdrMinimumLuminance = 1.0;
  67669. _this.hdrDecreaseRate = 0.5;
  67670. _this.hdrIncreaseRate = 0.5;
  67671. _this.lensColorTexture = null;
  67672. _this.lensFlareStrength = 20.0;
  67673. _this.lensFlareGhostDispersal = 1.4;
  67674. _this.lensFlareHaloWidth = 0.7;
  67675. _this.lensFlareDistortionStrength = 16.0;
  67676. _this.lensStarTexture = null;
  67677. _this.lensFlareDirtTexture = null;
  67678. _this.depthOfFieldDistance = 10.0;
  67679. _this.depthOfFieldBlurWidth = 64.0;
  67680. _this.motionStrength = 1.0;
  67681. // IAnimatable
  67682. _this.animations = [];
  67683. _this._currentDepthOfFieldSource = null;
  67684. _this._hdrCurrentLuminance = 1.0;
  67685. // Getters and setters
  67686. _this._bloomEnabled = true;
  67687. _this._depthOfFieldEnabled = false;
  67688. _this._vlsEnabled = false;
  67689. _this._lensFlareEnabled = false;
  67690. _this._hdrEnabled = false;
  67691. _this._motionBlurEnabled = false;
  67692. _this._motionBlurSamples = 64.0;
  67693. _this._volumetricLightStepsCount = 50.0;
  67694. _this._cameras = cameras || [];
  67695. // Initialize
  67696. _this._scene = scene;
  67697. _this._basePostProcess = originalPostProcess;
  67698. _this._ratio = ratio;
  67699. // Misc
  67700. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67701. // Finish
  67702. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67703. _this._buildPipeline();
  67704. return _this;
  67705. }
  67706. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67707. get: function () {
  67708. return this._bloomEnabled;
  67709. },
  67710. set: function (enabled) {
  67711. if (this._bloomEnabled === enabled) {
  67712. return;
  67713. }
  67714. this._bloomEnabled = enabled;
  67715. this._buildPipeline();
  67716. },
  67717. enumerable: true,
  67718. configurable: true
  67719. });
  67720. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67721. get: function () {
  67722. return this._depthOfFieldEnabled;
  67723. },
  67724. set: function (enabled) {
  67725. if (this._depthOfFieldEnabled === enabled) {
  67726. return;
  67727. }
  67728. this._depthOfFieldEnabled = enabled;
  67729. this._buildPipeline();
  67730. },
  67731. enumerable: true,
  67732. configurable: true
  67733. });
  67734. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67735. get: function () {
  67736. return this._lensFlareEnabled;
  67737. },
  67738. set: function (enabled) {
  67739. if (this._lensFlareEnabled === enabled) {
  67740. return;
  67741. }
  67742. this._lensFlareEnabled = enabled;
  67743. this._buildPipeline();
  67744. },
  67745. enumerable: true,
  67746. configurable: true
  67747. });
  67748. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67749. get: function () {
  67750. return this._hdrEnabled;
  67751. },
  67752. set: function (enabled) {
  67753. if (this._hdrEnabled === enabled) {
  67754. return;
  67755. }
  67756. this._hdrEnabled = enabled;
  67757. this._buildPipeline();
  67758. },
  67759. enumerable: true,
  67760. configurable: true
  67761. });
  67762. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67763. get: function () {
  67764. return this._vlsEnabled;
  67765. },
  67766. set: function (enabled) {
  67767. if (this._vlsEnabled === enabled) {
  67768. return;
  67769. }
  67770. if (enabled) {
  67771. var geometry = this._scene.enableGeometryBufferRenderer();
  67772. if (!geometry) {
  67773. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67774. return;
  67775. }
  67776. }
  67777. this._vlsEnabled = enabled;
  67778. this._buildPipeline();
  67779. },
  67780. enumerable: true,
  67781. configurable: true
  67782. });
  67783. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67784. get: function () {
  67785. return this._motionBlurEnabled;
  67786. },
  67787. set: function (enabled) {
  67788. if (this._motionBlurEnabled === enabled) {
  67789. return;
  67790. }
  67791. this._motionBlurEnabled = enabled;
  67792. this._buildPipeline();
  67793. },
  67794. enumerable: true,
  67795. configurable: true
  67796. });
  67797. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67798. get: function () {
  67799. return this._volumetricLightStepsCount;
  67800. },
  67801. set: function (count) {
  67802. if (this.volumetricLightPostProcess) {
  67803. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67804. }
  67805. this._volumetricLightStepsCount = count;
  67806. },
  67807. enumerable: true,
  67808. configurable: true
  67809. });
  67810. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67811. get: function () {
  67812. return this._motionBlurSamples;
  67813. },
  67814. set: function (samples) {
  67815. if (this.motionBlurPostProcess) {
  67816. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67817. }
  67818. this._motionBlurSamples = samples;
  67819. },
  67820. enumerable: true,
  67821. configurable: true
  67822. });
  67823. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67824. var _this = this;
  67825. var ratio = this._ratio;
  67826. var scene = this._scene;
  67827. this._disposePostProcesses();
  67828. this._reset();
  67829. // Create pass post-process
  67830. if (!this._basePostProcess) {
  67831. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67832. this.originalPostProcess.onApply = function (effect) {
  67833. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67834. };
  67835. }
  67836. else {
  67837. this.originalPostProcess = this._basePostProcess;
  67838. }
  67839. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67840. this._currentDepthOfFieldSource = this.originalPostProcess;
  67841. if (this._vlsEnabled) {
  67842. // Create volumetric light
  67843. this._createVolumetricLightPostProcess(scene, ratio);
  67844. // Create volumetric light final post-process
  67845. 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);
  67846. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67847. }
  67848. if (this._bloomEnabled) {
  67849. // Create down sample X4 post-process
  67850. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67851. // Create bright pass post-process
  67852. this._createBrightPassPostProcess(scene, ratio / 2);
  67853. // Create gaussian blur post-processes (down sampling blurs)
  67854. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67855. // Create texture adder post-process
  67856. this._createTextureAdderPostProcess(scene, ratio);
  67857. // Create depth-of-field source post-process
  67858. 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);
  67859. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67860. }
  67861. if (this._lensFlareEnabled) {
  67862. // Create lens flare post-process
  67863. this._createLensFlarePostProcess(scene, ratio);
  67864. // Create depth-of-field source post-process post lens-flare and disable it now
  67865. 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);
  67866. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67867. }
  67868. if (this._hdrEnabled) {
  67869. // Create luminance
  67870. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67871. // Create HDR
  67872. this._createHdrPostProcess(scene, ratio);
  67873. // Create depth-of-field source post-process post hdr and disable it now
  67874. 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);
  67875. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67876. }
  67877. if (this._depthOfFieldEnabled) {
  67878. // Create gaussian blur used by depth-of-field
  67879. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67880. // Create depth-of-field post-process
  67881. this._createDepthOfFieldPostProcess(scene, ratio);
  67882. }
  67883. if (this._motionBlurEnabled) {
  67884. // Create motion blur post-process
  67885. this._createMotionBlurPostProcess(scene, ratio);
  67886. }
  67887. if (this._cameras !== null) {
  67888. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67889. }
  67890. };
  67891. // Down Sample X4 Post-Processs
  67892. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67893. var _this = this;
  67894. var downSampleX4Offsets = new Array(32);
  67895. 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);
  67896. this.downSampleX4PostProcess.onApply = function (effect) {
  67897. var id = 0;
  67898. var width = _this.downSampleX4PostProcess.width;
  67899. var height = _this.downSampleX4PostProcess.height;
  67900. for (var i = -2; i < 2; i++) {
  67901. for (var j = -2; j < 2; j++) {
  67902. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67903. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67904. id += 2;
  67905. }
  67906. }
  67907. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67908. };
  67909. // Add to pipeline
  67910. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67911. };
  67912. // Brightpass Post-Process
  67913. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67914. var _this = this;
  67915. var brightOffsets = new Array(8);
  67916. 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);
  67917. this.brightPassPostProcess.onApply = function (effect) {
  67918. var sU = (1.0 / _this.brightPassPostProcess.width);
  67919. var sV = (1.0 / _this.brightPassPostProcess.height);
  67920. brightOffsets[0] = -0.5 * sU;
  67921. brightOffsets[1] = 0.5 * sV;
  67922. brightOffsets[2] = 0.5 * sU;
  67923. brightOffsets[3] = 0.5 * sV;
  67924. brightOffsets[4] = -0.5 * sU;
  67925. brightOffsets[5] = -0.5 * sV;
  67926. brightOffsets[6] = 0.5 * sU;
  67927. brightOffsets[7] = -0.5 * sV;
  67928. effect.setArray2("dsOffsets", brightOffsets);
  67929. effect.setFloat("brightThreshold", _this.brightThreshold);
  67930. };
  67931. // Add to pipeline
  67932. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67933. };
  67934. // Create blur H&V post-processes
  67935. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67936. var _this = this;
  67937. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67938. var engine = scene.getEngine();
  67939. 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);
  67940. 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);
  67941. blurX.onActivateObservable.add(function () {
  67942. var dw = blurX.width / engine.getRenderWidth();
  67943. blurX.kernel = _this[blurWidthKey] * dw;
  67944. });
  67945. blurY.onActivateObservable.add(function () {
  67946. var dw = blurY.height / engine.getRenderHeight();
  67947. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67948. });
  67949. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67950. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67951. this.blurHPostProcesses.push(blurX);
  67952. this.blurVPostProcesses.push(blurY);
  67953. };
  67954. // Create texture adder post-process
  67955. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67956. var _this = this;
  67957. 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);
  67958. this.textureAdderPostProcess.onApply = function (effect) {
  67959. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67960. effect.setTexture("lensSampler", _this.lensTexture);
  67961. effect.setFloat("exposure", _this.exposure);
  67962. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67963. };
  67964. // Add to pipeline
  67965. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67966. };
  67967. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67968. var _this = this;
  67969. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67970. geometryRenderer.enablePosition = true;
  67971. var geometry = geometryRenderer.getGBuffer();
  67972. // Base post-process
  67973. 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));
  67974. var depthValues = BABYLON.Vector2.Zero();
  67975. this.volumetricLightPostProcess.onApply = function (effect) {
  67976. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67977. var generator = _this.sourceLight.getShadowGenerator();
  67978. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67979. effect.setTexture("positionSampler", geometry.textures[2]);
  67980. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67981. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67982. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67983. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67984. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67985. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67986. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67987. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67988. effect.setVector2("depthValues", depthValues);
  67989. }
  67990. };
  67991. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67992. // Smooth
  67993. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67994. // Merge
  67995. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67996. this.volumetricLightMergePostProces.onApply = function (effect) {
  67997. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67998. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67999. };
  68000. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68001. };
  68002. // Create luminance
  68003. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68004. var _this = this;
  68005. // Create luminance
  68006. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68007. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68008. var offsets = [];
  68009. this.luminancePostProcess.onApply = function (effect) {
  68010. var sU = (1.0 / _this.luminancePostProcess.width);
  68011. var sV = (1.0 / _this.luminancePostProcess.height);
  68012. offsets[0] = -0.5 * sU;
  68013. offsets[1] = 0.5 * sV;
  68014. offsets[2] = 0.5 * sU;
  68015. offsets[3] = 0.5 * sV;
  68016. offsets[4] = -0.5 * sU;
  68017. offsets[5] = -0.5 * sV;
  68018. offsets[6] = 0.5 * sU;
  68019. offsets[7] = -0.5 * sV;
  68020. effect.setArray2("lumOffsets", offsets);
  68021. };
  68022. // Add to pipeline
  68023. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68024. // Create down sample luminance
  68025. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68026. var size = Math.pow(3, i);
  68027. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68028. if (i === 0) {
  68029. defines += "#define FINAL_DOWN_SAMPLER";
  68030. }
  68031. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68032. this.luminanceDownSamplePostProcesses.push(postProcess);
  68033. }
  68034. // Create callbacks and add effects
  68035. var lastLuminance = this.luminancePostProcess;
  68036. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68037. var downSampleOffsets = new Array(18);
  68038. pp.onApply = function (effect) {
  68039. if (!lastLuminance) {
  68040. return;
  68041. }
  68042. var id = 0;
  68043. for (var x = -1; x < 2; x++) {
  68044. for (var y = -1; y < 2; y++) {
  68045. downSampleOffsets[id] = x / lastLuminance.width;
  68046. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68047. id += 2;
  68048. }
  68049. }
  68050. effect.setArray2("dsOffsets", downSampleOffsets);
  68051. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68052. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68053. lastLuminance = _this.luminancePostProcess;
  68054. }
  68055. else {
  68056. lastLuminance = pp;
  68057. }
  68058. };
  68059. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68060. pp.onAfterRender = function (effect) {
  68061. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68062. 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);
  68063. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68064. };
  68065. }
  68066. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68067. });
  68068. };
  68069. // Create HDR post-process
  68070. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68071. var _this = this;
  68072. 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);
  68073. var outputLiminance = 1;
  68074. var time = 0;
  68075. var lastTime = 0;
  68076. this.hdrPostProcess.onApply = function (effect) {
  68077. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  68078. time += scene.getEngine().getDeltaTime();
  68079. if (outputLiminance < 0) {
  68080. outputLiminance = _this._hdrCurrentLuminance;
  68081. }
  68082. else {
  68083. var dt = (lastTime - time) / 1000.0;
  68084. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  68085. outputLiminance += _this.hdrDecreaseRate * dt;
  68086. }
  68087. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  68088. outputLiminance -= _this.hdrIncreaseRate * dt;
  68089. }
  68090. else {
  68091. outputLiminance = _this._hdrCurrentLuminance;
  68092. }
  68093. }
  68094. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  68095. effect.setFloat("averageLuminance", outputLiminance);
  68096. lastTime = time;
  68097. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  68098. };
  68099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  68100. };
  68101. // Create lens flare post-process
  68102. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  68103. var _this = this;
  68104. 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);
  68105. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  68106. this._createBlurPostProcesses(scene, ratio / 4, 2);
  68107. 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);
  68108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  68109. var resolution = new BABYLON.Vector2(0, 0);
  68110. // Lens flare
  68111. this.lensFlarePostProcess.onApply = function (effect) {
  68112. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  68113. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  68114. effect.setFloat("strength", _this.lensFlareStrength);
  68115. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  68116. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  68117. // Shift
  68118. resolution.x = _this.lensFlarePostProcess.width;
  68119. resolution.y = _this.lensFlarePostProcess.height;
  68120. effect.setVector2("resolution", resolution);
  68121. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  68122. };
  68123. // Compose
  68124. 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);
  68125. 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);
  68126. this.lensFlareComposePostProcess.onApply = function (effect) {
  68127. if (!_this._scene.activeCamera) {
  68128. return;
  68129. }
  68130. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68131. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  68132. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  68133. // Lens start rotation matrix
  68134. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  68135. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  68136. 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));
  68137. camRot *= 4.0;
  68138. 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);
  68139. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  68140. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  68141. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  68142. };
  68143. };
  68144. // Create depth-of-field post-process
  68145. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  68146. var _this = this;
  68147. 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);
  68148. this.depthOfFieldPostProcess.onApply = function (effect) {
  68149. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68150. effect.setTexture("depthSampler", _this._getDepthTexture());
  68151. effect.setFloat("distance", _this.depthOfFieldDistance);
  68152. };
  68153. // Add to pipeline
  68154. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  68155. };
  68156. // Create motion blur post-process
  68157. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  68158. var _this = this;
  68159. 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);
  68160. var motionScale = 0;
  68161. var prevViewProjection = BABYLON.Matrix.Identity();
  68162. var invViewProjection = BABYLON.Matrix.Identity();
  68163. var viewProjection = BABYLON.Matrix.Identity();
  68164. var screenSize = BABYLON.Vector2.Zero();
  68165. this.motionBlurPostProcess.onApply = function (effect) {
  68166. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  68167. viewProjection.invertToRef(invViewProjection);
  68168. effect.setMatrix("inverseViewProjection", invViewProjection);
  68169. effect.setMatrix("prevViewProjection", prevViewProjection);
  68170. prevViewProjection = viewProjection;
  68171. screenSize.x = _this.motionBlurPostProcess.width;
  68172. screenSize.y = _this.motionBlurPostProcess.height;
  68173. effect.setVector2("screenSize", screenSize);
  68174. motionScale = scene.getEngine().getFps() / 60.0;
  68175. effect.setFloat("motionScale", motionScale);
  68176. effect.setFloat("motionStrength", _this.motionStrength);
  68177. effect.setTexture("depthSampler", _this._getDepthTexture());
  68178. };
  68179. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  68180. };
  68181. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  68182. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  68183. var renderer = this._scene.enableGeometryBufferRenderer();
  68184. return renderer.getGBuffer().textures[0];
  68185. }
  68186. return this._scene.enableDepthRenderer().getDepthMap();
  68187. };
  68188. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  68189. for (var i = 0; i < this._cameras.length; i++) {
  68190. var camera = this._cameras[i];
  68191. if (this.originalPostProcess) {
  68192. this.originalPostProcess.dispose(camera);
  68193. }
  68194. if (this.downSampleX4PostProcess) {
  68195. this.downSampleX4PostProcess.dispose(camera);
  68196. }
  68197. if (this.brightPassPostProcess) {
  68198. this.brightPassPostProcess.dispose(camera);
  68199. }
  68200. if (this.textureAdderPostProcess) {
  68201. this.textureAdderPostProcess.dispose(camera);
  68202. }
  68203. if (this.textureAdderFinalPostProcess) {
  68204. this.textureAdderFinalPostProcess.dispose(camera);
  68205. }
  68206. if (this.volumetricLightPostProcess) {
  68207. this.volumetricLightPostProcess.dispose(camera);
  68208. }
  68209. if (this.volumetricLightSmoothXPostProcess) {
  68210. this.volumetricLightSmoothXPostProcess.dispose(camera);
  68211. }
  68212. if (this.volumetricLightSmoothYPostProcess) {
  68213. this.volumetricLightSmoothYPostProcess.dispose(camera);
  68214. }
  68215. if (this.volumetricLightMergePostProces) {
  68216. this.volumetricLightMergePostProces.dispose(camera);
  68217. }
  68218. if (this.volumetricLightFinalPostProcess) {
  68219. this.volumetricLightFinalPostProcess.dispose(camera);
  68220. }
  68221. if (this.lensFlarePostProcess) {
  68222. this.lensFlarePostProcess.dispose(camera);
  68223. }
  68224. if (this.lensFlareComposePostProcess) {
  68225. this.lensFlareComposePostProcess.dispose(camera);
  68226. }
  68227. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  68228. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  68229. }
  68230. if (this.luminancePostProcess) {
  68231. this.luminancePostProcess.dispose(camera);
  68232. }
  68233. if (this.hdrPostProcess) {
  68234. this.hdrPostProcess.dispose(camera);
  68235. }
  68236. if (this.hdrFinalPostProcess) {
  68237. this.hdrFinalPostProcess.dispose(camera);
  68238. }
  68239. if (this.depthOfFieldPostProcess) {
  68240. this.depthOfFieldPostProcess.dispose(camera);
  68241. }
  68242. if (this.motionBlurPostProcess) {
  68243. this.motionBlurPostProcess.dispose(camera);
  68244. }
  68245. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  68246. this.blurHPostProcesses[j].dispose(camera);
  68247. }
  68248. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  68249. this.blurVPostProcesses[j].dispose(camera);
  68250. }
  68251. }
  68252. this.originalPostProcess = null;
  68253. this.downSampleX4PostProcess = null;
  68254. this.brightPassPostProcess = null;
  68255. this.textureAdderPostProcess = null;
  68256. this.textureAdderFinalPostProcess = null;
  68257. this.volumetricLightPostProcess = null;
  68258. this.volumetricLightSmoothXPostProcess = null;
  68259. this.volumetricLightSmoothYPostProcess = null;
  68260. this.volumetricLightMergePostProces = null;
  68261. this.volumetricLightFinalPostProcess = null;
  68262. this.lensFlarePostProcess = null;
  68263. this.lensFlareComposePostProcess = null;
  68264. this.luminancePostProcess = null;
  68265. this.hdrPostProcess = null;
  68266. this.hdrFinalPostProcess = null;
  68267. this.depthOfFieldPostProcess = null;
  68268. this.motionBlurPostProcess = null;
  68269. this.luminanceDownSamplePostProcesses = [];
  68270. this.blurHPostProcesses = [];
  68271. this.blurVPostProcesses = [];
  68272. };
  68273. // Dispose
  68274. StandardRenderingPipeline.prototype.dispose = function () {
  68275. this._disposePostProcesses();
  68276. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68277. _super.prototype.dispose.call(this);
  68278. };
  68279. // Serialize rendering pipeline
  68280. StandardRenderingPipeline.prototype.serialize = function () {
  68281. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68282. serializationObject.customType = "StandardRenderingPipeline";
  68283. return serializationObject;
  68284. };
  68285. /**
  68286. * Static members
  68287. */
  68288. // Parse serialized pipeline
  68289. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68290. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  68291. };
  68292. // Luminance steps
  68293. StandardRenderingPipeline.LuminanceSteps = 6;
  68294. __decorate([
  68295. BABYLON.serialize()
  68296. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  68297. __decorate([
  68298. BABYLON.serialize()
  68299. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  68300. __decorate([
  68301. BABYLON.serialize()
  68302. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  68303. __decorate([
  68304. BABYLON.serialize()
  68305. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  68306. __decorate([
  68307. BABYLON.serializeAsTexture("lensTexture")
  68308. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  68309. __decorate([
  68310. BABYLON.serialize()
  68311. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  68312. __decorate([
  68313. BABYLON.serialize()
  68314. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  68315. __decorate([
  68316. BABYLON.serialize()
  68317. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  68318. __decorate([
  68319. BABYLON.serialize()
  68320. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  68321. __decorate([
  68322. BABYLON.serialize()
  68323. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68324. __decorate([
  68325. BABYLON.serialize()
  68326. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68327. __decorate([
  68328. BABYLON.serializeAsTexture("lensColorTexture")
  68329. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68330. __decorate([
  68331. BABYLON.serialize()
  68332. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68333. __decorate([
  68334. BABYLON.serialize()
  68335. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68336. __decorate([
  68337. BABYLON.serialize()
  68338. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68339. __decorate([
  68340. BABYLON.serialize()
  68341. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68342. __decorate([
  68343. BABYLON.serializeAsTexture("lensStarTexture")
  68344. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68345. __decorate([
  68346. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68347. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68348. __decorate([
  68349. BABYLON.serialize()
  68350. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68351. __decorate([
  68352. BABYLON.serialize()
  68353. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68354. __decorate([
  68355. BABYLON.serialize()
  68356. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68357. __decorate([
  68358. BABYLON.serialize()
  68359. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68360. __decorate([
  68361. BABYLON.serialize()
  68362. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68363. __decorate([
  68364. BABYLON.serialize()
  68365. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68366. __decorate([
  68367. BABYLON.serialize()
  68368. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68369. __decorate([
  68370. BABYLON.serialize()
  68371. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68372. __decorate([
  68373. BABYLON.serialize()
  68374. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68375. __decorate([
  68376. BABYLON.serialize()
  68377. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68378. __decorate([
  68379. BABYLON.serialize()
  68380. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68381. __decorate([
  68382. BABYLON.serialize()
  68383. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68384. return StandardRenderingPipeline;
  68385. }(BABYLON.PostProcessRenderPipeline));
  68386. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68387. })(BABYLON || (BABYLON = {}));
  68388. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68389. var BABYLON;
  68390. (function (BABYLON) {
  68391. var FxaaPostProcess = /** @class */ (function (_super) {
  68392. __extends(FxaaPostProcess, _super);
  68393. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68394. if (camera === void 0) { camera = null; }
  68395. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68396. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68397. _this.onApplyObservable.add(function (effect) {
  68398. var texelSize = _this.texelSize;
  68399. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68400. });
  68401. return _this;
  68402. }
  68403. return FxaaPostProcess;
  68404. }(BABYLON.PostProcess));
  68405. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68406. })(BABYLON || (BABYLON = {}));
  68407. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68408. var BABYLON;
  68409. (function (BABYLON) {
  68410. /**
  68411. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  68412. */
  68413. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  68414. __extends(CircleOfConfusionPostProcess, _super);
  68415. /**
  68416. * Creates a new instance of @see CircleOfConfusionPostProcess
  68417. * @param name The name of the effect.
  68418. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  68419. * @param options The required width/height ratio to downsize to before computing the render pass.
  68420. * @param camera The camera to apply the render pass to.
  68421. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68422. * @param engine The engine which the post process will be applied. (default: current engine)
  68423. * @param reusable If the post process can be reused on the same frame. (default: false)
  68424. * @param textureType Type of textures used when performing the post process. (default: 0)
  68425. */
  68426. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  68427. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68428. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68429. /**
  68430. * 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.
  68431. */
  68432. _this.lensSize = 50;
  68433. /**
  68434. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68435. */
  68436. _this.fStop = 1.4;
  68437. /**
  68438. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68439. */
  68440. _this.focusDistance = 2000;
  68441. /**
  68442. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  68443. */
  68444. _this.focalLength = 50;
  68445. _this.onApplyObservable.add(function (effect) {
  68446. effect.setTexture("depthSampler", depthTexture);
  68447. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  68448. var aperture = _this.lensSize / _this.fStop;
  68449. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  68450. effect.setFloat('focusDistance', _this.focusDistance);
  68451. effect.setFloat('cocPrecalculation', cocPrecalculation);
  68452. effect.setFloat2('cameraMinMaxZ', depthTexture.activeCamera.minZ, depthTexture.activeCamera.maxZ);
  68453. });
  68454. return _this;
  68455. }
  68456. return CircleOfConfusionPostProcess;
  68457. }(BABYLON.PostProcess));
  68458. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  68459. })(BABYLON || (BABYLON = {}));
  68460. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  68461. var BABYLON;
  68462. (function (BABYLON) {
  68463. /**
  68464. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  68465. */
  68466. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  68467. __extends(DepthOfFieldMergePostProcess, _super);
  68468. /**
  68469. * Creates a new instance of @see CircleOfConfusionPostProcess
  68470. * @param name The name of the effect.
  68471. * @param original The non-blurred image to be modified
  68472. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  68473. * @param blurSteps Incrimental bluring post processes.
  68474. * @param options The required width/height ratio to downsize to before computing the render pass.
  68475. * @param camera The camera to apply the render pass to.
  68476. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68477. * @param engine The engine which the post process will be applied. (default: current engine)
  68478. * @param reusable If the post process can be reused on the same frame. (default: false)
  68479. * @param textureType Type of textures used when performing the post process. (default: 0)
  68480. */
  68481. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  68482. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68483. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  68484. _this.onApplyObservable.add(function (effect) {
  68485. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68486. effect.setTextureFromPostProcess("originalSampler", original);
  68487. blurSteps.forEach(function (step, index) {
  68488. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  68489. });
  68490. });
  68491. return _this;
  68492. }
  68493. return DepthOfFieldMergePostProcess;
  68494. }(BABYLON.PostProcess));
  68495. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  68496. })(BABYLON || (BABYLON = {}));
  68497. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  68498. var BABYLON;
  68499. (function (BABYLON) {
  68500. /**
  68501. * Specifies the level of max blur that should be applied when using the depth of field effect
  68502. */
  68503. var DepthOfFieldEffectBlurLevel;
  68504. (function (DepthOfFieldEffectBlurLevel) {
  68505. /**
  68506. * Subtle blur
  68507. */
  68508. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  68509. /**
  68510. * Medium blur
  68511. */
  68512. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  68513. /**
  68514. * Large blur
  68515. */
  68516. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  68517. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  68518. ;
  68519. /**
  68520. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  68521. */
  68522. var DepthOfFieldEffect = /** @class */ (function (_super) {
  68523. __extends(DepthOfFieldEffect, _super);
  68524. /**
  68525. * Creates a new instance of @see DepthOfFieldEffect
  68526. * @param scene The scene the effect belongs to.
  68527. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  68528. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  68529. */
  68530. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  68531. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  68532. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  68533. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  68534. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  68535. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68536. // Capture circle of confusion texture
  68537. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68538. _this._depthOfFieldPass.autoClear = false;
  68539. // 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)
  68540. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  68541. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68542. _this._depthOfFieldBlurY = [];
  68543. _this._depthOfFieldBlurX = [];
  68544. var blurCount = 1;
  68545. var kernelSize = 15;
  68546. switch (blurLevel) {
  68547. case DepthOfFieldEffectBlurLevel.High: {
  68548. blurCount = 3;
  68549. kernelSize = 51;
  68550. break;
  68551. }
  68552. case DepthOfFieldEffectBlurLevel.Medium: {
  68553. blurCount = 2;
  68554. kernelSize = 31;
  68555. break;
  68556. }
  68557. default: {
  68558. kernelSize = 15;
  68559. blurCount = 1;
  68560. break;
  68561. }
  68562. }
  68563. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  68564. for (var i = 0; i < blurCount; i++) {
  68565. 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);
  68566. blurY.autoClear = false;
  68567. 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);
  68568. blurX.autoClear = false;
  68569. _this._depthOfFieldBlurY.push(blurY);
  68570. _this._depthOfFieldBlurX.push(blurX);
  68571. }
  68572. // Merge blurred images with original image based on circleOfConfusion
  68573. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  68574. _this._depthOfFieldMerge.autoClear = false;
  68575. // Set all post processes on the effect.
  68576. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  68577. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  68578. effects.push(_this._depthOfFieldBlurY[i]);
  68579. effects.push(_this._depthOfFieldBlurX[i]);
  68580. }
  68581. effects.push(_this._depthOfFieldMerge);
  68582. return effects;
  68583. }, true) || this;
  68584. return _this;
  68585. }
  68586. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  68587. get: function () {
  68588. return this._circleOfConfusion.focalLength;
  68589. },
  68590. /**
  68591. * The focal the length of the camera used in the effect
  68592. */
  68593. set: function (value) {
  68594. this._circleOfConfusion.focalLength = value;
  68595. },
  68596. enumerable: true,
  68597. configurable: true
  68598. });
  68599. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  68600. get: function () {
  68601. return this._circleOfConfusion.fStop;
  68602. },
  68603. /**
  68604. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68605. */
  68606. set: function (value) {
  68607. this._circleOfConfusion.fStop = value;
  68608. },
  68609. enumerable: true,
  68610. configurable: true
  68611. });
  68612. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  68613. get: function () {
  68614. return this._circleOfConfusion.focusDistance;
  68615. },
  68616. /**
  68617. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68618. */
  68619. set: function (value) {
  68620. this._circleOfConfusion.focusDistance = value;
  68621. },
  68622. enumerable: true,
  68623. configurable: true
  68624. });
  68625. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  68626. get: function () {
  68627. return this._circleOfConfusion.lensSize;
  68628. },
  68629. /**
  68630. * 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.
  68631. */
  68632. set: function (value) {
  68633. this._circleOfConfusion.lensSize = value;
  68634. },
  68635. enumerable: true,
  68636. configurable: true
  68637. });
  68638. /**
  68639. * Disposes each of the internal effects for a given camera.
  68640. * @param camera The camera to dispose the effect on.
  68641. */
  68642. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  68643. this._depthOfFieldPass.dispose(camera);
  68644. this._circleOfConfusion.dispose(camera);
  68645. this._depthOfFieldBlurX.forEach(function (element) {
  68646. element.dispose(camera);
  68647. });
  68648. this._depthOfFieldBlurY.forEach(function (element) {
  68649. element.dispose(camera);
  68650. });
  68651. this._depthOfFieldMerge.dispose(camera);
  68652. };
  68653. return DepthOfFieldEffect;
  68654. }(BABYLON.PostProcessRenderEffect));
  68655. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  68656. })(BABYLON || (BABYLON = {}));
  68657. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  68658. var BABYLON;
  68659. (function (BABYLON) {
  68660. /**
  68661. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  68662. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  68663. */
  68664. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  68665. __extends(DefaultRenderingPipeline, _super);
  68666. /**
  68667. * @constructor
  68668. * @param {string} name - The rendering pipeline name
  68669. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68670. * @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)
  68671. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68672. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  68673. */
  68674. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  68675. if (automaticBuild === void 0) { automaticBuild = true; }
  68676. var _this = _super.call(this, scene.getEngine(), name) || this;
  68677. /**
  68678. * ID of the sharpen post process,
  68679. */
  68680. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  68681. /**
  68682. * ID of the pass post process used for bloom,
  68683. */
  68684. _this.PassPostProcessId = "PassPostProcessEffect";
  68685. /**
  68686. * ID of the highlight post process used for bloom,
  68687. */
  68688. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  68689. /**
  68690. * ID of the blurX post process used for bloom,
  68691. */
  68692. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  68693. /**
  68694. * ID of the blurY post process used for bloom,
  68695. */
  68696. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  68697. /**
  68698. * ID of the copy back post process used for bloom,
  68699. */
  68700. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  68701. /**
  68702. * ID of the image processing post process;
  68703. */
  68704. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  68705. /**
  68706. * ID of the Fast Approximate Anti-Aliasing post process;
  68707. */
  68708. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  68709. /**
  68710. * ID of the final merge post process;
  68711. */
  68712. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  68713. /**
  68714. * ID of the chromatic aberration post process,
  68715. */
  68716. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  68717. /**
  68718. * Animations which can be used to tweak settings over a period of time
  68719. */
  68720. _this.animations = [];
  68721. // Values
  68722. _this._sharpenEnabled = false;
  68723. _this._bloomEnabled = false;
  68724. _this._depthOfFieldEnabled = false;
  68725. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  68726. _this._fxaaEnabled = false;
  68727. _this._msaaEnabled = false;
  68728. _this._imageProcessingEnabled = true;
  68729. _this._bloomScale = 0.6;
  68730. _this._chromaticAberrationEnabled = false;
  68731. _this._buildAllowed = true;
  68732. /**
  68733. * Specifies the size of the bloom blur kernel, relative to the final output size
  68734. */
  68735. _this.bloomKernel = 64;
  68736. /**
  68737. * Specifies the weight of the bloom in the final rendering
  68738. */
  68739. _this._bloomWeight = 0.15;
  68740. _this._cameras = cameras || [];
  68741. _this._buildAllowed = automaticBuild;
  68742. // Initialize
  68743. _this._scene = scene;
  68744. var caps = _this._scene.getEngine().getCaps();
  68745. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  68746. // Misc
  68747. if (_this._hdr) {
  68748. if (caps.textureHalfFloatRender) {
  68749. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68750. }
  68751. else if (caps.textureFloatRender) {
  68752. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68753. }
  68754. }
  68755. else {
  68756. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68757. }
  68758. // Attach
  68759. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68760. _this._buildPipeline();
  68761. return _this;
  68762. }
  68763. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  68764. get: function () {
  68765. return this._sharpenEnabled;
  68766. },
  68767. /**
  68768. * Enable or disable the sharpen process from the pipeline
  68769. */
  68770. set: function (enabled) {
  68771. if (this._sharpenEnabled === enabled) {
  68772. return;
  68773. }
  68774. this._sharpenEnabled = enabled;
  68775. this._buildPipeline();
  68776. },
  68777. enumerable: true,
  68778. configurable: true
  68779. });
  68780. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  68781. get: function () {
  68782. return this._bloomWeight;
  68783. },
  68784. /**
  68785. * The strength of the bloom.
  68786. */
  68787. set: function (value) {
  68788. if (this._bloomWeight === value) {
  68789. return;
  68790. }
  68791. this._bloomWeight = value;
  68792. if (this._hdr && this.copyBack) {
  68793. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  68794. }
  68795. },
  68796. enumerable: true,
  68797. configurable: true
  68798. });
  68799. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  68800. get: function () {
  68801. return this._bloomScale;
  68802. },
  68803. /**
  68804. * The scale of the bloom, lower value will provide better performance.
  68805. */
  68806. set: function (value) {
  68807. if (this._bloomScale === value) {
  68808. return;
  68809. }
  68810. this._bloomScale = value;
  68811. this._buildPipeline();
  68812. },
  68813. enumerable: true,
  68814. configurable: true
  68815. });
  68816. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  68817. get: function () {
  68818. return this._bloomEnabled;
  68819. },
  68820. /**
  68821. * Enable or disable the bloom from the pipeline
  68822. */
  68823. set: function (enabled) {
  68824. if (this._bloomEnabled === enabled) {
  68825. return;
  68826. }
  68827. this._bloomEnabled = enabled;
  68828. this._buildPipeline();
  68829. },
  68830. enumerable: true,
  68831. configurable: true
  68832. });
  68833. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  68834. /**
  68835. * If the depth of field is enabled.
  68836. */
  68837. get: function () {
  68838. return this._depthOfFieldEnabled;
  68839. },
  68840. set: function (enabled) {
  68841. if (this._depthOfFieldEnabled === enabled) {
  68842. return;
  68843. }
  68844. this._depthOfFieldEnabled = enabled;
  68845. this._buildPipeline();
  68846. },
  68847. enumerable: true,
  68848. configurable: true
  68849. });
  68850. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  68851. /**
  68852. * Blur level of the depth of field effect. (Higher blur will effect performance)
  68853. */
  68854. get: function () {
  68855. return this._depthOfFieldBlurLevel;
  68856. },
  68857. set: function (value) {
  68858. if (this._depthOfFieldBlurLevel === value) {
  68859. return;
  68860. }
  68861. this._depthOfFieldBlurLevel = value;
  68862. this._buildPipeline();
  68863. },
  68864. enumerable: true,
  68865. configurable: true
  68866. });
  68867. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  68868. get: function () {
  68869. return this._fxaaEnabled;
  68870. },
  68871. /**
  68872. * If the anti aliasing is enabled.
  68873. */
  68874. set: function (enabled) {
  68875. if (this._fxaaEnabled === enabled) {
  68876. return;
  68877. }
  68878. this._fxaaEnabled = enabled;
  68879. this._buildPipeline();
  68880. },
  68881. enumerable: true,
  68882. configurable: true
  68883. });
  68884. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  68885. get: function () {
  68886. return this._msaaEnabled;
  68887. },
  68888. /**
  68889. * If the multisample anti-aliasing is enabled.
  68890. */
  68891. set: function (enabled) {
  68892. if (this._msaaEnabled === enabled) {
  68893. return;
  68894. }
  68895. this._msaaEnabled = enabled;
  68896. this._buildPipeline();
  68897. },
  68898. enumerable: true,
  68899. configurable: true
  68900. });
  68901. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68902. get: function () {
  68903. return this._imageProcessingEnabled;
  68904. },
  68905. /**
  68906. * If image processing is enabled.
  68907. */
  68908. set: function (enabled) {
  68909. if (this._imageProcessingEnabled === enabled) {
  68910. return;
  68911. }
  68912. this._imageProcessingEnabled = enabled;
  68913. this._buildPipeline();
  68914. },
  68915. enumerable: true,
  68916. configurable: true
  68917. });
  68918. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  68919. get: function () {
  68920. return this._chromaticAberrationEnabled;
  68921. },
  68922. /**
  68923. * Enable or disable the chromaticAberration process from the pipeline
  68924. */
  68925. set: function (enabled) {
  68926. if (this._chromaticAberrationEnabled === enabled) {
  68927. return;
  68928. }
  68929. this._chromaticAberrationEnabled = enabled;
  68930. this._buildPipeline();
  68931. },
  68932. enumerable: true,
  68933. configurable: true
  68934. });
  68935. /**
  68936. * Force the compilation of the entire pipeline.
  68937. */
  68938. DefaultRenderingPipeline.prototype.prepare = function () {
  68939. var previousState = this._buildAllowed;
  68940. this._buildAllowed = true;
  68941. this._buildPipeline();
  68942. this._buildAllowed = previousState;
  68943. };
  68944. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68945. var _this = this;
  68946. if (!this._buildAllowed) {
  68947. return;
  68948. }
  68949. var engine = this._scene.getEngine();
  68950. this._disposePostProcesses();
  68951. this._reset();
  68952. if (this.sharpenEnabled) {
  68953. this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68954. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.SharpenPostProcessId, function () { return _this.sharpen; }, true));
  68955. }
  68956. if (this.depthOfFieldEnabled) {
  68957. // Enable and get current depth map
  68958. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68959. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, depthTexture, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68960. this.addEffect(this.depthOfField);
  68961. }
  68962. if (this.bloomEnabled) {
  68963. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68964. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68965. if (!this._hdr) {
  68966. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68967. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68968. this.highlights.autoClear = false;
  68969. this.highlights.alwaysForcePOT = true;
  68970. }
  68971. 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);
  68972. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68973. this.blurX.alwaysForcePOT = true;
  68974. this.blurX.autoClear = false;
  68975. this.blurX.onActivateObservable.add(function () {
  68976. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68977. _this.blurX.kernel = _this.bloomKernel * dw;
  68978. });
  68979. 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);
  68980. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68981. this.blurY.alwaysForcePOT = true;
  68982. this.blurY.autoClear = false;
  68983. this.blurY.onActivateObservable.add(function () {
  68984. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68985. _this.blurY.kernel = _this.bloomKernel * dh;
  68986. });
  68987. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68988. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68989. this.copyBack.alwaysForcePOT = true;
  68990. if (this._hdr) {
  68991. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68992. var w = this.bloomWeight;
  68993. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68994. }
  68995. else {
  68996. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68997. }
  68998. this.copyBack.autoClear = false;
  68999. }
  69000. if (this._imageProcessingEnabled) {
  69001. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69002. if (this._hdr) {
  69003. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  69004. }
  69005. else {
  69006. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  69007. }
  69008. }
  69009. if (this.fxaaEnabled) {
  69010. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69011. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69012. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69013. }
  69014. else if (this._hdr && this.imageProcessing) {
  69015. this.finalMerge = this.imageProcessing;
  69016. }
  69017. else {
  69018. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69019. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  69020. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69021. }
  69022. if (this.bloomEnabled) {
  69023. if (this._hdr) {
  69024. this.copyBack.shareOutputWith(this.blurX);
  69025. if (this.imageProcessing) {
  69026. this.imageProcessing.shareOutputWith(this.pass);
  69027. this.imageProcessing.autoClear = false;
  69028. }
  69029. else if (this.fxaa) {
  69030. this.fxaa.shareOutputWith(this.pass);
  69031. }
  69032. else {
  69033. this.finalMerge.shareOutputWith(this.pass);
  69034. }
  69035. }
  69036. else {
  69037. if (this.fxaa) {
  69038. this.fxaa.shareOutputWith(this.pass);
  69039. }
  69040. else {
  69041. this.finalMerge.shareOutputWith(this.pass);
  69042. }
  69043. }
  69044. }
  69045. if (this.chromaticAberrationEnabled) {
  69046. this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69047. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true));
  69048. }
  69049. if (this._cameras !== null) {
  69050. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69051. }
  69052. if (this.msaaEnabled) {
  69053. if (!this._enableMSAAOnFirstPostProcess()) {
  69054. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69055. }
  69056. }
  69057. };
  69058. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  69059. for (var i = 0; i < this._cameras.length; i++) {
  69060. var camera = this._cameras[i];
  69061. if (this.sharpen) {
  69062. this.sharpen.dispose(camera);
  69063. }
  69064. if (this.pass) {
  69065. this.pass.dispose(camera);
  69066. }
  69067. if (this.highlights) {
  69068. this.highlights.dispose(camera);
  69069. }
  69070. if (this.blurX) {
  69071. this.blurX.dispose(camera);
  69072. }
  69073. if (this.blurY) {
  69074. this.blurY.dispose(camera);
  69075. }
  69076. if (this.copyBack) {
  69077. this.copyBack.dispose(camera);
  69078. }
  69079. if (this.imageProcessing) {
  69080. this.imageProcessing.dispose(camera);
  69081. }
  69082. if (this.fxaa) {
  69083. this.fxaa.dispose(camera);
  69084. }
  69085. if (this.finalMerge) {
  69086. this.finalMerge.dispose(camera);
  69087. }
  69088. if (this.depthOfField) {
  69089. this.depthOfField.disposeEffects(camera);
  69090. }
  69091. if (this.chromaticAberration) {
  69092. this.chromaticAberration.dispose(camera);
  69093. }
  69094. }
  69095. this.sharpen = null;
  69096. this.pass = null;
  69097. this.highlights = null;
  69098. this.blurX = null;
  69099. this.blurY = null;
  69100. this.copyBack = null;
  69101. this.imageProcessing = null;
  69102. this.fxaa = null;
  69103. this.finalMerge = null;
  69104. this.depthOfField = null;
  69105. this.chromaticAberration = null;
  69106. };
  69107. /**
  69108. * Dispose of the pipeline and stop all post processes
  69109. */
  69110. DefaultRenderingPipeline.prototype.dispose = function () {
  69111. this._disposePostProcesses();
  69112. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69113. _super.prototype.dispose.call(this);
  69114. };
  69115. /**
  69116. * Serialize the rendering pipeline (Used when exporting)
  69117. * @returns the serialized object
  69118. */
  69119. DefaultRenderingPipeline.prototype.serialize = function () {
  69120. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69121. serializationObject.customType = "DefaultRenderingPipeline";
  69122. return serializationObject;
  69123. };
  69124. /**
  69125. * Parse the serialized pipeline
  69126. * @param source Source pipeline.
  69127. * @param scene The scene to load the pipeline to.
  69128. * @param rootUrl The URL of the serialized pipeline.
  69129. * @returns An instantiated pipeline from the serialized object.
  69130. */
  69131. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69132. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  69133. };
  69134. __decorate([
  69135. BABYLON.serialize()
  69136. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  69137. __decorate([
  69138. BABYLON.serialize()
  69139. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  69140. __decorate([
  69141. BABYLON.serialize()
  69142. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  69143. __decorate([
  69144. BABYLON.serialize()
  69145. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  69146. __decorate([
  69147. BABYLON.serialize()
  69148. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  69149. __decorate([
  69150. BABYLON.serialize()
  69151. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  69152. __decorate([
  69153. BABYLON.serialize()
  69154. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  69155. __decorate([
  69156. BABYLON.serialize()
  69157. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  69158. __decorate([
  69159. BABYLON.serialize()
  69160. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  69161. __decorate([
  69162. BABYLON.serialize()
  69163. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  69164. __decorate([
  69165. BABYLON.serialize()
  69166. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  69167. __decorate([
  69168. BABYLON.serialize()
  69169. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  69170. __decorate([
  69171. BABYLON.serialize()
  69172. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  69173. return DefaultRenderingPipeline;
  69174. }(BABYLON.PostProcessRenderPipeline));
  69175. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  69176. })(BABYLON || (BABYLON = {}));
  69177. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  69178. var BABYLON;
  69179. (function (BABYLON) {
  69180. /**
  69181. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  69182. */
  69183. var GeometryBufferRenderer = /** @class */ (function () {
  69184. /**
  69185. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  69186. * @param scene The scene the buffer belongs to
  69187. * @param ratio How big is the buffer related to the main canvas.
  69188. */
  69189. function GeometryBufferRenderer(scene, ratio) {
  69190. if (ratio === void 0) { ratio = 1; }
  69191. this._enablePosition = false;
  69192. this._scene = scene;
  69193. this._ratio = ratio;
  69194. // Render target
  69195. this._createRenderTargets();
  69196. }
  69197. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  69198. /**
  69199. * Set the render list (meshes to be rendered) used in the G buffer.
  69200. */
  69201. set: function (meshes) {
  69202. this._multiRenderTarget.renderList = meshes;
  69203. },
  69204. enumerable: true,
  69205. configurable: true
  69206. });
  69207. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  69208. /**
  69209. * Gets wether or not G buffer are supported by the running hardware.
  69210. * This requires draw buffer supports
  69211. */
  69212. get: function () {
  69213. return this._multiRenderTarget.isSupported;
  69214. },
  69215. enumerable: true,
  69216. configurable: true
  69217. });
  69218. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  69219. /**
  69220. * Gets wether or not position are enabled for the G buffer.
  69221. */
  69222. get: function () {
  69223. return this._enablePosition;
  69224. },
  69225. /**
  69226. * Sets wether or not position are enabled for the G buffer.
  69227. */
  69228. set: function (enable) {
  69229. this._enablePosition = enable;
  69230. this.dispose();
  69231. this._createRenderTargets();
  69232. },
  69233. enumerable: true,
  69234. configurable: true
  69235. });
  69236. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  69237. /**
  69238. * Gets the scene associated with the buffer.
  69239. */
  69240. get: function () {
  69241. return this._scene;
  69242. },
  69243. enumerable: true,
  69244. configurable: true
  69245. });
  69246. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  69247. /**
  69248. * Gets the ratio used by the buffer during its creation.
  69249. * How big is the buffer related to the main canvas.
  69250. */
  69251. get: function () {
  69252. return this._ratio;
  69253. },
  69254. enumerable: true,
  69255. configurable: true
  69256. });
  69257. /**
  69258. * Checks wether everything is ready to render a submesh to the G buffer.
  69259. * @param subMesh the submesh to check readiness for
  69260. * @param useInstances is the mesh drawn using instance or not
  69261. * @returns true if ready otherwise false
  69262. */
  69263. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  69264. var material = subMesh.getMaterial();
  69265. if (material && material.disableDepthWrite) {
  69266. return false;
  69267. }
  69268. var defines = [];
  69269. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  69270. var mesh = subMesh.getMesh();
  69271. // Alpha test
  69272. if (material && material.needAlphaTesting()) {
  69273. defines.push("#define ALPHATEST");
  69274. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69275. attribs.push(BABYLON.VertexBuffer.UVKind);
  69276. defines.push("#define UV1");
  69277. }
  69278. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69279. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69280. defines.push("#define UV2");
  69281. }
  69282. }
  69283. // Buffers
  69284. if (this._enablePosition) {
  69285. defines.push("#define POSITION");
  69286. }
  69287. // Bones
  69288. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69289. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69290. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69291. if (mesh.numBoneInfluencers > 4) {
  69292. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69293. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69294. }
  69295. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69296. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  69297. }
  69298. else {
  69299. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69300. }
  69301. // Instances
  69302. if (useInstances) {
  69303. defines.push("#define INSTANCES");
  69304. attribs.push("world0");
  69305. attribs.push("world1");
  69306. attribs.push("world2");
  69307. attribs.push("world3");
  69308. }
  69309. // Get correct effect
  69310. var join = defines.join("\n");
  69311. if (this._cachedDefines !== join) {
  69312. this._cachedDefines = join;
  69313. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  69314. }
  69315. return this._effect.isReady();
  69316. };
  69317. /**
  69318. * Gets the current underlying G Buffer.
  69319. * @returns the buffer
  69320. */
  69321. GeometryBufferRenderer.prototype.getGBuffer = function () {
  69322. return this._multiRenderTarget;
  69323. };
  69324. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  69325. /**
  69326. * Gets the number of samples used to render the buffer (anti aliasing).
  69327. */
  69328. get: function () {
  69329. return this._multiRenderTarget.samples;
  69330. },
  69331. /**
  69332. * Sets the number of samples used to render the buffer (anti aliasing).
  69333. */
  69334. set: function (value) {
  69335. this._multiRenderTarget.samples = value;
  69336. },
  69337. enumerable: true,
  69338. configurable: true
  69339. });
  69340. /**
  69341. * Disposes the renderer and frees up associated resources.
  69342. */
  69343. GeometryBufferRenderer.prototype.dispose = function () {
  69344. this.getGBuffer().dispose();
  69345. };
  69346. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  69347. var _this = this;
  69348. var engine = this._scene.getEngine();
  69349. var count = this._enablePosition ? 3 : 2;
  69350. 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 });
  69351. if (!this.isSupported) {
  69352. return;
  69353. }
  69354. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69355. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69356. this._multiRenderTarget.refreshRate = 1;
  69357. this._multiRenderTarget.renderParticles = false;
  69358. this._multiRenderTarget.renderList = null;
  69359. // set default depth value to 1.0 (far away)
  69360. this._multiRenderTarget.onClearObservable.add(function (engine) {
  69361. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  69362. });
  69363. // Custom render function
  69364. var renderSubMesh = function (subMesh) {
  69365. var mesh = subMesh.getRenderingMesh();
  69366. var scene = _this._scene;
  69367. var engine = scene.getEngine();
  69368. var material = subMesh.getMaterial();
  69369. if (!material) {
  69370. return;
  69371. }
  69372. // Culling
  69373. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  69374. // Managing instances
  69375. var batch = mesh._getInstancesRenderList(subMesh._id);
  69376. if (batch.mustReturn) {
  69377. return;
  69378. }
  69379. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69380. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  69381. engine.enableEffect(_this._effect);
  69382. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  69383. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  69384. _this._effect.setMatrix("view", scene.getViewMatrix());
  69385. // Alpha test
  69386. if (material && material.needAlphaTesting()) {
  69387. var alphaTexture = material.getAlphaTestTexture();
  69388. if (alphaTexture) {
  69389. _this._effect.setTexture("diffuseSampler", alphaTexture);
  69390. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69391. }
  69392. }
  69393. // Bones
  69394. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69395. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69396. }
  69397. // Draw
  69398. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69399. }
  69400. };
  69401. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69402. var index;
  69403. if (depthOnlySubMeshes.length) {
  69404. engine.setColorWrite(false);
  69405. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69406. renderSubMesh(depthOnlySubMeshes.data[index]);
  69407. }
  69408. engine.setColorWrite(true);
  69409. }
  69410. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69411. renderSubMesh(opaqueSubMeshes.data[index]);
  69412. }
  69413. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69414. renderSubMesh(alphaTestSubMeshes.data[index]);
  69415. }
  69416. };
  69417. };
  69418. return GeometryBufferRenderer;
  69419. }());
  69420. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  69421. })(BABYLON || (BABYLON = {}));
  69422. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  69423. var BABYLON;
  69424. (function (BABYLON) {
  69425. var RefractionPostProcess = /** @class */ (function (_super) {
  69426. __extends(RefractionPostProcess, _super);
  69427. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  69428. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  69429. _this.color = color;
  69430. _this.depth = depth;
  69431. _this.colorLevel = colorLevel;
  69432. _this._ownRefractionTexture = true;
  69433. _this.onActivateObservable.add(function (cam) {
  69434. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  69435. });
  69436. _this.onApplyObservable.add(function (effect) {
  69437. effect.setColor3("baseColor", _this.color);
  69438. effect.setFloat("depth", _this.depth);
  69439. effect.setFloat("colorLevel", _this.colorLevel);
  69440. effect.setTexture("refractionSampler", _this._refTexture);
  69441. });
  69442. return _this;
  69443. }
  69444. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  69445. /**
  69446. * Gets or sets the refraction texture
  69447. * Please note that you are responsible for disposing the texture if you set it manually
  69448. */
  69449. get: function () {
  69450. return this._refTexture;
  69451. },
  69452. set: function (value) {
  69453. if (this._refTexture && this._ownRefractionTexture) {
  69454. this._refTexture.dispose();
  69455. }
  69456. this._refTexture = value;
  69457. this._ownRefractionTexture = false;
  69458. },
  69459. enumerable: true,
  69460. configurable: true
  69461. });
  69462. // Methods
  69463. RefractionPostProcess.prototype.dispose = function (camera) {
  69464. if (this._refTexture && this._ownRefractionTexture) {
  69465. this._refTexture.dispose();
  69466. this._refTexture = null;
  69467. }
  69468. _super.prototype.dispose.call(this, camera);
  69469. };
  69470. return RefractionPostProcess;
  69471. }(BABYLON.PostProcess));
  69472. BABYLON.RefractionPostProcess = RefractionPostProcess;
  69473. })(BABYLON || (BABYLON = {}));
  69474. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  69475. var BABYLON;
  69476. (function (BABYLON) {
  69477. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  69478. __extends(BlackAndWhitePostProcess, _super);
  69479. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  69480. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  69481. _this.degree = 1;
  69482. _this.onApplyObservable.add(function (effect) {
  69483. effect.setFloat("degree", _this.degree);
  69484. });
  69485. return _this;
  69486. }
  69487. return BlackAndWhitePostProcess;
  69488. }(BABYLON.PostProcess));
  69489. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  69490. })(BABYLON || (BABYLON = {}));
  69491. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  69492. var BABYLON;
  69493. (function (BABYLON) {
  69494. /**
  69495. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  69496. * input texture to perform effects such as edge detection or sharpening
  69497. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69498. */
  69499. var ConvolutionPostProcess = /** @class */ (function (_super) {
  69500. __extends(ConvolutionPostProcess, _super);
  69501. /**
  69502. * Creates a new instance of @see ConvolutionPostProcess
  69503. * @param name The name of the effect.
  69504. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  69505. * @param options The required width/height ratio to downsize to before computing the render pass.
  69506. * @param camera The camera to apply the render pass to.
  69507. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69508. * @param engine The engine which the post process will be applied. (default: current engine)
  69509. * @param reusable If the post process can be reused on the same frame. (default: false)
  69510. * @param textureType Type of textures used when performing the post process. (default: 0)
  69511. */
  69512. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  69513. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69514. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69515. _this.kernel = kernel;
  69516. _this.onApply = function (effect) {
  69517. effect.setFloat2("screenSize", _this.width, _this.height);
  69518. effect.setArray("kernel", _this.kernel);
  69519. };
  69520. return _this;
  69521. }
  69522. // Statics
  69523. /**
  69524. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69525. */
  69526. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  69527. /**
  69528. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69529. */
  69530. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  69531. /**
  69532. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69533. */
  69534. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  69535. /**
  69536. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69537. */
  69538. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  69539. /**
  69540. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69541. */
  69542. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  69543. /**
  69544. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69545. */
  69546. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  69547. return ConvolutionPostProcess;
  69548. }(BABYLON.PostProcess));
  69549. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  69550. })(BABYLON || (BABYLON = {}));
  69551. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  69552. var BABYLON;
  69553. (function (BABYLON) {
  69554. /**
  69555. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69556. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69557. */
  69558. var SharpenPostProcess = /** @class */ (function (_super) {
  69559. __extends(SharpenPostProcess, _super);
  69560. /**
  69561. * Creates a new instance of @see ConvolutionPostProcess
  69562. * @param name The name of the effect.
  69563. * @param options The required width/height ratio to downsize to before computing the render pass.
  69564. * @param camera The camera to apply the render pass to.
  69565. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69566. * @param engine The engine which the post process will be applied. (default: current engine)
  69567. * @param reusable If the post process can be reused on the same frame. (default: false)
  69568. * @param textureType Type of textures used when performing the post process. (default: 0)
  69569. */
  69570. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69571. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69572. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69573. /**
  69574. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69575. */
  69576. _this.colorAmount = 1.0;
  69577. /**
  69578. * How much sharpness should be applied (default: 0.3)
  69579. */
  69580. _this.edgeAmount = 0.3;
  69581. _this.onApply = function (effect) {
  69582. effect.setFloat2("screenSize", _this.width, _this.height);
  69583. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69584. };
  69585. return _this;
  69586. }
  69587. return SharpenPostProcess;
  69588. }(BABYLON.PostProcess));
  69589. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69590. })(BABYLON || (BABYLON = {}));
  69591. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69592. var BABYLON;
  69593. (function (BABYLON) {
  69594. /**
  69595. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69596. */
  69597. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69598. __extends(ChromaticAberrationPostProcess, _super);
  69599. /**
  69600. * Creates a new instance of @see ChromaticAberrationPostProcess
  69601. * @param name The name of the effect.
  69602. * @param screenWidth The width of the screen to apply the effect on.
  69603. * @param screenHeight The height of the screen to apply the effect on.
  69604. * @param options The required width/height ratio to downsize to before computing the render pass.
  69605. * @param camera The camera to apply the render pass to.
  69606. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69607. * @param engine The engine which the post process will be applied. (default: current engine)
  69608. * @param reusable If the post process can be reused on the same frame. (default: false)
  69609. * @param textureType Type of textures used when performing the post process. (default: 0)
  69610. */
  69611. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType) {
  69612. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69613. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69614. /**
  69615. * The amount of seperation of rgb channels (default: 0)
  69616. */
  69617. _this.aberrationAmount = 0;
  69618. /**
  69619. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69620. */
  69621. _this.radialIntensity = 0;
  69622. /**
  69623. * 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))
  69624. */
  69625. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69626. /**
  69627. * 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))
  69628. */
  69629. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69630. _this.onApplyObservable.add(function (effect) {
  69631. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69632. effect.setFloat('screen_width', screenWidth);
  69633. effect.setFloat('screen_height', screenHeight);
  69634. effect.setFloat('radialIntensity', _this.radialIntensity);
  69635. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69636. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69637. });
  69638. return _this;
  69639. }
  69640. return ChromaticAberrationPostProcess;
  69641. }(BABYLON.PostProcess));
  69642. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69643. })(BABYLON || (BABYLON = {}));
  69644. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69645. var BABYLON;
  69646. (function (BABYLON) {
  69647. var FilterPostProcess = /** @class */ (function (_super) {
  69648. __extends(FilterPostProcess, _super);
  69649. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  69650. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  69651. _this.kernelMatrix = kernelMatrix;
  69652. _this.onApply = function (effect) {
  69653. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  69654. };
  69655. return _this;
  69656. }
  69657. return FilterPostProcess;
  69658. }(BABYLON.PostProcess));
  69659. BABYLON.FilterPostProcess = FilterPostProcess;
  69660. })(BABYLON || (BABYLON = {}));
  69661. //# sourceMappingURL=babylon.filterPostProcess.js.map
  69662. var BABYLON;
  69663. (function (BABYLON) {
  69664. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  69665. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  69666. __extends(VolumetricLightScatteringPostProcess, _super);
  69667. /**
  69668. * @constructor
  69669. * @param {string} name - The post-process name
  69670. * @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)
  69671. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  69672. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  69673. * @param {number} samples - The post-process quality, default 100
  69674. * @param {number} samplingMode - The post-process filtering mode
  69675. * @param {BABYLON.Engine} engine - The babylon engine
  69676. * @param {boolean} reusable - If the post-process is reusable
  69677. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  69678. */
  69679. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  69680. if (samples === void 0) { samples = 100; }
  69681. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69682. 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;
  69683. _this._screenCoordinates = BABYLON.Vector2.Zero();
  69684. /**
  69685. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  69686. * @type {Vector3}
  69687. */
  69688. _this.customMeshPosition = BABYLON.Vector3.Zero();
  69689. /**
  69690. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  69691. * @type {boolean}
  69692. */
  69693. _this.useCustomMeshPosition = false;
  69694. /**
  69695. * If the post-process should inverse the light scattering direction
  69696. * @type {boolean}
  69697. */
  69698. _this.invert = true;
  69699. /**
  69700. * Array containing the excluded meshes not rendered in the internal pass
  69701. */
  69702. _this.excludedMeshes = new Array();
  69703. /**
  69704. * Controls the overall intensity of the post-process
  69705. * @type {number}
  69706. */
  69707. _this.exposure = 0.3;
  69708. /**
  69709. * Dissipates each sample's contribution in range [0, 1]
  69710. * @type {number}
  69711. */
  69712. _this.decay = 0.96815;
  69713. /**
  69714. * Controls the overall intensity of each sample
  69715. * @type {number}
  69716. */
  69717. _this.weight = 0.58767;
  69718. /**
  69719. * Controls the density of each sample
  69720. * @type {number}
  69721. */
  69722. _this.density = 0.926;
  69723. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  69724. engine = scene.getEngine();
  69725. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  69726. // Configure mesh
  69727. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  69728. // Configure
  69729. _this._createPass(scene, ratio.passRatio || ratio);
  69730. _this.onActivate = function (camera) {
  69731. if (!_this.isSupported) {
  69732. _this.dispose(camera);
  69733. }
  69734. _this.onActivate = null;
  69735. };
  69736. _this.onApplyObservable.add(function (effect) {
  69737. _this._updateMeshScreenCoordinates(scene);
  69738. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  69739. effect.setFloat("exposure", _this.exposure);
  69740. effect.setFloat("decay", _this.decay);
  69741. effect.setFloat("weight", _this.weight);
  69742. effect.setFloat("density", _this.density);
  69743. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  69744. });
  69745. return _this;
  69746. }
  69747. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  69748. get: function () {
  69749. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69750. return false;
  69751. },
  69752. set: function (useDiffuseColor) {
  69753. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69754. },
  69755. enumerable: true,
  69756. configurable: true
  69757. });
  69758. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  69759. return "VolumetricLightScatteringPostProcess";
  69760. };
  69761. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  69762. var mesh = subMesh.getMesh();
  69763. // Render this.mesh as default
  69764. if (mesh === this.mesh && mesh.material) {
  69765. return mesh.material.isReady(mesh);
  69766. }
  69767. var defines = [];
  69768. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69769. var material = subMesh.getMaterial();
  69770. // Alpha test
  69771. if (material) {
  69772. if (material.needAlphaTesting()) {
  69773. defines.push("#define ALPHATEST");
  69774. }
  69775. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69776. attribs.push(BABYLON.VertexBuffer.UVKind);
  69777. defines.push("#define UV1");
  69778. }
  69779. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69780. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69781. defines.push("#define UV2");
  69782. }
  69783. }
  69784. // Bones
  69785. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69786. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69787. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69788. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69789. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  69790. }
  69791. else {
  69792. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69793. }
  69794. // Instances
  69795. if (useInstances) {
  69796. defines.push("#define INSTANCES");
  69797. attribs.push("world0");
  69798. attribs.push("world1");
  69799. attribs.push("world2");
  69800. attribs.push("world3");
  69801. }
  69802. // Get correct effect
  69803. var join = defines.join("\n");
  69804. if (this._cachedDefines !== join) {
  69805. this._cachedDefines = join;
  69806. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  69807. }
  69808. return this._volumetricLightScatteringPass.isReady();
  69809. };
  69810. /**
  69811. * Sets the new light position for light scattering effect
  69812. * @param {BABYLON.Vector3} The new custom light position
  69813. */
  69814. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  69815. this.customMeshPosition = position;
  69816. };
  69817. /**
  69818. * Returns the light position for light scattering effect
  69819. * @return {BABYLON.Vector3} The custom light position
  69820. */
  69821. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  69822. return this.customMeshPosition;
  69823. };
  69824. /**
  69825. * Disposes the internal assets and detaches the post-process from the camera
  69826. */
  69827. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  69828. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  69829. if (rttIndex !== -1) {
  69830. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  69831. }
  69832. this._volumetricLightScatteringRTT.dispose();
  69833. _super.prototype.dispose.call(this, camera);
  69834. };
  69835. /**
  69836. * Returns the render target texture used by the post-process
  69837. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  69838. */
  69839. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  69840. return this._volumetricLightScatteringRTT;
  69841. };
  69842. // Private methods
  69843. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  69844. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  69845. return true;
  69846. }
  69847. return false;
  69848. };
  69849. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  69850. var _this = this;
  69851. var engine = scene.getEngine();
  69852. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69853. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69854. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69855. this._volumetricLightScatteringRTT.renderList = null;
  69856. this._volumetricLightScatteringRTT.renderParticles = false;
  69857. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  69858. var camera = this.getCamera();
  69859. if (camera) {
  69860. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69861. }
  69862. else {
  69863. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69864. }
  69865. // Custom render function for submeshes
  69866. var renderSubMesh = function (subMesh) {
  69867. var mesh = subMesh.getRenderingMesh();
  69868. if (_this._meshExcluded(mesh)) {
  69869. return;
  69870. }
  69871. var material = subMesh.getMaterial();
  69872. if (!material) {
  69873. return;
  69874. }
  69875. var scene = mesh.getScene();
  69876. var engine = scene.getEngine();
  69877. // Culling
  69878. engine.setState(material.backFaceCulling);
  69879. // Managing instances
  69880. var batch = mesh._getInstancesRenderList(subMesh._id);
  69881. if (batch.mustReturn) {
  69882. return;
  69883. }
  69884. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69885. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  69886. var effect = _this._volumetricLightScatteringPass;
  69887. if (mesh === _this.mesh) {
  69888. if (subMesh.effect) {
  69889. effect = subMesh.effect;
  69890. }
  69891. else {
  69892. effect = material.getEffect();
  69893. }
  69894. }
  69895. engine.enableEffect(effect);
  69896. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  69897. if (mesh === _this.mesh) {
  69898. material.bind(mesh.getWorldMatrix(), mesh);
  69899. }
  69900. else {
  69901. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  69902. // Alpha test
  69903. if (material && material.needAlphaTesting()) {
  69904. var alphaTexture = material.getAlphaTestTexture();
  69905. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  69906. if (alphaTexture) {
  69907. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69908. }
  69909. }
  69910. // Bones
  69911. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69912. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69913. }
  69914. }
  69915. // Draw
  69916. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  69917. }
  69918. };
  69919. // Render target texture callbacks
  69920. var savedSceneClearColor;
  69921. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  69922. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  69923. savedSceneClearColor = scene.clearColor;
  69924. scene.clearColor = sceneClearColor;
  69925. });
  69926. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  69927. scene.clearColor = savedSceneClearColor;
  69928. });
  69929. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69930. var engine = scene.getEngine();
  69931. var index;
  69932. if (depthOnlySubMeshes.length) {
  69933. engine.setColorWrite(false);
  69934. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69935. renderSubMesh(depthOnlySubMeshes.data[index]);
  69936. }
  69937. engine.setColorWrite(true);
  69938. }
  69939. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69940. renderSubMesh(opaqueSubMeshes.data[index]);
  69941. }
  69942. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69943. renderSubMesh(alphaTestSubMeshes.data[index]);
  69944. }
  69945. if (transparentSubMeshes.length) {
  69946. // Sort sub meshes
  69947. for (index = 0; index < transparentSubMeshes.length; index++) {
  69948. var submesh = transparentSubMeshes.data[index];
  69949. var boundingInfo = submesh.getBoundingInfo();
  69950. if (boundingInfo && scene.activeCamera) {
  69951. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  69952. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  69953. }
  69954. }
  69955. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  69956. sortedArray.sort(function (a, b) {
  69957. // Alpha index first
  69958. if (a._alphaIndex > b._alphaIndex) {
  69959. return 1;
  69960. }
  69961. if (a._alphaIndex < b._alphaIndex) {
  69962. return -1;
  69963. }
  69964. // Then distance to camera
  69965. if (a._distanceToCamera < b._distanceToCamera) {
  69966. return 1;
  69967. }
  69968. if (a._distanceToCamera > b._distanceToCamera) {
  69969. return -1;
  69970. }
  69971. return 0;
  69972. });
  69973. // Render sub meshes
  69974. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  69975. for (index = 0; index < sortedArray.length; index++) {
  69976. renderSubMesh(sortedArray[index]);
  69977. }
  69978. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69979. }
  69980. };
  69981. };
  69982. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  69983. var transform = scene.getTransformMatrix();
  69984. var meshPosition;
  69985. if (this.useCustomMeshPosition) {
  69986. meshPosition = this.customMeshPosition;
  69987. }
  69988. else if (this.attachedNode) {
  69989. meshPosition = this.attachedNode.position;
  69990. }
  69991. else {
  69992. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  69993. }
  69994. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  69995. this._screenCoordinates.x = pos.x / this._viewPort.width;
  69996. this._screenCoordinates.y = pos.y / this._viewPort.height;
  69997. if (this.invert)
  69998. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  69999. };
  70000. // Static methods
  70001. /**
  70002. * Creates a default mesh for the Volumeric Light Scattering post-process
  70003. * @param {string} The mesh name
  70004. * @param {BABYLON.Scene} The scene where to create the mesh
  70005. * @return {BABYLON.Mesh} the default mesh
  70006. */
  70007. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  70008. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  70009. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  70010. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  70011. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  70012. mesh.material = material;
  70013. return mesh;
  70014. };
  70015. __decorate([
  70016. BABYLON.serializeAsVector3()
  70017. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  70018. __decorate([
  70019. BABYLON.serialize()
  70020. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  70021. __decorate([
  70022. BABYLON.serialize()
  70023. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  70024. __decorate([
  70025. BABYLON.serializeAsMeshReference()
  70026. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  70027. __decorate([
  70028. BABYLON.serialize()
  70029. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  70030. __decorate([
  70031. BABYLON.serialize()
  70032. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  70033. __decorate([
  70034. BABYLON.serialize()
  70035. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  70036. __decorate([
  70037. BABYLON.serialize()
  70038. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  70039. __decorate([
  70040. BABYLON.serialize()
  70041. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  70042. return VolumetricLightScatteringPostProcess;
  70043. }(BABYLON.PostProcess));
  70044. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  70045. })(BABYLON || (BABYLON = {}));
  70046. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  70047. //
  70048. // This post-process allows the modification of rendered colors by using
  70049. // a 'look-up table' (LUT). This effect is also called Color Grading.
  70050. //
  70051. // The object needs to be provided an url to a texture containing the color
  70052. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  70053. // Use an image editing software to tweak the LUT to match your needs.
  70054. //
  70055. // For an example of a color LUT, see here:
  70056. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  70057. // For explanations on color grading, see here:
  70058. // http://udn.epicgames.com/Three/ColorGrading.html
  70059. //
  70060. var BABYLON;
  70061. (function (BABYLON) {
  70062. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  70063. __extends(ColorCorrectionPostProcess, _super);
  70064. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  70065. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  70066. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70067. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  70068. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70069. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70070. _this.onApply = function (effect) {
  70071. effect.setTexture("colorTable", _this._colorTableTexture);
  70072. };
  70073. return _this;
  70074. }
  70075. return ColorCorrectionPostProcess;
  70076. }(BABYLON.PostProcess));
  70077. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  70078. })(BABYLON || (BABYLON = {}));
  70079. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  70080. var BABYLON;
  70081. (function (BABYLON) {
  70082. var TonemappingOperator;
  70083. (function (TonemappingOperator) {
  70084. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  70085. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  70086. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  70087. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  70088. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  70089. ;
  70090. var TonemapPostProcess = /** @class */ (function (_super) {
  70091. __extends(TonemapPostProcess, _super);
  70092. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  70093. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70094. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70095. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  70096. _this._operator = _operator;
  70097. _this.exposureAdjustment = exposureAdjustment;
  70098. var defines = "#define ";
  70099. if (_this._operator === TonemappingOperator.Hable)
  70100. defines += "HABLE_TONEMAPPING";
  70101. else if (_this._operator === TonemappingOperator.Reinhard)
  70102. defines += "REINHARD_TONEMAPPING";
  70103. else if (_this._operator === TonemappingOperator.HejiDawson)
  70104. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  70105. else if (_this._operator === TonemappingOperator.Photographic)
  70106. defines += "PHOTOGRAPHIC_TONEMAPPING";
  70107. //sadly a second call to create the effect.
  70108. _this.updateEffect(defines);
  70109. _this.onApply = function (effect) {
  70110. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  70111. };
  70112. return _this;
  70113. }
  70114. return TonemapPostProcess;
  70115. }(BABYLON.PostProcess));
  70116. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70117. })(BABYLON || (BABYLON = {}));
  70118. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70119. var BABYLON;
  70120. (function (BABYLON) {
  70121. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70122. __extends(DisplayPassPostProcess, _super);
  70123. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70124. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70125. }
  70126. return DisplayPassPostProcess;
  70127. }(BABYLON.PostProcess));
  70128. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70129. })(BABYLON || (BABYLON = {}));
  70130. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70131. var BABYLON;
  70132. (function (BABYLON) {
  70133. var HighlightsPostProcess = /** @class */ (function (_super) {
  70134. __extends(HighlightsPostProcess, _super);
  70135. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70136. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70137. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70138. }
  70139. return HighlightsPostProcess;
  70140. }(BABYLON.PostProcess));
  70141. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70142. })(BABYLON || (BABYLON = {}));
  70143. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70144. var BABYLON;
  70145. (function (BABYLON) {
  70146. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70147. __extends(ImageProcessingPostProcess, _super);
  70148. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70149. if (camera === void 0) { camera = null; }
  70150. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70151. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70152. _this._fromLinearSpace = true;
  70153. /**
  70154. * Defines cache preventing GC.
  70155. */
  70156. _this._defines = {
  70157. IMAGEPROCESSING: false,
  70158. VIGNETTE: false,
  70159. VIGNETTEBLENDMODEMULTIPLY: false,
  70160. VIGNETTEBLENDMODEOPAQUE: false,
  70161. TONEMAPPING: false,
  70162. CONTRAST: false,
  70163. COLORCURVES: false,
  70164. COLORGRADING: false,
  70165. COLORGRADING3D: false,
  70166. FROMLINEARSPACE: false,
  70167. SAMPLER3DGREENDEPTH: false,
  70168. SAMPLER3DBGRMAP: false,
  70169. IMAGEPROCESSINGPOSTPROCESS: false,
  70170. EXPOSURE: false,
  70171. GRAIN: false,
  70172. };
  70173. // Setup the configuration as forced by the constructor. This would then not force the
  70174. // scene materials output in linear space and let untouched the default forward pass.
  70175. if (imageProcessingConfiguration) {
  70176. imageProcessingConfiguration.applyByPostProcess = true;
  70177. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  70178. // This will cause the shader to be compiled
  70179. _this.fromLinearSpace = false;
  70180. }
  70181. else {
  70182. _this._attachImageProcessingConfiguration(null, true);
  70183. _this.imageProcessingConfiguration.applyByPostProcess = true;
  70184. }
  70185. _this.onApply = function (effect) {
  70186. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  70187. };
  70188. return _this;
  70189. }
  70190. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  70191. /**
  70192. * Gets the image processing configuration used either in this material.
  70193. */
  70194. get: function () {
  70195. return this._imageProcessingConfiguration;
  70196. },
  70197. /**
  70198. * Sets the Default image processing configuration used either in the this material.
  70199. *
  70200. * If sets to null, the scene one is in use.
  70201. */
  70202. set: function (value) {
  70203. this._attachImageProcessingConfiguration(value);
  70204. },
  70205. enumerable: true,
  70206. configurable: true
  70207. });
  70208. /**
  70209. * Attaches a new image processing configuration to the PBR Material.
  70210. * @param configuration
  70211. */
  70212. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  70213. var _this = this;
  70214. if (doNotBuild === void 0) { doNotBuild = false; }
  70215. if (configuration === this._imageProcessingConfiguration) {
  70216. return;
  70217. }
  70218. // Detaches observer.
  70219. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70220. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70221. }
  70222. // Pick the scene configuration if needed.
  70223. if (!configuration) {
  70224. var scene = null;
  70225. var engine = this.getEngine();
  70226. var camera = this.getCamera();
  70227. if (camera) {
  70228. scene = camera.getScene();
  70229. }
  70230. else if (engine && engine.scenes) {
  70231. var scenes = engine.scenes;
  70232. scene = scenes[scenes.length - 1];
  70233. }
  70234. else {
  70235. scene = BABYLON.Engine.LastCreatedScene;
  70236. }
  70237. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  70238. }
  70239. else {
  70240. this._imageProcessingConfiguration = configuration;
  70241. }
  70242. // Attaches observer.
  70243. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  70244. _this._updateParameters();
  70245. });
  70246. // Ensure the effect will be rebuilt.
  70247. if (!doNotBuild) {
  70248. this._updateParameters();
  70249. }
  70250. };
  70251. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  70252. /**
  70253. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70254. */
  70255. get: function () {
  70256. return this.imageProcessingConfiguration.colorCurves;
  70257. },
  70258. /**
  70259. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70260. */
  70261. set: function (value) {
  70262. this.imageProcessingConfiguration.colorCurves = value;
  70263. },
  70264. enumerable: true,
  70265. configurable: true
  70266. });
  70267. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  70268. /**
  70269. * Gets wether the color curves effect is enabled.
  70270. */
  70271. get: function () {
  70272. return this.imageProcessingConfiguration.colorCurvesEnabled;
  70273. },
  70274. /**
  70275. * Sets wether the color curves effect is enabled.
  70276. */
  70277. set: function (value) {
  70278. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  70279. },
  70280. enumerable: true,
  70281. configurable: true
  70282. });
  70283. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  70284. /**
  70285. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70286. */
  70287. get: function () {
  70288. return this.imageProcessingConfiguration.colorGradingTexture;
  70289. },
  70290. /**
  70291. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70292. */
  70293. set: function (value) {
  70294. this.imageProcessingConfiguration.colorGradingTexture = value;
  70295. },
  70296. enumerable: true,
  70297. configurable: true
  70298. });
  70299. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  70300. /**
  70301. * Gets wether the color grading effect is enabled.
  70302. */
  70303. get: function () {
  70304. return this.imageProcessingConfiguration.colorGradingEnabled;
  70305. },
  70306. /**
  70307. * Gets wether the color grading effect is enabled.
  70308. */
  70309. set: function (value) {
  70310. this.imageProcessingConfiguration.colorGradingEnabled = value;
  70311. },
  70312. enumerable: true,
  70313. configurable: true
  70314. });
  70315. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  70316. /**
  70317. * Gets exposure used in the effect.
  70318. */
  70319. get: function () {
  70320. return this.imageProcessingConfiguration.exposure;
  70321. },
  70322. /**
  70323. * Sets exposure used in the effect.
  70324. */
  70325. set: function (value) {
  70326. this.imageProcessingConfiguration.exposure = value;
  70327. },
  70328. enumerable: true,
  70329. configurable: true
  70330. });
  70331. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  70332. /**
  70333. * Gets wether tonemapping is enabled or not.
  70334. */
  70335. get: function () {
  70336. return this._imageProcessingConfiguration.toneMappingEnabled;
  70337. },
  70338. /**
  70339. * Sets wether tonemapping is enabled or not
  70340. */
  70341. set: function (value) {
  70342. this._imageProcessingConfiguration.toneMappingEnabled = value;
  70343. },
  70344. enumerable: true,
  70345. configurable: true
  70346. });
  70347. ;
  70348. ;
  70349. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  70350. /**
  70351. * Gets contrast used in the effect.
  70352. */
  70353. get: function () {
  70354. return this.imageProcessingConfiguration.contrast;
  70355. },
  70356. /**
  70357. * Sets contrast used in the effect.
  70358. */
  70359. set: function (value) {
  70360. this.imageProcessingConfiguration.contrast = value;
  70361. },
  70362. enumerable: true,
  70363. configurable: true
  70364. });
  70365. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  70366. /**
  70367. * Gets Vignette stretch size.
  70368. */
  70369. get: function () {
  70370. return this.imageProcessingConfiguration.vignetteStretch;
  70371. },
  70372. /**
  70373. * Sets Vignette stretch size.
  70374. */
  70375. set: function (value) {
  70376. this.imageProcessingConfiguration.vignetteStretch = value;
  70377. },
  70378. enumerable: true,
  70379. configurable: true
  70380. });
  70381. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  70382. /**
  70383. * Gets Vignette centre X Offset.
  70384. */
  70385. get: function () {
  70386. return this.imageProcessingConfiguration.vignetteCentreX;
  70387. },
  70388. /**
  70389. * Sets Vignette centre X Offset.
  70390. */
  70391. set: function (value) {
  70392. this.imageProcessingConfiguration.vignetteCentreX = value;
  70393. },
  70394. enumerable: true,
  70395. configurable: true
  70396. });
  70397. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  70398. /**
  70399. * Gets Vignette centre Y Offset.
  70400. */
  70401. get: function () {
  70402. return this.imageProcessingConfiguration.vignetteCentreY;
  70403. },
  70404. /**
  70405. * Sets Vignette centre Y Offset.
  70406. */
  70407. set: function (value) {
  70408. this.imageProcessingConfiguration.vignetteCentreY = value;
  70409. },
  70410. enumerable: true,
  70411. configurable: true
  70412. });
  70413. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  70414. /**
  70415. * Gets Vignette weight or intensity of the vignette effect.
  70416. */
  70417. get: function () {
  70418. return this.imageProcessingConfiguration.vignetteWeight;
  70419. },
  70420. /**
  70421. * Sets Vignette weight or intensity of the vignette effect.
  70422. */
  70423. set: function (value) {
  70424. this.imageProcessingConfiguration.vignetteWeight = value;
  70425. },
  70426. enumerable: true,
  70427. configurable: true
  70428. });
  70429. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  70430. /**
  70431. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70432. * if vignetteEnabled is set to true.
  70433. */
  70434. get: function () {
  70435. return this.imageProcessingConfiguration.vignetteColor;
  70436. },
  70437. /**
  70438. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70439. * if vignetteEnabled is set to true.
  70440. */
  70441. set: function (value) {
  70442. this.imageProcessingConfiguration.vignetteColor = value;
  70443. },
  70444. enumerable: true,
  70445. configurable: true
  70446. });
  70447. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  70448. /**
  70449. * Gets Camera field of view used by the Vignette effect.
  70450. */
  70451. get: function () {
  70452. return this.imageProcessingConfiguration.vignetteCameraFov;
  70453. },
  70454. /**
  70455. * Sets Camera field of view used by the Vignette effect.
  70456. */
  70457. set: function (value) {
  70458. this.imageProcessingConfiguration.vignetteCameraFov = value;
  70459. },
  70460. enumerable: true,
  70461. configurable: true
  70462. });
  70463. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  70464. /**
  70465. * Gets the vignette blend mode allowing different kind of effect.
  70466. */
  70467. get: function () {
  70468. return this.imageProcessingConfiguration.vignetteBlendMode;
  70469. },
  70470. /**
  70471. * Sets the vignette blend mode allowing different kind of effect.
  70472. */
  70473. set: function (value) {
  70474. this.imageProcessingConfiguration.vignetteBlendMode = value;
  70475. },
  70476. enumerable: true,
  70477. configurable: true
  70478. });
  70479. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  70480. /**
  70481. * Gets wether the vignette effect is enabled.
  70482. */
  70483. get: function () {
  70484. return this.imageProcessingConfiguration.vignetteEnabled;
  70485. },
  70486. /**
  70487. * Sets wether the vignette effect is enabled.
  70488. */
  70489. set: function (value) {
  70490. this.imageProcessingConfiguration.vignetteEnabled = value;
  70491. },
  70492. enumerable: true,
  70493. configurable: true
  70494. });
  70495. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  70496. /**
  70497. * Gets wether the input of the processing is in Gamma or Linear Space.
  70498. */
  70499. get: function () {
  70500. return this._fromLinearSpace;
  70501. },
  70502. /**
  70503. * Sets wether the input of the processing is in Gamma or Linear Space.
  70504. */
  70505. set: function (value) {
  70506. if (this._fromLinearSpace === value) {
  70507. return;
  70508. }
  70509. this._fromLinearSpace = value;
  70510. this._updateParameters();
  70511. },
  70512. enumerable: true,
  70513. configurable: true
  70514. });
  70515. ImageProcessingPostProcess.prototype.getClassName = function () {
  70516. return "ImageProcessingPostProcess";
  70517. };
  70518. ImageProcessingPostProcess.prototype._updateParameters = function () {
  70519. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  70520. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  70521. var defines = "";
  70522. for (var define in this._defines) {
  70523. if (this._defines[define]) {
  70524. defines += "#define " + define + ";\r\n";
  70525. }
  70526. }
  70527. var samplers = ["textureSampler"];
  70528. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  70529. var uniforms = ["scale"];
  70530. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  70531. this.updateEffect(defines, uniforms, samplers);
  70532. };
  70533. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  70534. _super.prototype.dispose.call(this, camera);
  70535. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70536. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70537. }
  70538. this.imageProcessingConfiguration.applyByPostProcess = false;
  70539. };
  70540. __decorate([
  70541. BABYLON.serialize()
  70542. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  70543. return ImageProcessingPostProcess;
  70544. }(BABYLON.PostProcess));
  70545. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  70546. })(BABYLON || (BABYLON = {}));
  70547. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  70548. var BABYLON;
  70549. (function (BABYLON) {
  70550. /**
  70551. * The Blur Post Process which blurs an image based on a kernel and direction.
  70552. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  70553. */
  70554. var BlurPostProcess = /** @class */ (function (_super) {
  70555. __extends(BlurPostProcess, _super);
  70556. /**
  70557. * Creates a new instance of @see BlurPostProcess
  70558. * @param name The name of the effect.
  70559. * @param direction The direction in which to blur the image.
  70560. * @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.
  70561. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  70562. * @param camera The camera to apply the render pass to.
  70563. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70564. * @param engine The engine which the post process will be applied. (default: current engine)
  70565. * @param reusable If the post process can be reused on the same frame. (default: false)
  70566. * @param textureType Type of textures used when performing the post process. (default: 0)
  70567. */
  70568. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  70569. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70570. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70571. if (defines === void 0) { defines = ""; }
  70572. 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;
  70573. _this.direction = direction;
  70574. _this._packedFloat = false;
  70575. _this._staticDefines = "";
  70576. _this._staticDefines = defines;
  70577. _this.onApplyObservable.add(function (effect) {
  70578. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  70579. });
  70580. _this.kernel = kernel;
  70581. return _this;
  70582. }
  70583. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  70584. /**
  70585. * Gets the length in pixels of the blur sample region
  70586. */
  70587. get: function () {
  70588. return this._idealKernel;
  70589. },
  70590. /**
  70591. * Sets the length in pixels of the blur sample region
  70592. */
  70593. set: function (v) {
  70594. if (this._idealKernel === v) {
  70595. return;
  70596. }
  70597. v = Math.max(v, 1);
  70598. this._idealKernel = v;
  70599. this._kernel = this._nearestBestKernel(v);
  70600. this._updateParameters();
  70601. },
  70602. enumerable: true,
  70603. configurable: true
  70604. });
  70605. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  70606. /**
  70607. * Gets wether or not the blur is unpacking/repacking floats
  70608. */
  70609. get: function () {
  70610. return this._packedFloat;
  70611. },
  70612. /**
  70613. * Sets wether or not the blur needs to unpack/repack floats
  70614. */
  70615. set: function (v) {
  70616. if (this._packedFloat === v) {
  70617. return;
  70618. }
  70619. this._packedFloat = v;
  70620. this._updateParameters();
  70621. },
  70622. enumerable: true,
  70623. configurable: true
  70624. });
  70625. BlurPostProcess.prototype._updateParameters = function () {
  70626. // Generate sampling offsets and weights
  70627. var N = this._kernel;
  70628. var centerIndex = (N - 1) / 2;
  70629. // Generate Gaussian sampling weights over kernel
  70630. var offsets = [];
  70631. var weights = [];
  70632. var totalWeight = 0;
  70633. for (var i = 0; i < N; i++) {
  70634. var u = i / (N - 1);
  70635. var w = this._gaussianWeight(u * 2.0 - 1);
  70636. offsets[i] = (i - centerIndex);
  70637. weights[i] = w;
  70638. totalWeight += w;
  70639. }
  70640. // Normalize weights
  70641. for (var i = 0; i < weights.length; i++) {
  70642. weights[i] /= totalWeight;
  70643. }
  70644. // Optimize: combine samples to take advantage of hardware linear sampling
  70645. // Walk from left to center, combining pairs (symmetrically)
  70646. var linearSamplingWeights = [];
  70647. var linearSamplingOffsets = [];
  70648. var linearSamplingMap = [];
  70649. for (var i = 0; i <= centerIndex; i += 2) {
  70650. var j = Math.min(i + 1, Math.floor(centerIndex));
  70651. var singleCenterSample = i === j;
  70652. if (singleCenterSample) {
  70653. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70654. }
  70655. else {
  70656. var sharedCell = j === centerIndex;
  70657. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70658. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70659. if (offsetLinear === 0) {
  70660. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70661. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70662. }
  70663. else {
  70664. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70665. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70666. }
  70667. }
  70668. }
  70669. for (var i = 0; i < linearSamplingMap.length; i++) {
  70670. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70671. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70672. }
  70673. // Replace with optimized
  70674. offsets = linearSamplingOffsets;
  70675. weights = linearSamplingWeights;
  70676. // Generate shaders
  70677. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70678. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70679. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70680. var defines = "";
  70681. defines += this._staticDefines;
  70682. for (var i = 0; i < varyingCount; i++) {
  70683. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70684. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70685. }
  70686. var depCount = 0;
  70687. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70688. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70689. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70690. depCount++;
  70691. }
  70692. if (this.packedFloat) {
  70693. defines += "#define PACKEDFLOAT 1";
  70694. }
  70695. this.updateEffect(defines, null, null, {
  70696. varyingCount: varyingCount,
  70697. depCount: depCount
  70698. });
  70699. };
  70700. /**
  70701. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70702. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70703. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70704. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70705. * The gaps between physical kernels are compensated for in the weighting of the samples
  70706. * @param idealKernel Ideal blur kernel.
  70707. * @return Nearest best kernel.
  70708. */
  70709. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70710. var v = Math.round(idealKernel);
  70711. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70712. var k = _a[_i];
  70713. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70714. return Math.max(k, 3);
  70715. }
  70716. }
  70717. return Math.max(v, 3);
  70718. };
  70719. /**
  70720. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70721. * @param x The point on the Gaussian distribution to sample.
  70722. * @return the value of the Gaussian function at x.
  70723. */
  70724. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70725. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70726. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70727. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70728. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70729. // truncated at around 1.3% of peak strength.
  70730. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70731. var sigma = (1 / 3);
  70732. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70733. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70734. var weight = (1.0 / denominator) * Math.exp(exponent);
  70735. return weight;
  70736. };
  70737. /**
  70738. * Generates a string that can be used as a floating point number in GLSL.
  70739. * @param x Value to print.
  70740. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70741. * @return GLSL float string.
  70742. */
  70743. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70744. if (decimalFigures === void 0) { decimalFigures = 8; }
  70745. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70746. };
  70747. return BlurPostProcess;
  70748. }(BABYLON.PostProcess));
  70749. BABYLON.BlurPostProcess = BlurPostProcess;
  70750. })(BABYLON || (BABYLON = {}));
  70751. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70752. var BABYLON;
  70753. (function (BABYLON) {
  70754. /**
  70755. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70756. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70757. * based on samples that have a large difference in distance than the center pixel.
  70758. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70759. */
  70760. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70761. __extends(DepthOfFieldBlurPostProcess, _super);
  70762. /**
  70763. * Creates a new instance of @see CircleOfConfusionPostProcess
  70764. * @param name The name of the effect.
  70765. * @param scene The scene the effect belongs to.
  70766. * @param direction The direction the blur should be applied.
  70767. * @param kernel The size of the kernel used to blur.
  70768. * @param options The required width/height ratio to downsize to before computing the render pass.
  70769. * @param camera The camera to apply the render pass to.
  70770. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70771. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70772. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70773. * @param engine The engine which the post process will be applied. (default: current engine)
  70774. * @param reusable If the post process can be reused on the same frame. (default: false)
  70775. * @param textureType Type of textures used when performing the post process. (default: 0)
  70776. */
  70777. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType) {
  70778. if (imageToBlur === void 0) { imageToBlur = null; }
  70779. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70780. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70781. 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") || this;
  70782. _this.direction = direction;
  70783. _this.onApplyObservable.add(function (effect) {
  70784. if (imageToBlur != null) {
  70785. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70786. }
  70787. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  70788. if (scene.activeCamera) {
  70789. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70790. }
  70791. });
  70792. return _this;
  70793. }
  70794. return DepthOfFieldBlurPostProcess;
  70795. }(BABYLON.BlurPostProcess));
  70796. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  70797. })(BABYLON || (BABYLON = {}));
  70798. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  70799. var BABYLON;
  70800. (function (BABYLON) {
  70801. var Bone = /** @class */ (function (_super) {
  70802. __extends(Bone, _super);
  70803. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  70804. if (parentBone === void 0) { parentBone = null; }
  70805. if (localMatrix === void 0) { localMatrix = null; }
  70806. if (restPose === void 0) { restPose = null; }
  70807. if (baseMatrix === void 0) { baseMatrix = null; }
  70808. if (index === void 0) { index = null; }
  70809. var _this = _super.call(this, name, skeleton.getScene()) || this;
  70810. _this.name = name;
  70811. _this.children = new Array();
  70812. _this.animations = new Array();
  70813. // Set this value to map this bone to a different index in the transform matrices.
  70814. // Set this value to -1 to exclude the bone from the transform matrices.
  70815. _this._index = null;
  70816. _this._worldTransform = new BABYLON.Matrix();
  70817. _this._absoluteTransform = new BABYLON.Matrix();
  70818. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  70819. _this._scaleMatrix = BABYLON.Matrix.Identity();
  70820. _this._scaleVector = BABYLON.Vector3.One();
  70821. _this._negateScaleChildren = BABYLON.Vector3.One();
  70822. _this._scalingDeterminant = 1;
  70823. _this._skeleton = skeleton;
  70824. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  70825. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  70826. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  70827. _this._index = index;
  70828. skeleton.bones.push(_this);
  70829. _this.setParent(parentBone, false);
  70830. _this._updateDifferenceMatrix();
  70831. return _this;
  70832. }
  70833. Object.defineProperty(Bone.prototype, "_matrix", {
  70834. get: function () {
  70835. return this._localMatrix;
  70836. },
  70837. set: function (val) {
  70838. if (this._localMatrix) {
  70839. this._localMatrix.copyFrom(val);
  70840. }
  70841. else {
  70842. this._localMatrix = val;
  70843. }
  70844. },
  70845. enumerable: true,
  70846. configurable: true
  70847. });
  70848. // Members
  70849. Bone.prototype.getSkeleton = function () {
  70850. return this._skeleton;
  70851. };
  70852. Bone.prototype.getParent = function () {
  70853. return this._parent;
  70854. };
  70855. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  70856. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70857. if (this._parent === parent) {
  70858. return;
  70859. }
  70860. if (this._parent) {
  70861. var index = this._parent.children.indexOf(this);
  70862. if (index !== -1) {
  70863. this._parent.children.splice(index, 1);
  70864. }
  70865. }
  70866. this._parent = parent;
  70867. if (this._parent) {
  70868. this._parent.children.push(this);
  70869. }
  70870. if (updateDifferenceMatrix) {
  70871. this._updateDifferenceMatrix();
  70872. }
  70873. };
  70874. Bone.prototype.getLocalMatrix = function () {
  70875. return this._localMatrix;
  70876. };
  70877. Bone.prototype.getBaseMatrix = function () {
  70878. return this._baseMatrix;
  70879. };
  70880. Bone.prototype.getRestPose = function () {
  70881. return this._restPose;
  70882. };
  70883. Bone.prototype.returnToRest = function () {
  70884. this.updateMatrix(this._restPose.clone());
  70885. };
  70886. Bone.prototype.getWorldMatrix = function () {
  70887. return this._worldTransform;
  70888. };
  70889. Bone.prototype.getInvertedAbsoluteTransform = function () {
  70890. return this._invertedAbsoluteTransform;
  70891. };
  70892. Bone.prototype.getAbsoluteTransform = function () {
  70893. return this._absoluteTransform;
  70894. };
  70895. Object.defineProperty(Bone.prototype, "position", {
  70896. // Properties (matches AbstractMesh properties)
  70897. get: function () {
  70898. return this.getPosition();
  70899. },
  70900. set: function (newPosition) {
  70901. this.setPosition(newPosition);
  70902. },
  70903. enumerable: true,
  70904. configurable: true
  70905. });
  70906. Object.defineProperty(Bone.prototype, "rotation", {
  70907. get: function () {
  70908. return this.getRotation();
  70909. },
  70910. set: function (newRotation) {
  70911. this.setRotation(newRotation);
  70912. },
  70913. enumerable: true,
  70914. configurable: true
  70915. });
  70916. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  70917. get: function () {
  70918. return this.getRotationQuaternion();
  70919. },
  70920. set: function (newRotation) {
  70921. this.setRotationQuaternion(newRotation);
  70922. },
  70923. enumerable: true,
  70924. configurable: true
  70925. });
  70926. Object.defineProperty(Bone.prototype, "scaling", {
  70927. get: function () {
  70928. return this.getScale();
  70929. },
  70930. set: function (newScaling) {
  70931. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  70932. },
  70933. enumerable: true,
  70934. configurable: true
  70935. });
  70936. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  70937. /**
  70938. * Gets the animation properties override
  70939. */
  70940. get: function () {
  70941. return this._skeleton.animationPropertiesOverride;
  70942. },
  70943. enumerable: true,
  70944. configurable: true
  70945. });
  70946. // Methods
  70947. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  70948. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70949. this._baseMatrix = matrix.clone();
  70950. this._localMatrix = matrix.clone();
  70951. this._skeleton._markAsDirty();
  70952. if (updateDifferenceMatrix) {
  70953. this._updateDifferenceMatrix();
  70954. }
  70955. };
  70956. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  70957. if (!rootMatrix) {
  70958. rootMatrix = this._baseMatrix;
  70959. }
  70960. if (this._parent) {
  70961. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70962. }
  70963. else {
  70964. this._absoluteTransform.copyFrom(rootMatrix);
  70965. }
  70966. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  70967. for (var index = 0; index < this.children.length; index++) {
  70968. this.children[index]._updateDifferenceMatrix();
  70969. }
  70970. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  70971. };
  70972. Bone.prototype.markAsDirty = function () {
  70973. this._currentRenderId++;
  70974. this._skeleton._markAsDirty();
  70975. };
  70976. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  70977. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70978. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  70979. // all animation may be coming from a library skeleton, so may need to create animation
  70980. if (this.animations.length === 0) {
  70981. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  70982. this.animations[0].setKeys([]);
  70983. }
  70984. // get animation info / verify there is such a range from the source bone
  70985. var sourceRange = source.animations[0].getRange(rangeName);
  70986. if (!sourceRange) {
  70987. return false;
  70988. }
  70989. var from = sourceRange.from;
  70990. var to = sourceRange.to;
  70991. var sourceKeys = source.animations[0].getKeys();
  70992. // rescaling prep
  70993. var sourceBoneLength = source.length;
  70994. var sourceParent = source.getParent();
  70995. var parent = this.getParent();
  70996. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  70997. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  70998. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  70999. var destKeys = this.animations[0].getKeys();
  71000. // loop vars declaration
  71001. var orig;
  71002. var origTranslation;
  71003. var mat;
  71004. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  71005. orig = sourceKeys[key];
  71006. if (orig.frame >= from && orig.frame <= to) {
  71007. if (rescaleAsRequired) {
  71008. mat = orig.value.clone();
  71009. // scale based on parent ratio, when bone has parent
  71010. if (parentScalingReqd) {
  71011. origTranslation = mat.getTranslation();
  71012. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  71013. // scale based on skeleton dimension ratio when root bone, and value is passed
  71014. }
  71015. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  71016. origTranslation = mat.getTranslation();
  71017. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  71018. // use original when root bone, and no data for skelDimensionsRatio
  71019. }
  71020. else {
  71021. mat = orig.value;
  71022. }
  71023. }
  71024. else {
  71025. mat = orig.value;
  71026. }
  71027. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  71028. }
  71029. }
  71030. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  71031. return true;
  71032. };
  71033. /**
  71034. * Translate the bone in local or world space.
  71035. * @param vec The amount to translate the bone.
  71036. * @param space The space that the translation is in.
  71037. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71038. */
  71039. Bone.prototype.translate = function (vec, space, mesh) {
  71040. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71041. var lm = this.getLocalMatrix();
  71042. if (space == BABYLON.Space.LOCAL) {
  71043. lm.m[12] += vec.x;
  71044. lm.m[13] += vec.y;
  71045. lm.m[14] += vec.z;
  71046. }
  71047. else {
  71048. var wm = null;
  71049. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71050. if (mesh) {
  71051. wm = mesh.getWorldMatrix();
  71052. }
  71053. this._skeleton.computeAbsoluteTransforms();
  71054. var tmat = Bone._tmpMats[0];
  71055. var tvec = Bone._tmpVecs[0];
  71056. if (this._parent) {
  71057. if (mesh && wm) {
  71058. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71059. tmat.multiplyToRef(wm, tmat);
  71060. }
  71061. else {
  71062. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71063. }
  71064. }
  71065. tmat.m[12] = 0;
  71066. tmat.m[13] = 0;
  71067. tmat.m[14] = 0;
  71068. tmat.invert();
  71069. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  71070. lm.m[12] += tvec.x;
  71071. lm.m[13] += tvec.y;
  71072. lm.m[14] += tvec.z;
  71073. }
  71074. this.markAsDirty();
  71075. };
  71076. /**
  71077. * Set the postion of the bone in local or world space.
  71078. * @param position The position to set the bone.
  71079. * @param space The space that the position is in.
  71080. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71081. */
  71082. Bone.prototype.setPosition = function (position, space, mesh) {
  71083. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71084. var lm = this.getLocalMatrix();
  71085. if (space == BABYLON.Space.LOCAL) {
  71086. lm.m[12] = position.x;
  71087. lm.m[13] = position.y;
  71088. lm.m[14] = position.z;
  71089. }
  71090. else {
  71091. var wm = null;
  71092. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71093. if (mesh) {
  71094. wm = mesh.getWorldMatrix();
  71095. }
  71096. this._skeleton.computeAbsoluteTransforms();
  71097. var tmat = Bone._tmpMats[0];
  71098. var vec = Bone._tmpVecs[0];
  71099. if (this._parent) {
  71100. if (mesh && wm) {
  71101. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71102. tmat.multiplyToRef(wm, tmat);
  71103. }
  71104. else {
  71105. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71106. }
  71107. }
  71108. tmat.invert();
  71109. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  71110. lm.m[12] = vec.x;
  71111. lm.m[13] = vec.y;
  71112. lm.m[14] = vec.z;
  71113. }
  71114. this.markAsDirty();
  71115. };
  71116. /**
  71117. * Set the absolute postion of the bone (world space).
  71118. * @param position The position to set the bone.
  71119. * @param mesh The mesh that this bone is attached to.
  71120. */
  71121. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  71122. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  71123. };
  71124. /**
  71125. * Set the scale of the bone on the x, y and z axes.
  71126. * @param x The scale of the bone on the x axis.
  71127. * @param x The scale of the bone on the y axis.
  71128. * @param z The scale of the bone on the z axis.
  71129. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71130. */
  71131. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  71132. if (scaleChildren === void 0) { scaleChildren = false; }
  71133. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  71134. if (!scaleChildren) {
  71135. this._negateScaleChildren.x = 1 / x;
  71136. this._negateScaleChildren.y = 1 / y;
  71137. this._negateScaleChildren.z = 1 / z;
  71138. }
  71139. this._syncScaleVector();
  71140. }
  71141. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  71142. };
  71143. /**
  71144. * Scale the bone on the x, y and z axes.
  71145. * @param x The amount to scale the bone on the x axis.
  71146. * @param x The amount to scale the bone on the y axis.
  71147. * @param z The amount to scale the bone on the z axis.
  71148. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71149. */
  71150. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  71151. if (scaleChildren === void 0) { scaleChildren = false; }
  71152. var locMat = this.getLocalMatrix();
  71153. var origLocMat = Bone._tmpMats[0];
  71154. origLocMat.copyFrom(locMat);
  71155. var origLocMatInv = Bone._tmpMats[1];
  71156. origLocMatInv.copyFrom(origLocMat);
  71157. origLocMatInv.invert();
  71158. var scaleMat = Bone._tmpMats[2];
  71159. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  71160. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  71161. this._scaleVector.x *= x;
  71162. this._scaleVector.y *= y;
  71163. this._scaleVector.z *= z;
  71164. locMat.multiplyToRef(origLocMatInv, locMat);
  71165. locMat.multiplyToRef(scaleMat, locMat);
  71166. locMat.multiplyToRef(origLocMat, locMat);
  71167. var parent = this.getParent();
  71168. if (parent) {
  71169. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  71170. }
  71171. else {
  71172. this.getAbsoluteTransform().copyFrom(locMat);
  71173. }
  71174. var len = this.children.length;
  71175. scaleMat.invert();
  71176. for (var i = 0; i < len; i++) {
  71177. var child = this.children[i];
  71178. var cm = child.getLocalMatrix();
  71179. cm.multiplyToRef(scaleMat, cm);
  71180. var lm = child.getLocalMatrix();
  71181. lm.m[12] *= x;
  71182. lm.m[13] *= y;
  71183. lm.m[14] *= z;
  71184. }
  71185. this.computeAbsoluteTransforms();
  71186. if (scaleChildren) {
  71187. for (var i = 0; i < len; i++) {
  71188. this.children[i].scale(x, y, z, scaleChildren);
  71189. }
  71190. }
  71191. this.markAsDirty();
  71192. };
  71193. /**
  71194. * Set the yaw, pitch, and roll of the bone in local or world space.
  71195. * @param yaw The rotation of the bone on the y axis.
  71196. * @param pitch The rotation of the bone on the x axis.
  71197. * @param roll The rotation of the bone on the z axis.
  71198. * @param space The space that the axes of rotation are in.
  71199. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71200. */
  71201. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  71202. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71203. var rotMat = Bone._tmpMats[0];
  71204. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  71205. var rotMatInv = Bone._tmpMats[1];
  71206. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71207. rotMatInv.multiplyToRef(rotMat, rotMat);
  71208. this._rotateWithMatrix(rotMat, space, mesh);
  71209. };
  71210. /**
  71211. * Rotate the bone on an axis in local or world space.
  71212. * @param axis The axis to rotate the bone on.
  71213. * @param amount The amount to rotate the bone.
  71214. * @param space The space that the axis is in.
  71215. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71216. */
  71217. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  71218. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71219. var rmat = Bone._tmpMats[0];
  71220. rmat.m[12] = 0;
  71221. rmat.m[13] = 0;
  71222. rmat.m[14] = 0;
  71223. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  71224. this._rotateWithMatrix(rmat, space, mesh);
  71225. };
  71226. /**
  71227. * Set the rotation of the bone to a particular axis angle in local or world space.
  71228. * @param axis The axis to rotate the bone on.
  71229. * @param angle The angle that the bone should be rotated to.
  71230. * @param space The space that the axis is in.
  71231. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71232. */
  71233. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  71234. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71235. var rotMat = Bone._tmpMats[0];
  71236. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  71237. var rotMatInv = Bone._tmpMats[1];
  71238. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71239. rotMatInv.multiplyToRef(rotMat, rotMat);
  71240. this._rotateWithMatrix(rotMat, space, mesh);
  71241. };
  71242. /**
  71243. * Set the euler rotation of the bone in local of world space.
  71244. * @param rotation The euler rotation that the bone should be set to.
  71245. * @param space The space that the rotation is in.
  71246. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71247. */
  71248. Bone.prototype.setRotation = function (rotation, space, mesh) {
  71249. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71250. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  71251. };
  71252. /**
  71253. * Set the quaternion rotation of the bone in local of world space.
  71254. * @param quat The quaternion rotation that the bone should be set to.
  71255. * @param space The space that the rotation is in.
  71256. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71257. */
  71258. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  71259. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71260. var rotMatInv = Bone._tmpMats[0];
  71261. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71262. var rotMat = Bone._tmpMats[1];
  71263. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  71264. rotMatInv.multiplyToRef(rotMat, rotMat);
  71265. this._rotateWithMatrix(rotMat, space, mesh);
  71266. };
  71267. /**
  71268. * Set the rotation matrix of the bone in local of world space.
  71269. * @param rotMat The rotation matrix that the bone should be set to.
  71270. * @param space The space that the rotation is in.
  71271. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71272. */
  71273. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  71274. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71275. var rotMatInv = Bone._tmpMats[0];
  71276. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71277. var rotMat2 = Bone._tmpMats[1];
  71278. rotMat2.copyFrom(rotMat);
  71279. rotMatInv.multiplyToRef(rotMat, rotMat2);
  71280. this._rotateWithMatrix(rotMat2, space, mesh);
  71281. };
  71282. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  71283. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71284. var lmat = this.getLocalMatrix();
  71285. var lx = lmat.m[12];
  71286. var ly = lmat.m[13];
  71287. var lz = lmat.m[14];
  71288. var parent = this.getParent();
  71289. var parentScale = Bone._tmpMats[3];
  71290. var parentScaleInv = Bone._tmpMats[4];
  71291. if (parent) {
  71292. if (space == BABYLON.Space.WORLD) {
  71293. if (mesh) {
  71294. parentScale.copyFrom(mesh.getWorldMatrix());
  71295. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  71296. }
  71297. else {
  71298. parentScale.copyFrom(parent.getAbsoluteTransform());
  71299. }
  71300. }
  71301. else {
  71302. parentScale = parent._scaleMatrix;
  71303. }
  71304. parentScaleInv.copyFrom(parentScale);
  71305. parentScaleInv.invert();
  71306. lmat.multiplyToRef(parentScale, lmat);
  71307. lmat.multiplyToRef(rmat, lmat);
  71308. lmat.multiplyToRef(parentScaleInv, lmat);
  71309. }
  71310. else {
  71311. if (space == BABYLON.Space.WORLD && mesh) {
  71312. parentScale.copyFrom(mesh.getWorldMatrix());
  71313. parentScaleInv.copyFrom(parentScale);
  71314. parentScaleInv.invert();
  71315. lmat.multiplyToRef(parentScale, lmat);
  71316. lmat.multiplyToRef(rmat, lmat);
  71317. lmat.multiplyToRef(parentScaleInv, lmat);
  71318. }
  71319. else {
  71320. lmat.multiplyToRef(rmat, lmat);
  71321. }
  71322. }
  71323. lmat.m[12] = lx;
  71324. lmat.m[13] = ly;
  71325. lmat.m[14] = lz;
  71326. this.computeAbsoluteTransforms();
  71327. this.markAsDirty();
  71328. };
  71329. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71330. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71331. if (space == BABYLON.Space.WORLD) {
  71332. var scaleMatrix = Bone._tmpMats[2];
  71333. scaleMatrix.copyFrom(this._scaleMatrix);
  71334. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71335. if (mesh) {
  71336. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71337. var meshScale = Bone._tmpMats[3];
  71338. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71339. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71340. }
  71341. rotMatInv.invert();
  71342. scaleMatrix.m[0] *= this._scalingDeterminant;
  71343. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71344. }
  71345. else {
  71346. rotMatInv.copyFrom(this.getLocalMatrix());
  71347. rotMatInv.invert();
  71348. var scaleMatrix = Bone._tmpMats[2];
  71349. scaleMatrix.copyFrom(this._scaleMatrix);
  71350. if (this._parent) {
  71351. var pscaleMatrix = Bone._tmpMats[3];
  71352. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71353. pscaleMatrix.invert();
  71354. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71355. }
  71356. else {
  71357. scaleMatrix.m[0] *= this._scalingDeterminant;
  71358. }
  71359. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71360. }
  71361. };
  71362. /**
  71363. * Get the scale of the bone
  71364. * @returns the scale of the bone
  71365. */
  71366. Bone.prototype.getScale = function () {
  71367. return this._scaleVector.clone();
  71368. };
  71369. /**
  71370. * Copy the scale of the bone to a vector3.
  71371. * @param result The vector3 to copy the scale to
  71372. */
  71373. Bone.prototype.getScaleToRef = function (result) {
  71374. result.copyFrom(this._scaleVector);
  71375. };
  71376. /**
  71377. * Get the position of the bone in local or world space.
  71378. * @param space The space that the returned position is in.
  71379. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71380. * @returns The position of the bone
  71381. */
  71382. Bone.prototype.getPosition = function (space, mesh) {
  71383. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71384. if (mesh === void 0) { mesh = null; }
  71385. var pos = BABYLON.Vector3.Zero();
  71386. this.getPositionToRef(space, mesh, pos);
  71387. return pos;
  71388. };
  71389. /**
  71390. * Copy the position of the bone to a vector3 in local or world space.
  71391. * @param space The space that the returned position is in.
  71392. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71393. * @param result The vector3 to copy the position to.
  71394. */
  71395. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  71396. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71397. if (space == BABYLON.Space.LOCAL) {
  71398. var lm = this.getLocalMatrix();
  71399. result.x = lm.m[12];
  71400. result.y = lm.m[13];
  71401. result.z = lm.m[14];
  71402. }
  71403. else {
  71404. var wm = null;
  71405. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71406. if (mesh) {
  71407. wm = mesh.getWorldMatrix();
  71408. }
  71409. this._skeleton.computeAbsoluteTransforms();
  71410. var tmat = Bone._tmpMats[0];
  71411. if (mesh && wm) {
  71412. tmat.copyFrom(this.getAbsoluteTransform());
  71413. tmat.multiplyToRef(wm, tmat);
  71414. }
  71415. else {
  71416. tmat = this.getAbsoluteTransform();
  71417. }
  71418. result.x = tmat.m[12];
  71419. result.y = tmat.m[13];
  71420. result.z = tmat.m[14];
  71421. }
  71422. };
  71423. /**
  71424. * Get the absolute position of the bone (world space).
  71425. * @param mesh The mesh that this bone is attached to.
  71426. * @returns The absolute position of the bone
  71427. */
  71428. Bone.prototype.getAbsolutePosition = function (mesh) {
  71429. if (mesh === void 0) { mesh = null; }
  71430. var pos = BABYLON.Vector3.Zero();
  71431. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  71432. return pos;
  71433. };
  71434. /**
  71435. * Copy the absolute position of the bone (world space) to the result param.
  71436. * @param mesh The mesh that this bone is attached to.
  71437. * @param result The vector3 to copy the absolute position to.
  71438. */
  71439. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  71440. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  71441. };
  71442. /**
  71443. * Compute the absolute transforms of this bone and its children.
  71444. */
  71445. Bone.prototype.computeAbsoluteTransforms = function () {
  71446. if (this._parent) {
  71447. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71448. }
  71449. else {
  71450. this._absoluteTransform.copyFrom(this._localMatrix);
  71451. var poseMatrix = this._skeleton.getPoseMatrix();
  71452. if (poseMatrix) {
  71453. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  71454. }
  71455. }
  71456. var children = this.children;
  71457. var len = children.length;
  71458. for (var i = 0; i < len; i++) {
  71459. children[i].computeAbsoluteTransforms();
  71460. }
  71461. };
  71462. Bone.prototype._syncScaleVector = function () {
  71463. var lm = this.getLocalMatrix();
  71464. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  71465. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  71466. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  71467. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  71468. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  71469. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  71470. this._scaleVector.x = xs * Math.sqrt(xsq);
  71471. this._scaleVector.y = ys * Math.sqrt(ysq);
  71472. this._scaleVector.z = zs * Math.sqrt(zsq);
  71473. if (this._parent) {
  71474. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  71475. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  71476. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  71477. }
  71478. 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);
  71479. };
  71480. /**
  71481. * Get the world direction from an axis that is in the local space of the bone.
  71482. * @param localAxis The local direction that is used to compute the world direction.
  71483. * @param mesh The mesh that this bone is attached to.
  71484. * @returns The world direction
  71485. */
  71486. Bone.prototype.getDirection = function (localAxis, mesh) {
  71487. if (mesh === void 0) { mesh = null; }
  71488. var result = BABYLON.Vector3.Zero();
  71489. this.getDirectionToRef(localAxis, mesh, result);
  71490. return result;
  71491. };
  71492. /**
  71493. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  71494. * @param localAxis The local direction that is used to compute the world direction.
  71495. * @param mesh The mesh that this bone is attached to.
  71496. * @param result The vector3 that the world direction will be copied to.
  71497. */
  71498. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  71499. if (mesh === void 0) { mesh = null; }
  71500. var wm = null;
  71501. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71502. if (mesh) {
  71503. wm = mesh.getWorldMatrix();
  71504. }
  71505. this._skeleton.computeAbsoluteTransforms();
  71506. var mat = Bone._tmpMats[0];
  71507. mat.copyFrom(this.getAbsoluteTransform());
  71508. if (mesh && wm) {
  71509. mat.multiplyToRef(wm, mat);
  71510. }
  71511. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  71512. result.normalize();
  71513. };
  71514. /**
  71515. * Get the euler rotation of the bone in local or world space.
  71516. * @param space The space that the rotation should be in.
  71517. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71518. * @returns The euler rotation
  71519. */
  71520. Bone.prototype.getRotation = function (space, mesh) {
  71521. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71522. if (mesh === void 0) { mesh = null; }
  71523. var result = BABYLON.Vector3.Zero();
  71524. this.getRotationToRef(space, mesh, result);
  71525. return result;
  71526. };
  71527. /**
  71528. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  71529. * @param space The space that the rotation should be in.
  71530. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71531. * @param result The vector3 that the rotation should be copied to.
  71532. */
  71533. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  71534. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71535. if (mesh === void 0) { mesh = null; }
  71536. var quat = Bone._tmpQuat;
  71537. this.getRotationQuaternionToRef(space, mesh, quat);
  71538. quat.toEulerAnglesToRef(result);
  71539. };
  71540. /**
  71541. * Get the quaternion rotation of the bone in either local or world space.
  71542. * @param space The space that the rotation should be in.
  71543. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71544. * @returns The quaternion rotation
  71545. */
  71546. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  71547. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71548. if (mesh === void 0) { mesh = null; }
  71549. var result = BABYLON.Quaternion.Identity();
  71550. this.getRotationQuaternionToRef(space, mesh, result);
  71551. return result;
  71552. };
  71553. /**
  71554. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  71555. * @param space The space that the rotation should be in.
  71556. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71557. * @param result The quaternion that the rotation should be copied to.
  71558. */
  71559. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  71560. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71561. if (mesh === void 0) { mesh = null; }
  71562. if (space == BABYLON.Space.LOCAL) {
  71563. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71564. }
  71565. else {
  71566. var mat = Bone._tmpMats[0];
  71567. var amat = this.getAbsoluteTransform();
  71568. if (mesh) {
  71569. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71570. }
  71571. else {
  71572. mat.copyFrom(amat);
  71573. }
  71574. mat.m[0] *= this._scalingDeterminant;
  71575. mat.m[1] *= this._scalingDeterminant;
  71576. mat.m[2] *= this._scalingDeterminant;
  71577. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71578. }
  71579. };
  71580. /**
  71581. * Get the rotation matrix of the bone in local or world space.
  71582. * @param space The space that the rotation should be in.
  71583. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71584. * @returns The rotation matrix
  71585. */
  71586. Bone.prototype.getRotationMatrix = function (space, mesh) {
  71587. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71588. var result = BABYLON.Matrix.Identity();
  71589. this.getRotationMatrixToRef(space, mesh, result);
  71590. return result;
  71591. };
  71592. /**
  71593. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  71594. * @param space The space that the rotation should be in.
  71595. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71596. * @param result The quaternion that the rotation should be copied to.
  71597. */
  71598. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  71599. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71600. if (space == BABYLON.Space.LOCAL) {
  71601. this.getLocalMatrix().getRotationMatrixToRef(result);
  71602. }
  71603. else {
  71604. var mat = Bone._tmpMats[0];
  71605. var amat = this.getAbsoluteTransform();
  71606. if (mesh) {
  71607. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71608. }
  71609. else {
  71610. mat.copyFrom(amat);
  71611. }
  71612. mat.m[0] *= this._scalingDeterminant;
  71613. mat.m[1] *= this._scalingDeterminant;
  71614. mat.m[2] *= this._scalingDeterminant;
  71615. mat.getRotationMatrixToRef(result);
  71616. }
  71617. };
  71618. /**
  71619. * Get the world position of a point that is in the local space of the bone.
  71620. * @param position The local position
  71621. * @param mesh The mesh that this bone is attached to.
  71622. * @returns The world position
  71623. */
  71624. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  71625. if (mesh === void 0) { mesh = null; }
  71626. var result = BABYLON.Vector3.Zero();
  71627. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  71628. return result;
  71629. };
  71630. /**
  71631. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  71632. * @param position The local position
  71633. * @param mesh The mesh that this bone is attached to.
  71634. * @param result The vector3 that the world position should be copied to.
  71635. */
  71636. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  71637. if (mesh === void 0) { mesh = null; }
  71638. var wm = null;
  71639. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71640. if (mesh) {
  71641. wm = mesh.getWorldMatrix();
  71642. }
  71643. this._skeleton.computeAbsoluteTransforms();
  71644. var tmat = Bone._tmpMats[0];
  71645. if (mesh && wm) {
  71646. tmat.copyFrom(this.getAbsoluteTransform());
  71647. tmat.multiplyToRef(wm, tmat);
  71648. }
  71649. else {
  71650. tmat = this.getAbsoluteTransform();
  71651. }
  71652. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71653. };
  71654. /**
  71655. * Get the local position of a point that is in world space.
  71656. * @param position The world position
  71657. * @param mesh The mesh that this bone is attached to.
  71658. * @returns The local position
  71659. */
  71660. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  71661. if (mesh === void 0) { mesh = null; }
  71662. var result = BABYLON.Vector3.Zero();
  71663. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  71664. return result;
  71665. };
  71666. /**
  71667. * Get the local position of a point that is in world space and copy it to the result param.
  71668. * @param position The world position
  71669. * @param mesh The mesh that this bone is attached to.
  71670. * @param result The vector3 that the local position should be copied to.
  71671. */
  71672. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  71673. if (mesh === void 0) { mesh = null; }
  71674. var wm = null;
  71675. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71676. if (mesh) {
  71677. wm = mesh.getWorldMatrix();
  71678. }
  71679. this._skeleton.computeAbsoluteTransforms();
  71680. var tmat = Bone._tmpMats[0];
  71681. tmat.copyFrom(this.getAbsoluteTransform());
  71682. if (mesh && wm) {
  71683. tmat.multiplyToRef(wm, tmat);
  71684. }
  71685. tmat.invert();
  71686. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71687. };
  71688. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71689. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  71690. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71691. return Bone;
  71692. }(BABYLON.Node));
  71693. BABYLON.Bone = Bone;
  71694. })(BABYLON || (BABYLON = {}));
  71695. //# sourceMappingURL=babylon.bone.js.map
  71696. var BABYLON;
  71697. (function (BABYLON) {
  71698. var BoneIKController = /** @class */ (function () {
  71699. function BoneIKController(mesh, bone, options) {
  71700. this.targetPosition = BABYLON.Vector3.Zero();
  71701. this.poleTargetPosition = BABYLON.Vector3.Zero();
  71702. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  71703. this.poleAngle = 0;
  71704. this.slerpAmount = 1;
  71705. this._bone1Quat = BABYLON.Quaternion.Identity();
  71706. this._bone1Mat = BABYLON.Matrix.Identity();
  71707. this._bone2Ang = Math.PI;
  71708. this._maxAngle = Math.PI;
  71709. this._rightHandedSystem = false;
  71710. this._bendAxis = BABYLON.Vector3.Right();
  71711. this._slerping = false;
  71712. this._adjustRoll = 0;
  71713. this._bone2 = bone;
  71714. this._bone1 = bone.getParent();
  71715. if (!this._bone1) {
  71716. return;
  71717. }
  71718. this.mesh = mesh;
  71719. var bonePos = bone.getPosition();
  71720. if (bone.getAbsoluteTransform().determinant() > 0) {
  71721. this._rightHandedSystem = true;
  71722. this._bendAxis.x = 0;
  71723. this._bendAxis.y = 0;
  71724. this._bendAxis.z = -1;
  71725. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  71726. this._adjustRoll = Math.PI * .5;
  71727. this._bendAxis.z = 1;
  71728. }
  71729. }
  71730. if (this._bone1.length) {
  71731. var boneScale1 = this._bone1.getScale();
  71732. var boneScale2 = this._bone2.getScale();
  71733. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  71734. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  71735. }
  71736. else if (this._bone1.children[0]) {
  71737. mesh.computeWorldMatrix(true);
  71738. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  71739. var pos2 = this._bone2.getAbsolutePosition(mesh);
  71740. var pos3 = this._bone1.getAbsolutePosition(mesh);
  71741. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  71742. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  71743. }
  71744. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  71745. this.maxAngle = Math.PI;
  71746. if (options) {
  71747. if (options.targetMesh) {
  71748. this.targetMesh = options.targetMesh;
  71749. this.targetMesh.computeWorldMatrix(true);
  71750. }
  71751. if (options.poleTargetMesh) {
  71752. this.poleTargetMesh = options.poleTargetMesh;
  71753. this.poleTargetMesh.computeWorldMatrix(true);
  71754. }
  71755. else if (options.poleTargetBone) {
  71756. this.poleTargetBone = options.poleTargetBone;
  71757. }
  71758. else if (this._bone1.getParent()) {
  71759. this.poleTargetBone = this._bone1.getParent();
  71760. }
  71761. if (options.poleTargetLocalOffset) {
  71762. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  71763. }
  71764. if (options.poleAngle) {
  71765. this.poleAngle = options.poleAngle;
  71766. }
  71767. if (options.bendAxis) {
  71768. this._bendAxis.copyFrom(options.bendAxis);
  71769. }
  71770. if (options.maxAngle) {
  71771. this.maxAngle = options.maxAngle;
  71772. }
  71773. if (options.slerpAmount) {
  71774. this.slerpAmount = options.slerpAmount;
  71775. }
  71776. }
  71777. }
  71778. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  71779. get: function () {
  71780. return this._maxAngle;
  71781. },
  71782. set: function (value) {
  71783. this._setMaxAngle(value);
  71784. },
  71785. enumerable: true,
  71786. configurable: true
  71787. });
  71788. BoneIKController.prototype._setMaxAngle = function (ang) {
  71789. if (ang < 0) {
  71790. ang = 0;
  71791. }
  71792. if (ang > Math.PI || ang == undefined) {
  71793. ang = Math.PI;
  71794. }
  71795. this._maxAngle = ang;
  71796. var a = this._bone1Length;
  71797. var b = this._bone2Length;
  71798. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  71799. };
  71800. BoneIKController.prototype.update = function () {
  71801. var bone1 = this._bone1;
  71802. if (!bone1) {
  71803. return;
  71804. }
  71805. var target = this.targetPosition;
  71806. var poleTarget = this.poleTargetPosition;
  71807. var mat1 = BoneIKController._tmpMats[0];
  71808. var mat2 = BoneIKController._tmpMats[1];
  71809. if (this.targetMesh) {
  71810. target.copyFrom(this.targetMesh.getAbsolutePosition());
  71811. }
  71812. if (this.poleTargetBone) {
  71813. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  71814. }
  71815. else if (this.poleTargetMesh) {
  71816. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  71817. }
  71818. var bonePos = BoneIKController._tmpVecs[0];
  71819. var zaxis = BoneIKController._tmpVecs[1];
  71820. var xaxis = BoneIKController._tmpVecs[2];
  71821. var yaxis = BoneIKController._tmpVecs[3];
  71822. var upAxis = BoneIKController._tmpVecs[4];
  71823. var _tmpQuat = BoneIKController._tmpQuat;
  71824. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  71825. poleTarget.subtractToRef(bonePos, upAxis);
  71826. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  71827. upAxis.y = 1;
  71828. }
  71829. else {
  71830. upAxis.normalize();
  71831. }
  71832. target.subtractToRef(bonePos, yaxis);
  71833. yaxis.normalize();
  71834. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  71835. zaxis.normalize();
  71836. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  71837. xaxis.normalize();
  71838. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  71839. var a = this._bone1Length;
  71840. var b = this._bone2Length;
  71841. var c = BABYLON.Vector3.Distance(bonePos, target);
  71842. if (this._maxReach > 0) {
  71843. c = Math.min(this._maxReach, c);
  71844. }
  71845. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  71846. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  71847. if (acosa > 1) {
  71848. acosa = 1;
  71849. }
  71850. if (acosb > 1) {
  71851. acosb = 1;
  71852. }
  71853. if (acosa < -1) {
  71854. acosa = -1;
  71855. }
  71856. if (acosb < -1) {
  71857. acosb = -1;
  71858. }
  71859. var angA = Math.acos(acosa);
  71860. var angB = Math.acos(acosb);
  71861. var angC = -angA - angB;
  71862. if (this._rightHandedSystem) {
  71863. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  71864. mat2.multiplyToRef(mat1, mat1);
  71865. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  71866. mat2.multiplyToRef(mat1, mat1);
  71867. }
  71868. else {
  71869. var _tmpVec = BoneIKController._tmpVecs[5];
  71870. _tmpVec.copyFrom(this._bendAxis);
  71871. _tmpVec.x *= -1;
  71872. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  71873. mat2.multiplyToRef(mat1, mat1);
  71874. }
  71875. if (this.poleAngle) {
  71876. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  71877. mat1.multiplyToRef(mat2, mat1);
  71878. }
  71879. if (this._bone1) {
  71880. if (this.slerpAmount < 1) {
  71881. if (!this._slerping) {
  71882. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  71883. }
  71884. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  71885. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  71886. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  71887. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  71888. this._slerping = true;
  71889. }
  71890. else {
  71891. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  71892. this._bone1Mat.copyFrom(mat1);
  71893. this._slerping = false;
  71894. }
  71895. }
  71896. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  71897. this._bone2Ang = angC;
  71898. };
  71899. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71900. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  71901. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71902. return BoneIKController;
  71903. }());
  71904. BABYLON.BoneIKController = BoneIKController;
  71905. })(BABYLON || (BABYLON = {}));
  71906. //# sourceMappingURL=babylon.boneIKController.js.map
  71907. var BABYLON;
  71908. (function (BABYLON) {
  71909. var BoneLookController = /** @class */ (function () {
  71910. /**
  71911. * Create a BoneLookController
  71912. * @param mesh the mesh that the bone belongs to
  71913. * @param bone the bone that will be looking to the target
  71914. * @param target the target Vector3 to look at
  71915. * @param settings optional settings:
  71916. * - maxYaw: the maximum angle the bone will yaw to
  71917. * - minYaw: the minimum angle the bone will yaw to
  71918. * - maxPitch: the maximum angle the bone will pitch to
  71919. * - minPitch: the minimum angle the bone will yaw to
  71920. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  71921. * - upAxis: the up axis of the coordinate system
  71922. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71923. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  71924. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  71925. * - adjustYaw: used to make an adjustment to the yaw of the bone
  71926. * - adjustPitch: used to make an adjustment to the pitch of the bone
  71927. * - adjustRoll: used to make an adjustment to the roll of the bone
  71928. **/
  71929. function BoneLookController(mesh, bone, target, options) {
  71930. /**
  71931. * The up axis of the coordinate system that is used when the bone is rotated.
  71932. */
  71933. this.upAxis = BABYLON.Vector3.Up();
  71934. /**
  71935. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71936. */
  71937. this.upAxisSpace = BABYLON.Space.LOCAL;
  71938. /**
  71939. * Used to make an adjustment to the yaw of the bone.
  71940. */
  71941. this.adjustYaw = 0;
  71942. /**
  71943. * Used to make an adjustment to the pitch of the bone.
  71944. */
  71945. this.adjustPitch = 0;
  71946. /**
  71947. * Used to make an adjustment to the roll of the bone.
  71948. */
  71949. this.adjustRoll = 0;
  71950. /**
  71951. * 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).
  71952. */
  71953. this.slerpAmount = 1;
  71954. this._boneQuat = BABYLON.Quaternion.Identity();
  71955. this._slerping = false;
  71956. this._firstFrameSkipped = false;
  71957. this._fowardAxis = BABYLON.Vector3.Forward();
  71958. this.mesh = mesh;
  71959. this.bone = bone;
  71960. this.target = target;
  71961. if (options) {
  71962. if (options.adjustYaw) {
  71963. this.adjustYaw = options.adjustYaw;
  71964. }
  71965. if (options.adjustPitch) {
  71966. this.adjustPitch = options.adjustPitch;
  71967. }
  71968. if (options.adjustRoll) {
  71969. this.adjustRoll = options.adjustRoll;
  71970. }
  71971. if (options.maxYaw != null) {
  71972. this.maxYaw = options.maxYaw;
  71973. }
  71974. else {
  71975. this.maxYaw = Math.PI;
  71976. }
  71977. if (options.minYaw != null) {
  71978. this.minYaw = options.minYaw;
  71979. }
  71980. else {
  71981. this.minYaw = -Math.PI;
  71982. }
  71983. if (options.maxPitch != null) {
  71984. this.maxPitch = options.maxPitch;
  71985. }
  71986. else {
  71987. this.maxPitch = Math.PI;
  71988. }
  71989. if (options.minPitch != null) {
  71990. this.minPitch = options.minPitch;
  71991. }
  71992. else {
  71993. this.minPitch = -Math.PI;
  71994. }
  71995. if (options.slerpAmount != null) {
  71996. this.slerpAmount = options.slerpAmount;
  71997. }
  71998. if (options.upAxis != null) {
  71999. this.upAxis = options.upAxis;
  72000. }
  72001. if (options.upAxisSpace != null) {
  72002. this.upAxisSpace = options.upAxisSpace;
  72003. }
  72004. if (options.yawAxis != null || options.pitchAxis != null) {
  72005. var newYawAxis = BABYLON.Axis.Y;
  72006. var newPitchAxis = BABYLON.Axis.X;
  72007. if (options.yawAxis != null) {
  72008. newYawAxis = options.yawAxis.clone();
  72009. newYawAxis.normalize();
  72010. }
  72011. if (options.pitchAxis != null) {
  72012. newPitchAxis = options.pitchAxis.clone();
  72013. newPitchAxis.normalize();
  72014. }
  72015. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  72016. this._transformYawPitch = BABYLON.Matrix.Identity();
  72017. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  72018. this._transformYawPitchInv = this._transformYawPitch.clone();
  72019. this._transformYawPitch.invert();
  72020. }
  72021. }
  72022. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  72023. this.upAxisSpace = BABYLON.Space.LOCAL;
  72024. }
  72025. }
  72026. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  72027. /**
  72028. * Get/set the minimum yaw angle that the bone can look to.
  72029. */
  72030. get: function () {
  72031. return this._minYaw;
  72032. },
  72033. set: function (value) {
  72034. this._minYaw = value;
  72035. this._minYawSin = Math.sin(value);
  72036. this._minYawCos = Math.cos(value);
  72037. if (this._maxYaw != null) {
  72038. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72039. this._yawRange = this._maxYaw - this._minYaw;
  72040. }
  72041. },
  72042. enumerable: true,
  72043. configurable: true
  72044. });
  72045. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  72046. /**
  72047. * Get/set the maximum yaw angle that the bone can look to.
  72048. */
  72049. get: function () {
  72050. return this._maxYaw;
  72051. },
  72052. set: function (value) {
  72053. this._maxYaw = value;
  72054. this._maxYawSin = Math.sin(value);
  72055. this._maxYawCos = Math.cos(value);
  72056. if (this._minYaw != null) {
  72057. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72058. this._yawRange = this._maxYaw - this._minYaw;
  72059. }
  72060. },
  72061. enumerable: true,
  72062. configurable: true
  72063. });
  72064. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  72065. /**
  72066. * Get/set the minimum pitch angle that the bone can look to.
  72067. */
  72068. get: function () {
  72069. return this._minPitch;
  72070. },
  72071. set: function (value) {
  72072. this._minPitch = value;
  72073. this._minPitchTan = Math.tan(value);
  72074. },
  72075. enumerable: true,
  72076. configurable: true
  72077. });
  72078. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  72079. /**
  72080. * Get/set the maximum pitch angle that the bone can look to.
  72081. */
  72082. get: function () {
  72083. return this._maxPitch;
  72084. },
  72085. set: function (value) {
  72086. this._maxPitch = value;
  72087. this._maxPitchTan = Math.tan(value);
  72088. },
  72089. enumerable: true,
  72090. configurable: true
  72091. });
  72092. /**
  72093. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  72094. */
  72095. BoneLookController.prototype.update = function () {
  72096. //skip the first frame when slerping so that the mesh rotation is correct
  72097. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  72098. this._firstFrameSkipped = true;
  72099. return;
  72100. }
  72101. var bone = this.bone;
  72102. var bonePos = BoneLookController._tmpVecs[0];
  72103. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  72104. var target = this.target;
  72105. var _tmpMat1 = BoneLookController._tmpMats[0];
  72106. var _tmpMat2 = BoneLookController._tmpMats[1];
  72107. var mesh = this.mesh;
  72108. var parentBone = bone.getParent();
  72109. var upAxis = BoneLookController._tmpVecs[1];
  72110. upAxis.copyFrom(this.upAxis);
  72111. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  72112. if (this._transformYawPitch) {
  72113. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  72114. }
  72115. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  72116. }
  72117. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  72118. mesh.getDirectionToRef(upAxis, upAxis);
  72119. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  72120. upAxis.normalize();
  72121. }
  72122. }
  72123. var checkYaw = false;
  72124. var checkPitch = false;
  72125. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  72126. checkYaw = true;
  72127. }
  72128. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  72129. checkPitch = true;
  72130. }
  72131. if (checkYaw || checkPitch) {
  72132. var spaceMat = BoneLookController._tmpMats[2];
  72133. var spaceMatInv = BoneLookController._tmpMats[3];
  72134. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  72135. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  72136. }
  72137. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  72138. spaceMat.copyFrom(mesh.getWorldMatrix());
  72139. }
  72140. else {
  72141. var forwardAxis = BoneLookController._tmpVecs[2];
  72142. forwardAxis.copyFrom(this._fowardAxis);
  72143. if (this._transformYawPitch) {
  72144. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  72145. }
  72146. if (parentBone) {
  72147. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  72148. }
  72149. else {
  72150. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  72151. }
  72152. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  72153. rightAxis.normalize();
  72154. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  72155. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  72156. }
  72157. spaceMat.invertToRef(spaceMatInv);
  72158. var xzlen = null;
  72159. if (checkPitch) {
  72160. var localTarget = BoneLookController._tmpVecs[3];
  72161. target.subtractToRef(bonePos, localTarget);
  72162. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72163. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72164. var pitch = Math.atan2(localTarget.y, xzlen);
  72165. var newPitch = pitch;
  72166. if (pitch > this._maxPitch) {
  72167. localTarget.y = this._maxPitchTan * xzlen;
  72168. newPitch = this._maxPitch;
  72169. }
  72170. else if (pitch < this._minPitch) {
  72171. localTarget.y = this._minPitchTan * xzlen;
  72172. newPitch = this._minPitch;
  72173. }
  72174. if (pitch != newPitch) {
  72175. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72176. localTarget.addInPlace(bonePos);
  72177. target = localTarget;
  72178. }
  72179. }
  72180. if (checkYaw) {
  72181. var localTarget = BoneLookController._tmpVecs[4];
  72182. target.subtractToRef(bonePos, localTarget);
  72183. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72184. var yaw = Math.atan2(localTarget.x, localTarget.z);
  72185. var newYaw = yaw;
  72186. if (yaw > this._maxYaw || yaw < this._minYaw) {
  72187. if (xzlen == null) {
  72188. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72189. }
  72190. if (this._yawRange > Math.PI) {
  72191. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  72192. localTarget.z = this._maxYawCos * xzlen;
  72193. localTarget.x = this._maxYawSin * xzlen;
  72194. newYaw = this._maxYaw;
  72195. }
  72196. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  72197. localTarget.z = this._minYawCos * xzlen;
  72198. localTarget.x = this._minYawSin * xzlen;
  72199. newYaw = this._minYaw;
  72200. }
  72201. }
  72202. else {
  72203. if (yaw > this._maxYaw) {
  72204. localTarget.z = this._maxYawCos * xzlen;
  72205. localTarget.x = this._maxYawSin * xzlen;
  72206. newYaw = this._maxYaw;
  72207. }
  72208. else if (yaw < this._minYaw) {
  72209. localTarget.z = this._minYawCos * xzlen;
  72210. localTarget.x = this._minYawSin * xzlen;
  72211. newYaw = this._minYaw;
  72212. }
  72213. }
  72214. }
  72215. if (this._slerping && this._yawRange > Math.PI) {
  72216. //are we going to be crossing into the min/max region?
  72217. var boneFwd = BoneLookController._tmpVecs[8];
  72218. boneFwd.copyFrom(BABYLON.Axis.Z);
  72219. if (this._transformYawPitch) {
  72220. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  72221. }
  72222. var boneRotMat = BoneLookController._tmpMats[4];
  72223. this._boneQuat.toRotationMatrix(boneRotMat);
  72224. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  72225. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  72226. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  72227. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  72228. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  72229. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  72230. if (angBtwTar > angBtwMidYaw) {
  72231. if (xzlen == null) {
  72232. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72233. }
  72234. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  72235. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  72236. if (angBtwMin < angBtwMax) {
  72237. newYaw = boneYaw + Math.PI * .75;
  72238. localTarget.z = Math.cos(newYaw) * xzlen;
  72239. localTarget.x = Math.sin(newYaw) * xzlen;
  72240. }
  72241. else {
  72242. newYaw = boneYaw - Math.PI * .75;
  72243. localTarget.z = Math.cos(newYaw) * xzlen;
  72244. localTarget.x = Math.sin(newYaw) * xzlen;
  72245. }
  72246. }
  72247. }
  72248. if (yaw != newYaw) {
  72249. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72250. localTarget.addInPlace(bonePos);
  72251. target = localTarget;
  72252. }
  72253. }
  72254. }
  72255. var zaxis = BoneLookController._tmpVecs[5];
  72256. var xaxis = BoneLookController._tmpVecs[6];
  72257. var yaxis = BoneLookController._tmpVecs[7];
  72258. var _tmpQuat = BoneLookController._tmpQuat;
  72259. target.subtractToRef(bonePos, zaxis);
  72260. zaxis.normalize();
  72261. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  72262. xaxis.normalize();
  72263. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  72264. yaxis.normalize();
  72265. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  72266. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  72267. return;
  72268. }
  72269. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  72270. return;
  72271. }
  72272. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  72273. return;
  72274. }
  72275. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  72276. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  72277. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  72278. }
  72279. if (this.slerpAmount < 1) {
  72280. if (!this._slerping) {
  72281. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  72282. }
  72283. if (this._transformYawPitch) {
  72284. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72285. }
  72286. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  72287. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  72288. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  72289. this._slerping = true;
  72290. }
  72291. else {
  72292. if (this._transformYawPitch) {
  72293. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72294. }
  72295. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  72296. this._slerping = false;
  72297. }
  72298. };
  72299. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  72300. var angDiff = ang2 - ang1;
  72301. angDiff %= Math.PI * 2;
  72302. if (angDiff > Math.PI) {
  72303. angDiff -= Math.PI * 2;
  72304. }
  72305. else if (angDiff < -Math.PI) {
  72306. angDiff += Math.PI * 2;
  72307. }
  72308. return angDiff;
  72309. };
  72310. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  72311. ang1 %= (2 * Math.PI);
  72312. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72313. ang2 %= (2 * Math.PI);
  72314. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72315. var ab = 0;
  72316. if (ang1 < ang2) {
  72317. ab = ang2 - ang1;
  72318. }
  72319. else {
  72320. ab = ang1 - ang2;
  72321. }
  72322. if (ab > Math.PI) {
  72323. ab = Math.PI * 2 - ab;
  72324. }
  72325. return ab;
  72326. };
  72327. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72328. ang %= (2 * Math.PI);
  72329. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72330. ang1 %= (2 * Math.PI);
  72331. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72332. ang2 %= (2 * Math.PI);
  72333. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72334. if (ang1 < ang2) {
  72335. if (ang > ang1 && ang < ang2) {
  72336. return true;
  72337. }
  72338. }
  72339. else {
  72340. if (ang > ang2 && ang < ang1) {
  72341. return true;
  72342. }
  72343. }
  72344. return false;
  72345. };
  72346. 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()];
  72347. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72348. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72349. return BoneLookController;
  72350. }());
  72351. BABYLON.BoneLookController = BoneLookController;
  72352. })(BABYLON || (BABYLON = {}));
  72353. //# sourceMappingURL=babylon.boneLookController.js.map
  72354. var BABYLON;
  72355. (function (BABYLON) {
  72356. var Skeleton = /** @class */ (function () {
  72357. function Skeleton(name, id, scene) {
  72358. this.name = name;
  72359. this.id = id;
  72360. this.bones = new Array();
  72361. this.needInitialSkinMatrix = false;
  72362. this._isDirty = true;
  72363. this._meshesWithPoseMatrix = new Array();
  72364. this._identity = BABYLON.Matrix.Identity();
  72365. this._ranges = {};
  72366. this._lastAbsoluteTransformsUpdateId = -1;
  72367. /**
  72368. * Specifies if the skeleton should be serialized.
  72369. */
  72370. this.doNotSerialize = false;
  72371. // Events
  72372. /**
  72373. * An event triggered before computing the skeleton's matrices
  72374. * @type {BABYLON.Observable}
  72375. */
  72376. this.onBeforeComputeObservable = new BABYLON.Observable();
  72377. this.bones = [];
  72378. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72379. scene.skeletons.push(this);
  72380. //make sure it will recalculate the matrix next time prepare is called.
  72381. this._isDirty = true;
  72382. }
  72383. // Members
  72384. Skeleton.prototype.getTransformMatrices = function (mesh) {
  72385. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  72386. return mesh._bonesTransformMatrices;
  72387. }
  72388. if (!this._transformMatrices) {
  72389. this.prepare();
  72390. }
  72391. return this._transformMatrices;
  72392. };
  72393. Skeleton.prototype.getScene = function () {
  72394. return this._scene;
  72395. };
  72396. // Methods
  72397. /**
  72398. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  72399. */
  72400. Skeleton.prototype.toString = function (fullDetails) {
  72401. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  72402. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  72403. if (fullDetails) {
  72404. ret += ", Ranges: {";
  72405. var first = true;
  72406. for (var name_1 in this._ranges) {
  72407. if (first) {
  72408. ret += ", ";
  72409. first = false;
  72410. }
  72411. ret += name_1;
  72412. }
  72413. ret += "}";
  72414. }
  72415. return ret;
  72416. };
  72417. /**
  72418. * Get bone's index searching by name
  72419. * @param {string} name is bone's name to search for
  72420. * @return {number} Indice of the bone. Returns -1 if not found
  72421. */
  72422. Skeleton.prototype.getBoneIndexByName = function (name) {
  72423. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  72424. if (this.bones[boneIndex].name === name) {
  72425. return boneIndex;
  72426. }
  72427. }
  72428. return -1;
  72429. };
  72430. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  72431. // check name not already in use
  72432. if (!this._ranges[name]) {
  72433. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  72434. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72435. if (this.bones[i].animations[0]) {
  72436. this.bones[i].animations[0].createRange(name, from, to);
  72437. }
  72438. }
  72439. }
  72440. };
  72441. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  72442. if (deleteFrames === void 0) { deleteFrames = true; }
  72443. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72444. if (this.bones[i].animations[0]) {
  72445. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  72446. }
  72447. }
  72448. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  72449. };
  72450. Skeleton.prototype.getAnimationRange = function (name) {
  72451. return this._ranges[name];
  72452. };
  72453. /**
  72454. * Returns as an Array, all AnimationRanges defined on this skeleton
  72455. */
  72456. Skeleton.prototype.getAnimationRanges = function () {
  72457. var animationRanges = [];
  72458. var name;
  72459. var i = 0;
  72460. for (name in this._ranges) {
  72461. animationRanges[i] = this._ranges[name];
  72462. i++;
  72463. }
  72464. return animationRanges;
  72465. };
  72466. /**
  72467. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  72468. */
  72469. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  72470. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72471. if (this._ranges[name] || !source.getAnimationRange(name)) {
  72472. return false;
  72473. }
  72474. var ret = true;
  72475. var frameOffset = this._getHighestAnimationFrame() + 1;
  72476. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  72477. var boneDict = {};
  72478. var sourceBones = source.bones;
  72479. var nBones;
  72480. var i;
  72481. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  72482. boneDict[sourceBones[i].name] = sourceBones[i];
  72483. }
  72484. if (this.bones.length !== sourceBones.length) {
  72485. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  72486. ret = false;
  72487. }
  72488. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  72489. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  72490. var boneName = this.bones[i].name;
  72491. var sourceBone = boneDict[boneName];
  72492. if (sourceBone) {
  72493. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  72494. }
  72495. else {
  72496. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  72497. ret = false;
  72498. }
  72499. }
  72500. // do not call createAnimationRange(), since it also is done to bones, which was already done
  72501. var range = source.getAnimationRange(name);
  72502. if (range) {
  72503. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  72504. }
  72505. return ret;
  72506. };
  72507. Skeleton.prototype.returnToRest = function () {
  72508. for (var index = 0; index < this.bones.length; index++) {
  72509. this.bones[index].returnToRest();
  72510. }
  72511. };
  72512. Skeleton.prototype._getHighestAnimationFrame = function () {
  72513. var ret = 0;
  72514. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72515. if (this.bones[i].animations[0]) {
  72516. var highest = this.bones[i].animations[0].getHighestFrame();
  72517. if (ret < highest) {
  72518. ret = highest;
  72519. }
  72520. }
  72521. }
  72522. return ret;
  72523. };
  72524. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  72525. var range = this.getAnimationRange(name);
  72526. if (!range) {
  72527. return null;
  72528. }
  72529. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  72530. };
  72531. Skeleton.prototype._markAsDirty = function () {
  72532. this._isDirty = true;
  72533. };
  72534. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  72535. this._meshesWithPoseMatrix.push(mesh);
  72536. };
  72537. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  72538. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  72539. if (index > -1) {
  72540. this._meshesWithPoseMatrix.splice(index, 1);
  72541. }
  72542. };
  72543. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  72544. this.onBeforeComputeObservable.notifyObservers(this);
  72545. for (var index = 0; index < this.bones.length; index++) {
  72546. var bone = this.bones[index];
  72547. var parentBone = bone.getParent();
  72548. if (parentBone) {
  72549. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  72550. }
  72551. else {
  72552. if (initialSkinMatrix) {
  72553. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  72554. }
  72555. else {
  72556. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  72557. }
  72558. }
  72559. if (bone._index !== -1) {
  72560. var mappedIndex = bone._index === null ? index : bone._index;
  72561. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  72562. }
  72563. }
  72564. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  72565. };
  72566. Skeleton.prototype.prepare = function () {
  72567. if (!this._isDirty) {
  72568. return;
  72569. }
  72570. if (this.needInitialSkinMatrix) {
  72571. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  72572. var mesh = this._meshesWithPoseMatrix[index];
  72573. var poseMatrix = mesh.getPoseMatrix();
  72574. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  72575. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72576. }
  72577. if (this._synchronizedWithMesh !== mesh) {
  72578. this._synchronizedWithMesh = mesh;
  72579. // Prepare bones
  72580. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  72581. var bone = this.bones[boneIndex];
  72582. if (!bone.getParent()) {
  72583. var matrix = bone.getBaseMatrix();
  72584. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  72585. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  72586. }
  72587. }
  72588. }
  72589. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  72590. }
  72591. }
  72592. else {
  72593. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  72594. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72595. }
  72596. this._computeTransformMatrices(this._transformMatrices, null);
  72597. }
  72598. this._isDirty = false;
  72599. this._scene._activeBones.addCount(this.bones.length, false);
  72600. };
  72601. Skeleton.prototype.getAnimatables = function () {
  72602. if (!this._animatables || this._animatables.length !== this.bones.length) {
  72603. this._animatables = [];
  72604. for (var index = 0; index < this.bones.length; index++) {
  72605. this._animatables.push(this.bones[index]);
  72606. }
  72607. }
  72608. return this._animatables;
  72609. };
  72610. Skeleton.prototype.clone = function (name, id) {
  72611. var result = new Skeleton(name, id || name, this._scene);
  72612. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72613. for (var index = 0; index < this.bones.length; index++) {
  72614. var source = this.bones[index];
  72615. var parentBone = null;
  72616. var parent_1 = source.getParent();
  72617. if (parent_1) {
  72618. var parentIndex = this.bones.indexOf(parent_1);
  72619. parentBone = result.bones[parentIndex];
  72620. }
  72621. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  72622. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  72623. }
  72624. if (this._ranges) {
  72625. result._ranges = {};
  72626. for (var rangeName in this._ranges) {
  72627. var range = this._ranges[rangeName];
  72628. if (range) {
  72629. result._ranges[rangeName] = range.clone();
  72630. }
  72631. }
  72632. }
  72633. this._isDirty = true;
  72634. return result;
  72635. };
  72636. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  72637. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  72638. this.bones.forEach(function (bone) {
  72639. bone.animations.forEach(function (animation) {
  72640. animation.enableBlending = true;
  72641. animation.blendingSpeed = blendingSpeed;
  72642. });
  72643. });
  72644. };
  72645. Skeleton.prototype.dispose = function () {
  72646. this._meshesWithPoseMatrix = [];
  72647. // Animations
  72648. this.getScene().stopAnimation(this);
  72649. // Remove from scene
  72650. this.getScene().removeSkeleton(this);
  72651. };
  72652. Skeleton.prototype.serialize = function () {
  72653. var serializationObject = {};
  72654. serializationObject.name = this.name;
  72655. serializationObject.id = this.id;
  72656. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  72657. serializationObject.bones = [];
  72658. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72659. for (var index = 0; index < this.bones.length; index++) {
  72660. var bone = this.bones[index];
  72661. var parent_2 = bone.getParent();
  72662. var serializedBone = {
  72663. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  72664. name: bone.name,
  72665. matrix: bone.getBaseMatrix().toArray(),
  72666. rest: bone.getRestPose().toArray()
  72667. };
  72668. serializationObject.bones.push(serializedBone);
  72669. if (bone.length) {
  72670. serializedBone.length = bone.length;
  72671. }
  72672. if (bone.animations && bone.animations.length > 0) {
  72673. serializedBone.animation = bone.animations[0].serialize();
  72674. }
  72675. serializationObject.ranges = [];
  72676. for (var name in this._ranges) {
  72677. var source = this._ranges[name];
  72678. if (!source) {
  72679. continue;
  72680. }
  72681. var range = {};
  72682. range.name = name;
  72683. range.from = source.from;
  72684. range.to = source.to;
  72685. serializationObject.ranges.push(range);
  72686. }
  72687. }
  72688. return serializationObject;
  72689. };
  72690. Skeleton.Parse = function (parsedSkeleton, scene) {
  72691. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  72692. if (parsedSkeleton.dimensionsAtRest) {
  72693. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  72694. }
  72695. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  72696. var index;
  72697. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  72698. var parsedBone = parsedSkeleton.bones[index];
  72699. var parentBone = null;
  72700. if (parsedBone.parentBoneIndex > -1) {
  72701. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  72702. }
  72703. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  72704. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  72705. if (parsedBone.length) {
  72706. bone.length = parsedBone.length;
  72707. }
  72708. if (parsedBone.animation) {
  72709. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  72710. }
  72711. }
  72712. // placed after bones, so createAnimationRange can cascade down
  72713. if (parsedSkeleton.ranges) {
  72714. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  72715. var data = parsedSkeleton.ranges[index];
  72716. skeleton.createAnimationRange(data.name, data.from, data.to);
  72717. }
  72718. }
  72719. return skeleton;
  72720. };
  72721. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  72722. if (forceUpdate === void 0) { forceUpdate = false; }
  72723. var renderId = this._scene.getRenderId();
  72724. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  72725. this.bones[0].computeAbsoluteTransforms();
  72726. this._lastAbsoluteTransformsUpdateId = renderId;
  72727. }
  72728. };
  72729. Skeleton.prototype.getPoseMatrix = function () {
  72730. var poseMatrix = null;
  72731. if (this._meshesWithPoseMatrix.length > 0) {
  72732. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  72733. }
  72734. return poseMatrix;
  72735. };
  72736. Skeleton.prototype.sortBones = function () {
  72737. var bones = new Array();
  72738. var visited = new Array(this.bones.length);
  72739. for (var index = 0; index < this.bones.length; index++) {
  72740. this._sortBones(index, bones, visited);
  72741. }
  72742. this.bones = bones;
  72743. };
  72744. Skeleton.prototype._sortBones = function (index, bones, visited) {
  72745. if (visited[index]) {
  72746. return;
  72747. }
  72748. visited[index] = true;
  72749. var bone = this.bones[index];
  72750. if (bone._index === undefined) {
  72751. bone._index = index;
  72752. }
  72753. var parentBone = bone.getParent();
  72754. if (parentBone) {
  72755. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  72756. }
  72757. bones.push(bone);
  72758. };
  72759. return Skeleton;
  72760. }());
  72761. BABYLON.Skeleton = Skeleton;
  72762. })(BABYLON || (BABYLON = {}));
  72763. //# sourceMappingURL=babylon.skeleton.js.map
  72764. var BABYLON;
  72765. (function (BABYLON) {
  72766. var SphericalPolynomial = /** @class */ (function () {
  72767. function SphericalPolynomial() {
  72768. this.x = BABYLON.Vector3.Zero();
  72769. this.y = BABYLON.Vector3.Zero();
  72770. this.z = BABYLON.Vector3.Zero();
  72771. this.xx = BABYLON.Vector3.Zero();
  72772. this.yy = BABYLON.Vector3.Zero();
  72773. this.zz = BABYLON.Vector3.Zero();
  72774. this.xy = BABYLON.Vector3.Zero();
  72775. this.yz = BABYLON.Vector3.Zero();
  72776. this.zx = BABYLON.Vector3.Zero();
  72777. }
  72778. SphericalPolynomial.prototype.addAmbient = function (color) {
  72779. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72780. this.xx = this.xx.add(colorVector);
  72781. this.yy = this.yy.add(colorVector);
  72782. this.zz = this.zz.add(colorVector);
  72783. };
  72784. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  72785. var result = new SphericalPolynomial();
  72786. result.x = harmonics.L11.scale(1.02333);
  72787. result.y = harmonics.L1_1.scale(1.02333);
  72788. result.z = harmonics.L10.scale(1.02333);
  72789. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  72790. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  72791. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  72792. result.yz = harmonics.L2_1.scale(0.858086);
  72793. result.zx = harmonics.L21.scale(0.858086);
  72794. result.xy = harmonics.L2_2.scale(0.858086);
  72795. result.scale(1.0 / Math.PI);
  72796. return result;
  72797. };
  72798. SphericalPolynomial.prototype.scale = function (scale) {
  72799. this.x = this.x.scale(scale);
  72800. this.y = this.y.scale(scale);
  72801. this.z = this.z.scale(scale);
  72802. this.xx = this.xx.scale(scale);
  72803. this.yy = this.yy.scale(scale);
  72804. this.zz = this.zz.scale(scale);
  72805. this.yz = this.yz.scale(scale);
  72806. this.zx = this.zx.scale(scale);
  72807. this.xy = this.xy.scale(scale);
  72808. };
  72809. return SphericalPolynomial;
  72810. }());
  72811. BABYLON.SphericalPolynomial = SphericalPolynomial;
  72812. var SphericalHarmonics = /** @class */ (function () {
  72813. function SphericalHarmonics() {
  72814. this.L00 = BABYLON.Vector3.Zero();
  72815. this.L1_1 = BABYLON.Vector3.Zero();
  72816. this.L10 = BABYLON.Vector3.Zero();
  72817. this.L11 = BABYLON.Vector3.Zero();
  72818. this.L2_2 = BABYLON.Vector3.Zero();
  72819. this.L2_1 = BABYLON.Vector3.Zero();
  72820. this.L20 = BABYLON.Vector3.Zero();
  72821. this.L21 = BABYLON.Vector3.Zero();
  72822. this.L22 = BABYLON.Vector3.Zero();
  72823. }
  72824. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  72825. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72826. var c = colorVector.scale(deltaSolidAngle);
  72827. this.L00 = this.L00.add(c.scale(0.282095));
  72828. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  72829. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  72830. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  72831. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  72832. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  72833. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  72834. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  72835. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  72836. };
  72837. SphericalHarmonics.prototype.scale = function (scale) {
  72838. this.L00 = this.L00.scale(scale);
  72839. this.L1_1 = this.L1_1.scale(scale);
  72840. this.L10 = this.L10.scale(scale);
  72841. this.L11 = this.L11.scale(scale);
  72842. this.L2_2 = this.L2_2.scale(scale);
  72843. this.L2_1 = this.L2_1.scale(scale);
  72844. this.L20 = this.L20.scale(scale);
  72845. this.L21 = this.L21.scale(scale);
  72846. this.L22 = this.L22.scale(scale);
  72847. };
  72848. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  72849. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  72850. //
  72851. // E_lm = A_l * L_lm
  72852. //
  72853. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  72854. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  72855. // the scaling factors are given in equation 9.
  72856. // Constant (Band 0)
  72857. this.L00 = this.L00.scale(3.141593);
  72858. // Linear (Band 1)
  72859. this.L1_1 = this.L1_1.scale(2.094395);
  72860. this.L10 = this.L10.scale(2.094395);
  72861. this.L11 = this.L11.scale(2.094395);
  72862. // Quadratic (Band 2)
  72863. this.L2_2 = this.L2_2.scale(0.785398);
  72864. this.L2_1 = this.L2_1.scale(0.785398);
  72865. this.L20 = this.L20.scale(0.785398);
  72866. this.L21 = this.L21.scale(0.785398);
  72867. this.L22 = this.L22.scale(0.785398);
  72868. };
  72869. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  72870. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  72871. // L = (1/pi) * E * rho
  72872. //
  72873. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  72874. this.scale(1.0 / Math.PI);
  72875. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  72876. // (The pixel shader must apply albedo after texture fetches, etc).
  72877. };
  72878. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  72879. var result = new SphericalHarmonics();
  72880. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  72881. result.L1_1 = polynomial.y.scale(0.977204);
  72882. result.L10 = polynomial.z.scale(0.977204);
  72883. result.L11 = polynomial.x.scale(0.977204);
  72884. result.L2_2 = polynomial.xy.scale(1.16538);
  72885. result.L2_1 = polynomial.yz.scale(1.16538);
  72886. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  72887. result.L21 = polynomial.zx.scale(1.16538);
  72888. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  72889. result.scale(Math.PI);
  72890. return result;
  72891. };
  72892. return SphericalHarmonics;
  72893. }());
  72894. BABYLON.SphericalHarmonics = SphericalHarmonics;
  72895. })(BABYLON || (BABYLON = {}));
  72896. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  72897. var BABYLON;
  72898. (function (BABYLON) {
  72899. var FileFaceOrientation = /** @class */ (function () {
  72900. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  72901. this.name = name;
  72902. this.worldAxisForNormal = worldAxisForNormal;
  72903. this.worldAxisForFileX = worldAxisForFileX;
  72904. this.worldAxisForFileY = worldAxisForFileY;
  72905. }
  72906. return FileFaceOrientation;
  72907. }());
  72908. ;
  72909. /**
  72910. * Helper class dealing with the extraction of spherical polynomial dataArray
  72911. * from a cube map.
  72912. */
  72913. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  72914. function CubeMapToSphericalPolynomialTools() {
  72915. }
  72916. /**
  72917. * Converts a texture to the according Spherical Polynomial data.
  72918. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72919. *
  72920. * @param texture The texture to extract the information from.
  72921. * @return The Spherical Polynomial data.
  72922. */
  72923. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  72924. if (!texture.isCube) {
  72925. // Only supports cube Textures currently.
  72926. return null;
  72927. }
  72928. var size = texture.getSize().width;
  72929. var right = texture.readPixels(0);
  72930. var left = texture.readPixels(1);
  72931. var up;
  72932. var down;
  72933. if (texture.isRenderTarget) {
  72934. up = texture.readPixels(3);
  72935. down = texture.readPixels(2);
  72936. }
  72937. else {
  72938. up = texture.readPixels(2);
  72939. down = texture.readPixels(3);
  72940. }
  72941. var front = texture.readPixels(4);
  72942. var back = texture.readPixels(5);
  72943. var gammaSpace = texture.gammaSpace;
  72944. // Always read as RGBA.
  72945. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  72946. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72947. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72948. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72949. }
  72950. var cubeInfo = {
  72951. size: size,
  72952. right: right,
  72953. left: left,
  72954. up: up,
  72955. down: down,
  72956. front: front,
  72957. back: back,
  72958. format: format,
  72959. type: type,
  72960. gammaSpace: gammaSpace,
  72961. };
  72962. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  72963. };
  72964. /**
  72965. * Converts a cubemap to the according Spherical Polynomial data.
  72966. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72967. *
  72968. * @param cubeInfo The Cube map to extract the information from.
  72969. * @return The Spherical Polynomial data.
  72970. */
  72971. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  72972. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  72973. var totalSolidAngle = 0.0;
  72974. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  72975. var du = 2.0 / cubeInfo.size;
  72976. var dv = du;
  72977. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  72978. var minUV = du * 0.5 - 1.0;
  72979. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72980. var fileFace = this.FileFaces[faceIndex];
  72981. var dataArray = cubeInfo[fileFace.name];
  72982. var v = minUV;
  72983. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  72984. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  72985. // Because SP is still linear, so summation is fine in that basis.
  72986. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  72987. for (var y = 0; y < cubeInfo.size; y++) {
  72988. var u = minUV;
  72989. for (var x = 0; x < cubeInfo.size; x++) {
  72990. // World direction (not normalised)
  72991. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  72992. worldDirection.normalize();
  72993. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  72994. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  72995. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  72996. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  72997. // Handle Integer types.
  72998. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72999. r /= 255;
  73000. g /= 255;
  73001. b /= 255;
  73002. }
  73003. // Handle Gamma space textures.
  73004. if (cubeInfo.gammaSpace) {
  73005. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  73006. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  73007. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  73008. }
  73009. var color = new BABYLON.Color3(r, g, b);
  73010. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  73011. totalSolidAngle += deltaSolidAngle;
  73012. u += du;
  73013. }
  73014. v += dv;
  73015. }
  73016. }
  73017. // Solid angle for entire sphere is 4*pi
  73018. var sphereSolidAngle = 4.0 * Math.PI;
  73019. // Adjust the solid angle to allow for how many faces we processed.
  73020. var facesProcessed = 6.0;
  73021. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  73022. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  73023. // This is needed because the numerical integration over the cube uses a
  73024. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  73025. // and also to compensate for accumulative error due to float precision in the summation.
  73026. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  73027. sphericalHarmonics.scale(correctionFactor);
  73028. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  73029. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  73030. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  73031. };
  73032. CubeMapToSphericalPolynomialTools.FileFaces = [
  73033. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  73034. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  73035. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  73036. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  73037. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  73038. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  73039. ];
  73040. return CubeMapToSphericalPolynomialTools;
  73041. }());
  73042. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  73043. })(BABYLON || (BABYLON = {}));
  73044. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  73045. var BABYLON;
  73046. (function (BABYLON) {
  73047. /**
  73048. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  73049. */
  73050. var PanoramaToCubeMapTools = /** @class */ (function () {
  73051. function PanoramaToCubeMapTools() {
  73052. }
  73053. /**
  73054. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  73055. *
  73056. * @param float32Array The source data.
  73057. * @param inputWidth The width of the input panorama.
  73058. * @param inputhHeight The height of the input panorama.
  73059. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  73060. * @return The cubemap data
  73061. */
  73062. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  73063. if (!float32Array) {
  73064. throw "ConvertPanoramaToCubemap: input cannot be null";
  73065. }
  73066. if (float32Array.length != inputWidth * inputHeight * 3) {
  73067. throw "ConvertPanoramaToCubemap: input size is wrong";
  73068. }
  73069. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  73070. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  73071. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  73072. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  73073. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  73074. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  73075. return {
  73076. front: textureFront,
  73077. back: textureBack,
  73078. left: textureLeft,
  73079. right: textureRight,
  73080. up: textureUp,
  73081. down: textureDown,
  73082. size: size,
  73083. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  73084. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  73085. gammaSpace: false,
  73086. };
  73087. };
  73088. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  73089. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  73090. var textureArray = new Float32Array(buffer);
  73091. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  73092. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  73093. var dy = 1 / texSize;
  73094. var fy = 0;
  73095. for (var y = 0; y < texSize; y++) {
  73096. var xv1 = faceData[0];
  73097. var xv2 = faceData[2];
  73098. for (var x = 0; x < texSize; x++) {
  73099. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  73100. v.normalize();
  73101. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  73102. // 3 channels per pixels
  73103. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  73104. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  73105. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  73106. xv1 = xv1.add(rotDX1);
  73107. xv2 = xv2.add(rotDX2);
  73108. }
  73109. fy += dy;
  73110. }
  73111. return textureArray;
  73112. };
  73113. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  73114. var theta = Math.atan2(vDir.z, vDir.x);
  73115. var phi = Math.acos(vDir.y);
  73116. while (theta < -Math.PI)
  73117. theta += 2 * Math.PI;
  73118. while (theta > Math.PI)
  73119. theta -= 2 * Math.PI;
  73120. var dx = theta / Math.PI;
  73121. var dy = phi / Math.PI;
  73122. // recenter.
  73123. dx = dx * 0.5 + 0.5;
  73124. var px = Math.round(dx * inputWidth);
  73125. if (px < 0)
  73126. px = 0;
  73127. else if (px >= inputWidth)
  73128. px = inputWidth - 1;
  73129. var py = Math.round(dy * inputHeight);
  73130. if (py < 0)
  73131. py = 0;
  73132. else if (py >= inputHeight)
  73133. py = inputHeight - 1;
  73134. var inputY = (inputHeight - py - 1);
  73135. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  73136. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  73137. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  73138. return {
  73139. r: r,
  73140. g: g,
  73141. b: b
  73142. };
  73143. };
  73144. PanoramaToCubeMapTools.FACE_FRONT = [
  73145. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73146. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73147. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73148. new BABYLON.Vector3(1.0, 1.0, -1.0)
  73149. ];
  73150. PanoramaToCubeMapTools.FACE_BACK = [
  73151. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73152. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73153. new BABYLON.Vector3(1.0, 1.0, 1.0),
  73154. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  73155. ];
  73156. PanoramaToCubeMapTools.FACE_RIGHT = [
  73157. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73158. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73159. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73160. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73161. ];
  73162. PanoramaToCubeMapTools.FACE_LEFT = [
  73163. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73164. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73165. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73166. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  73167. ];
  73168. PanoramaToCubeMapTools.FACE_DOWN = [
  73169. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73170. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73171. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73172. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73173. ];
  73174. PanoramaToCubeMapTools.FACE_UP = [
  73175. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73176. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73177. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73178. new BABYLON.Vector3(1.0, -1.0, -1.0)
  73179. ];
  73180. return PanoramaToCubeMapTools;
  73181. }());
  73182. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  73183. })(BABYLON || (BABYLON = {}));
  73184. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  73185. var BABYLON;
  73186. (function (BABYLON) {
  73187. ;
  73188. /**
  73189. * This groups tools to convert HDR texture to native colors array.
  73190. */
  73191. var HDRTools = /** @class */ (function () {
  73192. function HDRTools() {
  73193. }
  73194. HDRTools.Ldexp = function (mantissa, exponent) {
  73195. if (exponent > 1023) {
  73196. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  73197. }
  73198. if (exponent < -1074) {
  73199. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  73200. }
  73201. return mantissa * Math.pow(2, exponent);
  73202. };
  73203. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  73204. if (exponent > 0) {
  73205. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  73206. float32array[index + 0] = red * exponent;
  73207. float32array[index + 1] = green * exponent;
  73208. float32array[index + 2] = blue * exponent;
  73209. }
  73210. else {
  73211. float32array[index + 0] = 0;
  73212. float32array[index + 1] = 0;
  73213. float32array[index + 2] = 0;
  73214. }
  73215. };
  73216. HDRTools.readStringLine = function (uint8array, startIndex) {
  73217. var line = "";
  73218. var character = "";
  73219. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  73220. character = String.fromCharCode(uint8array[i]);
  73221. if (character == "\n") {
  73222. break;
  73223. }
  73224. line += character;
  73225. }
  73226. return line;
  73227. };
  73228. /**
  73229. * Reads header information from an RGBE texture stored in a native array.
  73230. * More information on this format are available here:
  73231. * https://en.wikipedia.org/wiki/RGBE_image_format
  73232. *
  73233. * @param uint8array The binary file stored in native array.
  73234. * @return The header information.
  73235. */
  73236. HDRTools.RGBE_ReadHeader = function (uint8array) {
  73237. var height = 0;
  73238. var width = 0;
  73239. var line = this.readStringLine(uint8array, 0);
  73240. if (line[0] != '#' || line[1] != '?') {
  73241. throw "Bad HDR Format.";
  73242. }
  73243. var endOfHeader = false;
  73244. var findFormat = false;
  73245. var lineIndex = 0;
  73246. do {
  73247. lineIndex += (line.length + 1);
  73248. line = this.readStringLine(uint8array, lineIndex);
  73249. if (line == "FORMAT=32-bit_rle_rgbe") {
  73250. findFormat = true;
  73251. }
  73252. else if (line.length == 0) {
  73253. endOfHeader = true;
  73254. }
  73255. } while (!endOfHeader);
  73256. if (!findFormat) {
  73257. throw "HDR Bad header format, unsupported FORMAT";
  73258. }
  73259. lineIndex += (line.length + 1);
  73260. line = this.readStringLine(uint8array, lineIndex);
  73261. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  73262. var match = sizeRegexp.exec(line);
  73263. // TODO. Support +Y and -X if needed.
  73264. if (!match || match.length < 3) {
  73265. throw "HDR Bad header format, no size";
  73266. }
  73267. width = parseInt(match[2]);
  73268. height = parseInt(match[1]);
  73269. if (width < 8 || width > 0x7fff) {
  73270. throw "HDR Bad header format, unsupported size";
  73271. }
  73272. lineIndex += (line.length + 1);
  73273. return {
  73274. height: height,
  73275. width: width,
  73276. dataPosition: lineIndex
  73277. };
  73278. };
  73279. /**
  73280. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  73281. * This RGBE texture needs to store the information as a panorama.
  73282. *
  73283. * More information on this format are available here:
  73284. * https://en.wikipedia.org/wiki/RGBE_image_format
  73285. *
  73286. * @param buffer The binary file stored in an array buffer.
  73287. * @param size The expected size of the extracted cubemap.
  73288. * @return The Cube Map information.
  73289. */
  73290. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  73291. var uint8array = new Uint8Array(buffer);
  73292. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  73293. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73294. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  73295. return cubeMapData;
  73296. };
  73297. /**
  73298. * Returns the pixels data extracted from an RGBE texture.
  73299. * This pixels will be stored left to right up to down in the R G B order in one array.
  73300. *
  73301. * More information on this format are available here:
  73302. * https://en.wikipedia.org/wiki/RGBE_image_format
  73303. *
  73304. * @param uint8array The binary file stored in an array buffer.
  73305. * @param hdrInfo The header information of the file.
  73306. * @return The pixels data in RGB right to left up to down order.
  73307. */
  73308. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  73309. // Keep for multi format supports.
  73310. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73311. };
  73312. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  73313. var num_scanlines = hdrInfo.height;
  73314. var scanline_width = hdrInfo.width;
  73315. var a, b, c, d, count;
  73316. var dataIndex = hdrInfo.dataPosition;
  73317. var index = 0, endIndex = 0, i = 0;
  73318. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73319. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73320. // 3 channels of 4 bytes per pixel in float.
  73321. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73322. var resultArray = new Float32Array(resultBuffer);
  73323. // read in each successive scanline
  73324. while (num_scanlines > 0) {
  73325. a = uint8array[dataIndex++];
  73326. b = uint8array[dataIndex++];
  73327. c = uint8array[dataIndex++];
  73328. d = uint8array[dataIndex++];
  73329. if (a != 2 || b != 2 || (c & 0x80)) {
  73330. // this file is not run length encoded
  73331. throw "HDR Bad header format, not RLE";
  73332. }
  73333. if (((c << 8) | d) != scanline_width) {
  73334. throw "HDR Bad header format, wrong scan line width";
  73335. }
  73336. index = 0;
  73337. // read each of the four channels for the scanline into the buffer
  73338. for (i = 0; i < 4; i++) {
  73339. endIndex = (i + 1) * scanline_width;
  73340. while (index < endIndex) {
  73341. a = uint8array[dataIndex++];
  73342. b = uint8array[dataIndex++];
  73343. if (a > 128) {
  73344. // a run of the same value
  73345. count = a - 128;
  73346. if ((count == 0) || (count > endIndex - index)) {
  73347. throw "HDR Bad Format, bad scanline data (run)";
  73348. }
  73349. while (count-- > 0) {
  73350. scanLineArray[index++] = b;
  73351. }
  73352. }
  73353. else {
  73354. // a non-run
  73355. count = a;
  73356. if ((count == 0) || (count > endIndex - index)) {
  73357. throw "HDR Bad Format, bad scanline data (non-run)";
  73358. }
  73359. scanLineArray[index++] = b;
  73360. if (--count > 0) {
  73361. for (var j = 0; j < count; j++) {
  73362. scanLineArray[index++] = uint8array[dataIndex++];
  73363. }
  73364. }
  73365. }
  73366. }
  73367. }
  73368. // now convert data from buffer into floats
  73369. for (i = 0; i < scanline_width; i++) {
  73370. a = scanLineArray[i];
  73371. b = scanLineArray[i + scanline_width];
  73372. c = scanLineArray[i + 2 * scanline_width];
  73373. d = scanLineArray[i + 3 * scanline_width];
  73374. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  73375. }
  73376. num_scanlines--;
  73377. }
  73378. return resultArray;
  73379. };
  73380. return HDRTools;
  73381. }());
  73382. BABYLON.HDRTools = HDRTools;
  73383. })(BABYLON || (BABYLON = {}));
  73384. //# sourceMappingURL=babylon.hdr.js.map
  73385. var BABYLON;
  73386. (function (BABYLON) {
  73387. /**
  73388. * This represents a texture coming from an HDR input.
  73389. *
  73390. * The only supported format is currently panorama picture stored in RGBE format.
  73391. * Example of such files can be found on HDRLib: http://hdrlib.com/
  73392. */
  73393. var HDRCubeTexture = /** @class */ (function (_super) {
  73394. __extends(HDRCubeTexture, _super);
  73395. /**
  73396. * Instantiates an HDRTexture from the following parameters.
  73397. *
  73398. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  73399. * @param scene The scene the texture will be used in
  73400. * @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.
  73401. * @param noMipmap Forces to not generate the mipmap if true
  73402. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  73403. * @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)
  73404. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  73405. */
  73406. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  73407. if (noMipmap === void 0) { noMipmap = false; }
  73408. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73409. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73410. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73411. if (onLoad === void 0) { onLoad = null; }
  73412. if (onError === void 0) { onError = null; }
  73413. var _this = _super.call(this, scene) || this;
  73414. _this._useInGammaSpace = false;
  73415. _this._generateHarmonics = true;
  73416. _this._isBABYLONPreprocessed = false;
  73417. _this._onLoad = null;
  73418. _this._onError = null;
  73419. /**
  73420. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  73421. */
  73422. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73423. /**
  73424. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  73425. * This is usefull at run time to apply the good shader.
  73426. */
  73427. _this.isPMREM = false;
  73428. _this._isBlocking = true;
  73429. /**
  73430. * Gets or sets the center of the bounding box associated with the cube texture
  73431. * It must define where the camera used to render the texture was set
  73432. */
  73433. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73434. if (!url) {
  73435. return _this;
  73436. }
  73437. _this.name = url;
  73438. _this.url = url;
  73439. _this.hasAlpha = false;
  73440. _this.isCube = true;
  73441. _this._textureMatrix = BABYLON.Matrix.Identity();
  73442. _this._onLoad = onLoad;
  73443. _this._onError = onError;
  73444. _this.gammaSpace = false;
  73445. var caps = scene.getEngine().getCaps();
  73446. if (size) {
  73447. _this._isBABYLONPreprocessed = false;
  73448. _this._noMipmap = noMipmap;
  73449. _this._size = size;
  73450. _this._useInGammaSpace = useInGammaSpace;
  73451. _this._usePMREMGenerator = usePMREMGenerator &&
  73452. caps.textureLOD &&
  73453. caps.textureFloat &&
  73454. !_this._useInGammaSpace;
  73455. }
  73456. else {
  73457. _this._isBABYLONPreprocessed = true;
  73458. _this._noMipmap = false;
  73459. _this._useInGammaSpace = false;
  73460. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  73461. !_this._useInGammaSpace;
  73462. }
  73463. _this.isPMREM = _this._usePMREMGenerator;
  73464. _this._texture = _this._getFromCache(url, _this._noMipmap);
  73465. if (!_this._texture) {
  73466. if (!scene.useDelayedTextureLoading) {
  73467. _this.loadTexture();
  73468. }
  73469. else {
  73470. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73471. }
  73472. }
  73473. return _this;
  73474. }
  73475. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  73476. /**
  73477. * Gets wether or not the texture is blocking during loading.
  73478. */
  73479. get: function () {
  73480. return this._isBlocking;
  73481. },
  73482. /**
  73483. * Sets wether or not the texture is blocking during loading.
  73484. */
  73485. set: function (value) {
  73486. this._isBlocking = value;
  73487. },
  73488. enumerable: true,
  73489. configurable: true
  73490. });
  73491. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  73492. get: function () {
  73493. return this._boundingBoxSize;
  73494. },
  73495. /**
  73496. * Gets or sets the size of the bounding box associated with the cube texture
  73497. * When defined, the cubemap will switch to local mode
  73498. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73499. * @example https://www.babylonjs-playground.com/#RNASML
  73500. */
  73501. set: function (value) {
  73502. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73503. return;
  73504. }
  73505. this._boundingBoxSize = value;
  73506. var scene = this.getScene();
  73507. if (scene) {
  73508. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73509. }
  73510. },
  73511. enumerable: true,
  73512. configurable: true
  73513. });
  73514. /**
  73515. * Occurs when the file is a preprocessed .babylon.hdr file.
  73516. */
  73517. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  73518. var _this = this;
  73519. var mipLevels = 0;
  73520. var floatArrayView = null;
  73521. var scene = this.getScene();
  73522. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  73523. var mips = new Array();
  73524. if (!floatArrayView) {
  73525. return mips;
  73526. }
  73527. var startIndex = 30;
  73528. for (var level = 0; level < mipLevels; level++) {
  73529. mips.push([]);
  73530. // Fill each pixel of the mip level.
  73531. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  73532. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73533. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  73534. mips[level].push(faceData);
  73535. startIndex += faceSize;
  73536. }
  73537. }
  73538. return mips;
  73539. } : null;
  73540. var callback = function (buffer) {
  73541. var scene = _this.getScene();
  73542. if (!scene) {
  73543. return null;
  73544. }
  73545. // Create Native Array Views
  73546. var intArrayView = new Int32Array(buffer);
  73547. floatArrayView = new Float32Array(buffer);
  73548. // Fill header.
  73549. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  73550. _this._size = intArrayView[1]; // CubeMap max mip face size.
  73551. // Update Texture Information.
  73552. if (!_this._texture) {
  73553. return null;
  73554. }
  73555. _this._texture.updateSize(_this._size, _this._size);
  73556. // Fill polynomial information.
  73557. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  73558. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  73559. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  73560. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  73561. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  73562. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  73563. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  73564. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  73565. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  73566. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  73567. _this.sphericalPolynomial = sphericalPolynomial;
  73568. // Fill pixel data.
  73569. mipLevels = intArrayView[29]; // Number of mip levels.
  73570. var startIndex = 30;
  73571. var data = [];
  73572. var faceSize = Math.pow(_this._size, 2) * 3;
  73573. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73574. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  73575. startIndex += faceSize;
  73576. }
  73577. var results = [];
  73578. var byteArray = null;
  73579. // Push each faces.
  73580. for (var k = 0; k < 6; k++) {
  73581. var dataFace = null;
  73582. // To be deprecated.
  73583. if (version === 1) {
  73584. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  73585. dataFace = data[j];
  73586. }
  73587. // If special cases.
  73588. if (!mipmapGenerator && dataFace) {
  73589. if (!scene.getEngine().getCaps().textureFloat) {
  73590. // 3 channels of 1 bytes per pixel in bytes.
  73591. var byteBuffer = new ArrayBuffer(faceSize);
  73592. byteArray = new Uint8Array(byteBuffer);
  73593. }
  73594. for (var i = 0; i < _this._size * _this._size; i++) {
  73595. // Put in gamma space if requested.
  73596. if (_this._useInGammaSpace) {
  73597. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73598. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73599. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73600. }
  73601. // Convert to int texture for fallback.
  73602. if (byteArray) {
  73603. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73604. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73605. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73606. // May use luminance instead if the result is not accurate.
  73607. var max = Math.max(Math.max(r, g), b);
  73608. if (max > 255) {
  73609. var scale = 255 / max;
  73610. r *= scale;
  73611. g *= scale;
  73612. b *= scale;
  73613. }
  73614. byteArray[(i * 3) + 0] = r;
  73615. byteArray[(i * 3) + 1] = g;
  73616. byteArray[(i * 3) + 2] = b;
  73617. }
  73618. }
  73619. }
  73620. // Fill the array accordingly.
  73621. if (byteArray) {
  73622. results.push(byteArray);
  73623. }
  73624. else {
  73625. results.push(dataFace);
  73626. }
  73627. }
  73628. return results;
  73629. };
  73630. if (scene) {
  73631. 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);
  73632. }
  73633. };
  73634. /**
  73635. * Occurs when the file is raw .hdr file.
  73636. */
  73637. HDRCubeTexture.prototype.loadHDRTexture = function () {
  73638. var _this = this;
  73639. var callback = function (buffer) {
  73640. var scene = _this.getScene();
  73641. if (!scene) {
  73642. return null;
  73643. }
  73644. // Extract the raw linear data.
  73645. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  73646. // Generate harmonics if needed.
  73647. if (_this._generateHarmonics) {
  73648. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  73649. _this.sphericalPolynomial = sphericalPolynomial;
  73650. }
  73651. var results = [];
  73652. var byteArray = null;
  73653. // Push each faces.
  73654. for (var j = 0; j < 6; j++) {
  73655. // Create uintarray fallback.
  73656. if (!scene.getEngine().getCaps().textureFloat) {
  73657. // 3 channels of 1 bytes per pixel in bytes.
  73658. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  73659. byteArray = new Uint8Array(byteBuffer);
  73660. }
  73661. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  73662. // If special cases.
  73663. if (_this._useInGammaSpace || byteArray) {
  73664. for (var i = 0; i < _this._size * _this._size; i++) {
  73665. // Put in gamma space if requested.
  73666. if (_this._useInGammaSpace) {
  73667. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73668. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73669. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73670. }
  73671. // Convert to int texture for fallback.
  73672. if (byteArray) {
  73673. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73674. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73675. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73676. // May use luminance instead if the result is not accurate.
  73677. var max = Math.max(Math.max(r, g), b);
  73678. if (max > 255) {
  73679. var scale = 255 / max;
  73680. r *= scale;
  73681. g *= scale;
  73682. b *= scale;
  73683. }
  73684. byteArray[(i * 3) + 0] = r;
  73685. byteArray[(i * 3) + 1] = g;
  73686. byteArray[(i * 3) + 2] = b;
  73687. }
  73688. }
  73689. }
  73690. if (byteArray) {
  73691. results.push(byteArray);
  73692. }
  73693. else {
  73694. results.push(dataFace);
  73695. }
  73696. }
  73697. return results;
  73698. };
  73699. var mipmapGenerator = null;
  73700. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  73701. // if (!this._noMipmap &&
  73702. // this._usePMREMGenerator) {
  73703. // mipmapGenerator = (data: ArrayBufferView[]) => {
  73704. // // Custom setup of the generator matching with the PBR shader values.
  73705. // var generator = new BABYLON.PMREMGenerator(data,
  73706. // this._size,
  73707. // this._size,
  73708. // 0,
  73709. // 3,
  73710. // this.getScene().getEngine().getCaps().textureFloat,
  73711. // 2048,
  73712. // 0.25,
  73713. // false,
  73714. // true);
  73715. // return generator.filterCubeMap();
  73716. // };
  73717. // }
  73718. var scene = this.getScene();
  73719. if (scene) {
  73720. 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);
  73721. }
  73722. };
  73723. /**
  73724. * Starts the loading process of the texture.
  73725. */
  73726. HDRCubeTexture.prototype.loadTexture = function () {
  73727. if (this._isBABYLONPreprocessed) {
  73728. this.loadBabylonTexture();
  73729. }
  73730. else {
  73731. this.loadHDRTexture();
  73732. }
  73733. };
  73734. HDRCubeTexture.prototype.clone = function () {
  73735. var scene = this.getScene();
  73736. if (!scene) {
  73737. return this;
  73738. }
  73739. var size = (this._isBABYLONPreprocessed ? null : this._size);
  73740. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  73741. // Base texture
  73742. newTexture.level = this.level;
  73743. newTexture.wrapU = this.wrapU;
  73744. newTexture.wrapV = this.wrapV;
  73745. newTexture.coordinatesIndex = this.coordinatesIndex;
  73746. newTexture.coordinatesMode = this.coordinatesMode;
  73747. return newTexture;
  73748. };
  73749. // Methods
  73750. HDRCubeTexture.prototype.delayLoad = function () {
  73751. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73752. return;
  73753. }
  73754. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73755. this._texture = this._getFromCache(this.url, this._noMipmap);
  73756. if (!this._texture) {
  73757. this.loadTexture();
  73758. }
  73759. };
  73760. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  73761. return this._textureMatrix;
  73762. };
  73763. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73764. this._textureMatrix = value;
  73765. };
  73766. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73767. var texture = null;
  73768. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  73769. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  73770. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  73771. texture.name = parsedTexture.name;
  73772. texture.hasAlpha = parsedTexture.hasAlpha;
  73773. texture.level = parsedTexture.level;
  73774. texture.coordinatesMode = parsedTexture.coordinatesMode;
  73775. texture.isBlocking = parsedTexture.isBlocking;
  73776. }
  73777. if (texture) {
  73778. if (parsedTexture.boundingBoxPosition) {
  73779. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  73780. }
  73781. if (parsedTexture.boundingBoxSize) {
  73782. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  73783. }
  73784. }
  73785. return texture;
  73786. };
  73787. HDRCubeTexture.prototype.serialize = function () {
  73788. if (!this.name) {
  73789. return null;
  73790. }
  73791. var serializationObject = {};
  73792. serializationObject.name = this.name;
  73793. serializationObject.hasAlpha = this.hasAlpha;
  73794. serializationObject.isCube = true;
  73795. serializationObject.level = this.level;
  73796. serializationObject.size = this._size;
  73797. serializationObject.coordinatesMode = this.coordinatesMode;
  73798. serializationObject.useInGammaSpace = this._useInGammaSpace;
  73799. serializationObject.generateHarmonics = this._generateHarmonics;
  73800. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  73801. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  73802. serializationObject.customType = "BABYLON.HDRCubeTexture";
  73803. serializationObject.noMipmap = this._noMipmap;
  73804. serializationObject.isBlocking = this._isBlocking;
  73805. return serializationObject;
  73806. };
  73807. /**
  73808. * Saves as a file the data contained in the texture in a binary format.
  73809. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73810. * as the spherical used in the lighting.
  73811. * @param url The HDR file url.
  73812. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73813. * @param onError Method called if any error happens during download.
  73814. * @return The packed binary data.
  73815. */
  73816. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  73817. if (onError === void 0) { onError = null; }
  73818. var callback = function (buffer) {
  73819. var data = new Blob([buffer], { type: 'application/octet-stream' });
  73820. // Returns a URL you can use as a href.
  73821. var objUrl = window.URL.createObjectURL(data);
  73822. // Simulates a link to it and click to dowload.
  73823. var a = document.createElement("a");
  73824. document.body.appendChild(a);
  73825. a.style.display = "none";
  73826. a.href = objUrl;
  73827. a.download = "envmap.babylon.hdr";
  73828. a.click();
  73829. };
  73830. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  73831. };
  73832. /**
  73833. * Serializes the data contained in the texture in a binary format.
  73834. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73835. * as the spherical used in the lighting.
  73836. * @param url The HDR file url.
  73837. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73838. * @param onError Method called if any error happens during download.
  73839. * @return The packed binary data.
  73840. */
  73841. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  73842. if (onError === void 0) { onError = null; }
  73843. // Needs the url tho create the texture.
  73844. if (!url) {
  73845. return;
  73846. }
  73847. // Check Power of two size.
  73848. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  73849. return;
  73850. }
  73851. // Coming Back in 3.x.
  73852. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  73853. };
  73854. HDRCubeTexture._facesMapping = [
  73855. "right",
  73856. "left",
  73857. "up",
  73858. "down",
  73859. "front",
  73860. "back"
  73861. ];
  73862. return HDRCubeTexture;
  73863. }(BABYLON.BaseTexture));
  73864. BABYLON.HDRCubeTexture = HDRCubeTexture;
  73865. })(BABYLON || (BABYLON = {}));
  73866. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  73867. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  73868. // Huge respect for a such great lib.
  73869. // Earcut license:
  73870. // Copyright (c) 2016, Mapbox
  73871. //
  73872. // Permission to use, copy, modify, and/or distribute this software for any purpose
  73873. // with or without fee is hereby granted, provided that the above copyright notice
  73874. // and this permission notice appear in all copies.
  73875. //
  73876. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  73877. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  73878. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  73879. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  73880. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  73881. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  73882. // THIS SOFTWARE.
  73883. var Earcut;
  73884. (function (Earcut) {
  73885. /**
  73886. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  73887. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  73888. * @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).
  73889. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  73890. */
  73891. function earcut(data, holeIndices, dim) {
  73892. dim = dim || 2;
  73893. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  73894. if (!outerNode)
  73895. return triangles;
  73896. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  73897. if (hasHoles)
  73898. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  73899. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  73900. if (data.length > 80 * dim) {
  73901. minX = maxX = data[0];
  73902. minY = maxY = data[1];
  73903. for (var i = dim; i < outerLen; i += dim) {
  73904. x = data[i];
  73905. y = data[i + 1];
  73906. if (x < minX)
  73907. minX = x;
  73908. if (y < minY)
  73909. minY = y;
  73910. if (x > maxX)
  73911. maxX = x;
  73912. if (y > maxY)
  73913. maxY = y;
  73914. }
  73915. // minX, minY and size are later used to transform coords into integers for z-order calculation
  73916. size = Math.max(maxX - minX, maxY - minY);
  73917. }
  73918. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  73919. return triangles;
  73920. }
  73921. Earcut.earcut = earcut;
  73922. var Node = /** @class */ (function () {
  73923. function Node(i, x, y) {
  73924. this.i = i;
  73925. this.x = x;
  73926. this.y = y;
  73927. this.prev = null;
  73928. this.next = null;
  73929. this.z = null;
  73930. this.prevZ = null;
  73931. this.nextZ = null;
  73932. this.steiner = false;
  73933. }
  73934. return Node;
  73935. }());
  73936. // create a circular doubly linked list from polygon points in the specified winding order
  73937. function linkedList(data, start, end, dim, clockwise) {
  73938. var i, last = null;
  73939. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  73940. for (i = start; i < end; i += dim)
  73941. last = insertNode(i, data[i], data[i + 1], last);
  73942. }
  73943. else {
  73944. for (i = end - dim; i >= start; i -= dim)
  73945. last = insertNode(i, data[i], data[i + 1], last);
  73946. }
  73947. if (last && equals(last, last.next)) {
  73948. removeNode(last);
  73949. last = last.next;
  73950. }
  73951. return last;
  73952. }
  73953. // eliminate colinear or duplicate points
  73954. function filterPoints(start, end) {
  73955. if (!start)
  73956. return start;
  73957. if (!end)
  73958. end = start;
  73959. var p = start, again;
  73960. do {
  73961. again = false;
  73962. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  73963. removeNode(p);
  73964. p = end = p.prev;
  73965. if (p === p.next)
  73966. return undefined;
  73967. again = true;
  73968. }
  73969. else {
  73970. p = p.next;
  73971. }
  73972. } while (again || p !== end);
  73973. return end;
  73974. }
  73975. // main ear slicing loop which triangulates a polygon (given as a linked list)
  73976. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  73977. if (!ear)
  73978. return;
  73979. // interlink polygon nodes in z-order
  73980. if (!pass && size)
  73981. indexCurve(ear, minX, minY, size);
  73982. var stop = ear, prev, next;
  73983. // iterate through ears, slicing them one by one
  73984. while (ear.prev !== ear.next) {
  73985. prev = ear.prev;
  73986. next = ear.next;
  73987. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  73988. // cut off the triangle
  73989. triangles.push(prev.i / dim);
  73990. triangles.push(ear.i / dim);
  73991. triangles.push(next.i / dim);
  73992. removeNode(ear);
  73993. // skipping the next vertice leads to less sliver triangles
  73994. ear = next.next;
  73995. stop = next.next;
  73996. continue;
  73997. }
  73998. ear = next;
  73999. // if we looped through the whole remaining polygon and can't find any more ears
  74000. if (ear === stop) {
  74001. // try filtering points and slicing again
  74002. if (!pass) {
  74003. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  74004. // if this didn't work, try curing all small self-intersections locally
  74005. }
  74006. else if (pass === 1) {
  74007. ear = cureLocalIntersections(ear, triangles, dim);
  74008. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  74009. // as a last resort, try splitting the remaining polygon into two
  74010. }
  74011. else if (pass === 2) {
  74012. splitEarcut(ear, triangles, dim, minX, minY, size);
  74013. }
  74014. break;
  74015. }
  74016. }
  74017. }
  74018. // check whether a polygon node forms a valid ear with adjacent nodes
  74019. function isEar(ear) {
  74020. var a = ear.prev, b = ear, c = ear.next;
  74021. if (area(a, b, c) >= 0)
  74022. return false; // reflex, can't be an ear
  74023. // now make sure we don't have other points inside the potential ear
  74024. var p = ear.next.next;
  74025. while (p !== ear.prev) {
  74026. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74027. area(p.prev, p, p.next) >= 0)
  74028. return false;
  74029. p = p.next;
  74030. }
  74031. return true;
  74032. }
  74033. function isEarHashed(ear, minX, minY, size) {
  74034. var a = ear.prev, b = ear, c = ear.next;
  74035. if (area(a, b, c) >= 0)
  74036. return false; // reflex, can't be an ear
  74037. // triangle bbox; min & max are calculated like this for speed
  74038. 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);
  74039. // z-order range for the current triangle bbox;
  74040. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  74041. // first look for points inside the triangle in increasing z-order
  74042. var p = ear.nextZ;
  74043. while (p && p.z <= maxZ) {
  74044. if (p !== ear.prev &&
  74045. p !== ear.next &&
  74046. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74047. area(p.prev, p, p.next) >= 0)
  74048. return false;
  74049. p = p.nextZ;
  74050. }
  74051. // then look for points in decreasing z-order
  74052. p = ear.prevZ;
  74053. while (p && p.z >= minZ) {
  74054. if (p !== ear.prev &&
  74055. p !== ear.next &&
  74056. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74057. area(p.prev, p, p.next) >= 0)
  74058. return false;
  74059. p = p.prevZ;
  74060. }
  74061. return true;
  74062. }
  74063. // go through all polygon nodes and cure small local self-intersections
  74064. function cureLocalIntersections(start, triangles, dim) {
  74065. var p = start;
  74066. do {
  74067. var a = p.prev, b = p.next.next;
  74068. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  74069. triangles.push(a.i / dim);
  74070. triangles.push(p.i / dim);
  74071. triangles.push(b.i / dim);
  74072. // remove two nodes involved
  74073. removeNode(p);
  74074. removeNode(p.next);
  74075. p = start = b;
  74076. }
  74077. p = p.next;
  74078. } while (p !== start);
  74079. return p;
  74080. }
  74081. // try splitting polygon into two and triangulate them independently
  74082. function splitEarcut(start, triangles, dim, minX, minY, size) {
  74083. // look for a valid diagonal that divides the polygon into two
  74084. var a = start;
  74085. do {
  74086. var b = a.next.next;
  74087. while (b !== a.prev) {
  74088. if (a.i !== b.i && isValidDiagonal(a, b)) {
  74089. // split the polygon in two by the diagonal
  74090. var c = splitPolygon(a, b);
  74091. // filter colinear points around the cuts
  74092. a = filterPoints(a, a.next);
  74093. c = filterPoints(c, c.next);
  74094. // run earcut on each half
  74095. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  74096. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  74097. return;
  74098. }
  74099. b = b.next;
  74100. }
  74101. a = a.next;
  74102. } while (a !== start);
  74103. }
  74104. // link every hole into the outer loop, producing a single-ring polygon without holes
  74105. function eliminateHoles(data, holeIndices, outerNode, dim) {
  74106. var queue = [], i, len, start, end, list;
  74107. for (i = 0, len = holeIndices.length; i < len; i++) {
  74108. start = holeIndices[i] * dim;
  74109. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74110. list = linkedList(data, start, end, dim, false);
  74111. if (list === list.next)
  74112. list.steiner = true;
  74113. queue.push(getLeftmost(list));
  74114. }
  74115. queue.sort(compareX);
  74116. // process holes from left to right
  74117. for (i = 0; i < queue.length; i++) {
  74118. eliminateHole(queue[i], outerNode);
  74119. outerNode = filterPoints(outerNode, outerNode.next);
  74120. }
  74121. return outerNode;
  74122. }
  74123. function compareX(a, b) {
  74124. return a.x - b.x;
  74125. }
  74126. // find a bridge between vertices that connects hole with an outer ring and and link it
  74127. function eliminateHole(hole, outerNode) {
  74128. outerNode = findHoleBridge(hole, outerNode);
  74129. if (outerNode) {
  74130. var b = splitPolygon(outerNode, hole);
  74131. filterPoints(b, b.next);
  74132. }
  74133. }
  74134. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  74135. function findHoleBridge(hole, outerNode) {
  74136. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  74137. // find a segment intersected by a ray from the hole's leftmost point to the left;
  74138. // segment's endpoint with lesser x will be potential connection point
  74139. do {
  74140. if (hy <= p.y && hy >= p.next.y) {
  74141. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  74142. if (x <= hx && x > qx) {
  74143. qx = x;
  74144. if (x === hx) {
  74145. if (hy === p.y)
  74146. return p;
  74147. if (hy === p.next.y)
  74148. return p.next;
  74149. }
  74150. m = p.x < p.next.x ? p : p.next;
  74151. }
  74152. }
  74153. p = p.next;
  74154. } while (p !== outerNode);
  74155. if (!m)
  74156. return null;
  74157. if (hx === qx)
  74158. return m.prev; // hole touches outer segment; pick lower endpoint
  74159. // look for points inside the triangle of hole point, segment intersection and endpoint;
  74160. // if there are no points found, we have a valid connection;
  74161. // otherwise choose the point of the minimum angle with the ray as connection point
  74162. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  74163. p = m.next;
  74164. while (p !== stop) {
  74165. if (hx >= p.x &&
  74166. p.x >= mx &&
  74167. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  74168. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  74169. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  74170. m = p;
  74171. tanMin = tan;
  74172. }
  74173. }
  74174. p = p.next;
  74175. }
  74176. return m;
  74177. }
  74178. // interlink polygon nodes in z-order
  74179. function indexCurve(start, minX, minY, size) {
  74180. var p = start;
  74181. do {
  74182. if (p.z === null)
  74183. p.z = zOrder(p.x, p.y, minX, minY, size);
  74184. p.prevZ = p.prev;
  74185. p.nextZ = p.next;
  74186. p = p.next;
  74187. } while (p !== start);
  74188. p.prevZ.nextZ = null;
  74189. p.prevZ = null;
  74190. sortLinked(p);
  74191. }
  74192. // Simon Tatham's linked list merge sort algorithm
  74193. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  74194. function sortLinked(list) {
  74195. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  74196. do {
  74197. p = list;
  74198. list = null;
  74199. tail = null;
  74200. numMerges = 0;
  74201. while (p) {
  74202. numMerges++;
  74203. q = p;
  74204. pSize = 0;
  74205. for (i = 0; i < inSize; i++) {
  74206. pSize++;
  74207. q = q.nextZ;
  74208. if (!q)
  74209. break;
  74210. }
  74211. qSize = inSize;
  74212. while (pSize > 0 || (qSize > 0 && q)) {
  74213. if (pSize === 0) {
  74214. e = q;
  74215. q = q.nextZ;
  74216. qSize--;
  74217. }
  74218. else if (qSize === 0 || !q) {
  74219. e = p;
  74220. p = p.nextZ;
  74221. pSize--;
  74222. }
  74223. else if (p.z <= q.z) {
  74224. e = p;
  74225. p = p.nextZ;
  74226. pSize--;
  74227. }
  74228. else {
  74229. e = q;
  74230. q = q.nextZ;
  74231. qSize--;
  74232. }
  74233. if (tail)
  74234. tail.nextZ = e;
  74235. else
  74236. list = e;
  74237. e.prevZ = tail;
  74238. tail = e;
  74239. }
  74240. p = q;
  74241. }
  74242. tail.nextZ = null;
  74243. inSize *= 2;
  74244. } while (numMerges > 1);
  74245. return list;
  74246. }
  74247. // z-order of a point given coords and size of the data bounding box
  74248. function zOrder(x, y, minX, minY, size) {
  74249. // coords are transformed into non-negative 15-bit integer range
  74250. x = 32767 * (x - minX) / size;
  74251. y = 32767 * (y - minY) / size;
  74252. x = (x | (x << 8)) & 0x00FF00FF;
  74253. x = (x | (x << 4)) & 0x0F0F0F0F;
  74254. x = (x | (x << 2)) & 0x33333333;
  74255. x = (x | (x << 1)) & 0x55555555;
  74256. y = (y | (y << 8)) & 0x00FF00FF;
  74257. y = (y | (y << 4)) & 0x0F0F0F0F;
  74258. y = (y | (y << 2)) & 0x33333333;
  74259. y = (y | (y << 1)) & 0x55555555;
  74260. return x | (y << 1);
  74261. }
  74262. // find the leftmost node of a polygon ring
  74263. function getLeftmost(start) {
  74264. var p = start, leftmost = start;
  74265. do {
  74266. if (p.x < leftmost.x)
  74267. leftmost = p;
  74268. p = p.next;
  74269. } while (p !== start);
  74270. return leftmost;
  74271. }
  74272. // check if a point lies within a convex triangle
  74273. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  74274. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  74275. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  74276. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  74277. }
  74278. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  74279. function isValidDiagonal(a, b) {
  74280. return a.next.i !== b.i &&
  74281. a.prev.i !== b.i &&
  74282. !intersectsPolygon(a, b) &&
  74283. locallyInside(a, b) &&
  74284. locallyInside(b, a) &&
  74285. middleInside(a, b);
  74286. }
  74287. // signed area of a triangle
  74288. function area(p, q, r) {
  74289. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  74290. }
  74291. // check if two points are equal
  74292. function equals(p1, p2) {
  74293. return p1.x === p2.x && p1.y === p2.y;
  74294. }
  74295. // check if two segments intersect
  74296. function intersects(p1, q1, p2, q2) {
  74297. if ((equals(p1, q1) && equals(p2, q2)) ||
  74298. (equals(p1, q2) && equals(p2, q1)))
  74299. return true;
  74300. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  74301. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  74302. }
  74303. // check if a polygon diagonal intersects any polygon segments
  74304. function intersectsPolygon(a, b) {
  74305. var p = a;
  74306. do {
  74307. if (p.i !== a.i &&
  74308. p.next.i !== a.i &&
  74309. p.i !== b.i &&
  74310. p.next.i !== b.i &&
  74311. intersects(p, p.next, a, b))
  74312. return true;
  74313. p = p.next;
  74314. } while (p !== a);
  74315. return false;
  74316. }
  74317. // check if a polygon diagonal is locally inside the polygon
  74318. function locallyInside(a, b) {
  74319. return area(a.prev, a, a.next) < 0
  74320. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74321. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74322. }
  74323. // check if the middle point of a polygon diagonal is inside the polygon
  74324. function middleInside(a, b) {
  74325. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74326. do {
  74327. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74328. inside = !inside;
  74329. p = p.next;
  74330. } while (p !== a);
  74331. return inside;
  74332. }
  74333. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74334. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74335. function splitPolygon(a, b) {
  74336. 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;
  74337. a.next = b;
  74338. b.prev = a;
  74339. a2.next = an;
  74340. an.prev = a2;
  74341. b2.next = a2;
  74342. a2.prev = b2;
  74343. bp.next = b2;
  74344. b2.prev = bp;
  74345. return b2;
  74346. }
  74347. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74348. function insertNode(i, x, y, last) {
  74349. var p = new Node(i, x, y);
  74350. if (!last) {
  74351. p.prev = p;
  74352. p.next = p;
  74353. }
  74354. else {
  74355. p.next = last.next;
  74356. p.prev = last;
  74357. last.next.prev = p;
  74358. last.next = p;
  74359. }
  74360. return p;
  74361. }
  74362. function removeNode(p) {
  74363. p.next.prev = p.prev;
  74364. p.prev.next = p.next;
  74365. if (p.prevZ)
  74366. p.prevZ.nextZ = p.nextZ;
  74367. if (p.nextZ)
  74368. p.nextZ.prevZ = p.prevZ;
  74369. }
  74370. /**
  74371. * return a percentage difference between the polygon area and its triangulation area;
  74372. * used to verify correctness of triangulation
  74373. */
  74374. function deviation(data, holeIndices, dim, triangles) {
  74375. var hasHoles = holeIndices && holeIndices.length;
  74376. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  74377. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  74378. if (hasHoles) {
  74379. for (var i = 0, len = holeIndices.length; i < len; i++) {
  74380. var start = holeIndices[i] * dim;
  74381. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74382. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  74383. }
  74384. }
  74385. var trianglesArea = 0;
  74386. for (i = 0; i < triangles.length; i += 3) {
  74387. var a = triangles[i] * dim;
  74388. var b = triangles[i + 1] * dim;
  74389. var c = triangles[i + 2] * dim;
  74390. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  74391. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  74392. }
  74393. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  74394. }
  74395. Earcut.deviation = deviation;
  74396. ;
  74397. function signedArea(data, start, end, dim) {
  74398. var sum = 0;
  74399. for (var i = start, j = end - dim; i < end; i += dim) {
  74400. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  74401. j = i;
  74402. }
  74403. return sum;
  74404. }
  74405. /**
  74406. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  74407. */
  74408. function flatten(data) {
  74409. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  74410. for (var i = 0; i < data.length; i++) {
  74411. for (var j = 0; j < data[i].length; j++) {
  74412. for (var d = 0; d < dim; d++)
  74413. result.vertices.push(data[i][j][d]);
  74414. }
  74415. if (i > 0) {
  74416. holeIndex += data[i - 1].length;
  74417. result.holes.push(holeIndex);
  74418. }
  74419. }
  74420. return result;
  74421. }
  74422. Earcut.flatten = flatten;
  74423. ;
  74424. })(Earcut || (Earcut = {}));
  74425. //# sourceMappingURL=babylon.earcut.js.map
  74426. var BABYLON;
  74427. (function (BABYLON) {
  74428. var IndexedVector2 = /** @class */ (function (_super) {
  74429. __extends(IndexedVector2, _super);
  74430. function IndexedVector2(original, index) {
  74431. var _this = _super.call(this, original.x, original.y) || this;
  74432. _this.index = index;
  74433. return _this;
  74434. }
  74435. return IndexedVector2;
  74436. }(BABYLON.Vector2));
  74437. var PolygonPoints = /** @class */ (function () {
  74438. function PolygonPoints() {
  74439. this.elements = new Array();
  74440. }
  74441. PolygonPoints.prototype.add = function (originalPoints) {
  74442. var _this = this;
  74443. var result = new Array();
  74444. originalPoints.forEach(function (point) {
  74445. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  74446. var newPoint = new IndexedVector2(point, _this.elements.length);
  74447. result.push(newPoint);
  74448. _this.elements.push(newPoint);
  74449. }
  74450. });
  74451. return result;
  74452. };
  74453. PolygonPoints.prototype.computeBounds = function () {
  74454. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74455. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74456. this.elements.forEach(function (point) {
  74457. // x
  74458. if (point.x < lmin.x) {
  74459. lmin.x = point.x;
  74460. }
  74461. else if (point.x > lmax.x) {
  74462. lmax.x = point.x;
  74463. }
  74464. // y
  74465. if (point.y < lmin.y) {
  74466. lmin.y = point.y;
  74467. }
  74468. else if (point.y > lmax.y) {
  74469. lmax.y = point.y;
  74470. }
  74471. });
  74472. return {
  74473. min: lmin,
  74474. max: lmax,
  74475. width: lmax.x - lmin.x,
  74476. height: lmax.y - lmin.y
  74477. };
  74478. };
  74479. return PolygonPoints;
  74480. }());
  74481. var Polygon = /** @class */ (function () {
  74482. function Polygon() {
  74483. }
  74484. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  74485. return [
  74486. new BABYLON.Vector2(xmin, ymin),
  74487. new BABYLON.Vector2(xmax, ymin),
  74488. new BABYLON.Vector2(xmax, ymax),
  74489. new BABYLON.Vector2(xmin, ymax)
  74490. ];
  74491. };
  74492. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  74493. if (cx === void 0) { cx = 0; }
  74494. if (cy === void 0) { cy = 0; }
  74495. if (numberOfSides === void 0) { numberOfSides = 32; }
  74496. var result = new Array();
  74497. var angle = 0;
  74498. var increment = (Math.PI * 2) / numberOfSides;
  74499. for (var i = 0; i < numberOfSides; i++) {
  74500. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  74501. angle -= increment;
  74502. }
  74503. return result;
  74504. };
  74505. Polygon.Parse = function (input) {
  74506. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  74507. var i, result = [];
  74508. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  74509. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  74510. }
  74511. return result;
  74512. };
  74513. Polygon.StartingAt = function (x, y) {
  74514. return BABYLON.Path2.StartingAt(x, y);
  74515. };
  74516. return Polygon;
  74517. }());
  74518. BABYLON.Polygon = Polygon;
  74519. var PolygonMeshBuilder = /** @class */ (function () {
  74520. function PolygonMeshBuilder(name, contours, scene) {
  74521. this._points = new PolygonPoints();
  74522. this._outlinepoints = new PolygonPoints();
  74523. this._holes = new Array();
  74524. this._epoints = new Array();
  74525. this._eholes = new Array();
  74526. this._name = name;
  74527. this._scene = scene;
  74528. var points;
  74529. if (contours instanceof BABYLON.Path2) {
  74530. points = contours.getPoints();
  74531. }
  74532. else {
  74533. points = contours;
  74534. }
  74535. this._addToepoint(points);
  74536. this._points.add(points);
  74537. this._outlinepoints.add(points);
  74538. }
  74539. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  74540. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  74541. var p = points_1[_i];
  74542. this._epoints.push(p.x, p.y);
  74543. }
  74544. };
  74545. PolygonMeshBuilder.prototype.addHole = function (hole) {
  74546. this._points.add(hole);
  74547. var holepoints = new PolygonPoints();
  74548. holepoints.add(hole);
  74549. this._holes.push(holepoints);
  74550. this._eholes.push(this._epoints.length / 2);
  74551. this._addToepoint(hole);
  74552. return this;
  74553. };
  74554. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  74555. var _this = this;
  74556. if (updatable === void 0) { updatable = false; }
  74557. if (depth === void 0) { depth = 0; }
  74558. var result = new BABYLON.Mesh(this._name, this._scene);
  74559. var normals = new Array();
  74560. var positions = new Array();
  74561. var uvs = new Array();
  74562. var bounds = this._points.computeBounds();
  74563. this._points.elements.forEach(function (p) {
  74564. normals.push(0, 1.0, 0);
  74565. positions.push(p.x, 0, p.y);
  74566. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  74567. });
  74568. var indices = new Array();
  74569. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  74570. for (var i = 0; i < res.length; i++) {
  74571. indices.push(res[i]);
  74572. }
  74573. if (depth > 0) {
  74574. var positionscount = (positions.length / 3); //get the current pointcount
  74575. this._points.elements.forEach(function (p) {
  74576. normals.push(0, -1.0, 0);
  74577. positions.push(p.x, -depth, p.y);
  74578. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  74579. });
  74580. var totalCount = indices.length;
  74581. for (var i = 0; i < totalCount; i += 3) {
  74582. var i0 = indices[i + 0];
  74583. var i1 = indices[i + 1];
  74584. var i2 = indices[i + 2];
  74585. indices.push(i2 + positionscount);
  74586. indices.push(i1 + positionscount);
  74587. indices.push(i0 + positionscount);
  74588. }
  74589. //Add the sides
  74590. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  74591. this._holes.forEach(function (hole) {
  74592. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  74593. });
  74594. }
  74595. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  74596. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  74597. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  74598. result.setIndices(indices);
  74599. return result;
  74600. };
  74601. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  74602. var StartIndex = positions.length / 3;
  74603. var ulength = 0;
  74604. for (var i = 0; i < points.elements.length; i++) {
  74605. var p = points.elements[i];
  74606. var p1;
  74607. if ((i + 1) > points.elements.length - 1) {
  74608. p1 = points.elements[0];
  74609. }
  74610. else {
  74611. p1 = points.elements[i + 1];
  74612. }
  74613. positions.push(p.x, 0, p.y);
  74614. positions.push(p.x, -depth, p.y);
  74615. positions.push(p1.x, 0, p1.y);
  74616. positions.push(p1.x, -depth, p1.y);
  74617. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  74618. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  74619. var v3 = v2.subtract(v1);
  74620. var v4 = new BABYLON.Vector3(0, 1, 0);
  74621. var vn = BABYLON.Vector3.Cross(v3, v4);
  74622. vn = vn.normalize();
  74623. uvs.push(ulength / bounds.width, 0);
  74624. uvs.push(ulength / bounds.width, 1);
  74625. ulength += v3.length();
  74626. uvs.push((ulength / bounds.width), 0);
  74627. uvs.push((ulength / bounds.width), 1);
  74628. if (!flip) {
  74629. normals.push(-vn.x, -vn.y, -vn.z);
  74630. normals.push(-vn.x, -vn.y, -vn.z);
  74631. normals.push(-vn.x, -vn.y, -vn.z);
  74632. normals.push(-vn.x, -vn.y, -vn.z);
  74633. indices.push(StartIndex);
  74634. indices.push(StartIndex + 1);
  74635. indices.push(StartIndex + 2);
  74636. indices.push(StartIndex + 1);
  74637. indices.push(StartIndex + 3);
  74638. indices.push(StartIndex + 2);
  74639. }
  74640. else {
  74641. normals.push(vn.x, vn.y, vn.z);
  74642. normals.push(vn.x, vn.y, vn.z);
  74643. normals.push(vn.x, vn.y, vn.z);
  74644. normals.push(vn.x, vn.y, vn.z);
  74645. indices.push(StartIndex);
  74646. indices.push(StartIndex + 2);
  74647. indices.push(StartIndex + 1);
  74648. indices.push(StartIndex + 1);
  74649. indices.push(StartIndex + 2);
  74650. indices.push(StartIndex + 3);
  74651. }
  74652. StartIndex += 4;
  74653. }
  74654. ;
  74655. };
  74656. return PolygonMeshBuilder;
  74657. }());
  74658. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  74659. })(BABYLON || (BABYLON = {}));
  74660. //# sourceMappingURL=babylon.polygonMesh.js.map
  74661. var BABYLON;
  74662. (function (BABYLON) {
  74663. // Unique ID when we import meshes from Babylon to CSG
  74664. var currentCSGMeshId = 0;
  74665. // # class Vertex
  74666. // Represents a vertex of a polygon. Use your own vertex class instead of this
  74667. // one to provide additional features like texture coordinates and vertex
  74668. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  74669. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  74670. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  74671. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  74672. // is not used anywhere else.
  74673. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  74674. var Vertex = /** @class */ (function () {
  74675. function Vertex(pos, normal, uv) {
  74676. this.pos = pos;
  74677. this.normal = normal;
  74678. this.uv = uv;
  74679. }
  74680. Vertex.prototype.clone = function () {
  74681. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  74682. };
  74683. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  74684. // orientation of a polygon is flipped.
  74685. Vertex.prototype.flip = function () {
  74686. this.normal = this.normal.scale(-1);
  74687. };
  74688. // Create a new vertex between this vertex and `other` by linearly
  74689. // interpolating all properties using a parameter of `t`. Subclasses should
  74690. // override this to interpolate additional properties.
  74691. Vertex.prototype.interpolate = function (other, t) {
  74692. 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));
  74693. };
  74694. return Vertex;
  74695. }());
  74696. // # class Plane
  74697. // Represents a plane in 3D space.
  74698. var Plane = /** @class */ (function () {
  74699. function Plane(normal, w) {
  74700. this.normal = normal;
  74701. this.w = w;
  74702. }
  74703. Plane.FromPoints = function (a, b, c) {
  74704. var v0 = c.subtract(a);
  74705. var v1 = b.subtract(a);
  74706. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  74707. return null;
  74708. }
  74709. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  74710. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  74711. };
  74712. Plane.prototype.clone = function () {
  74713. return new Plane(this.normal.clone(), this.w);
  74714. };
  74715. Plane.prototype.flip = function () {
  74716. this.normal.scaleInPlace(-1);
  74717. this.w = -this.w;
  74718. };
  74719. // Split `polygon` by this plane if needed, then put the polygon or polygon
  74720. // fragments in the appropriate lists. Coplanar polygons go into either
  74721. // `coplanarFront` or `coplanarBack` depending on their orientation with
  74722. // respect to this plane. Polygons in front or in back of this plane go into
  74723. // either `front` or `back`.
  74724. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  74725. var COPLANAR = 0;
  74726. var FRONT = 1;
  74727. var BACK = 2;
  74728. var SPANNING = 3;
  74729. // Classify each point as well as the entire polygon into one of the above
  74730. // four classes.
  74731. var polygonType = 0;
  74732. var types = [];
  74733. var i;
  74734. var t;
  74735. for (i = 0; i < polygon.vertices.length; i++) {
  74736. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  74737. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  74738. polygonType |= type;
  74739. types.push(type);
  74740. }
  74741. // Put the polygon in the correct list, splitting it when necessary.
  74742. switch (polygonType) {
  74743. case COPLANAR:
  74744. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  74745. break;
  74746. case FRONT:
  74747. front.push(polygon);
  74748. break;
  74749. case BACK:
  74750. back.push(polygon);
  74751. break;
  74752. case SPANNING:
  74753. var f = [], b = [];
  74754. for (i = 0; i < polygon.vertices.length; i++) {
  74755. var j = (i + 1) % polygon.vertices.length;
  74756. var ti = types[i], tj = types[j];
  74757. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  74758. if (ti !== BACK)
  74759. f.push(vi);
  74760. if (ti !== FRONT)
  74761. b.push(ti !== BACK ? vi.clone() : vi);
  74762. if ((ti | tj) === SPANNING) {
  74763. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  74764. var v = vi.interpolate(vj, t);
  74765. f.push(v);
  74766. b.push(v.clone());
  74767. }
  74768. }
  74769. var poly;
  74770. if (f.length >= 3) {
  74771. poly = new Polygon(f, polygon.shared);
  74772. if (poly.plane)
  74773. front.push(poly);
  74774. }
  74775. if (b.length >= 3) {
  74776. poly = new Polygon(b, polygon.shared);
  74777. if (poly.plane)
  74778. back.push(poly);
  74779. }
  74780. break;
  74781. }
  74782. };
  74783. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  74784. // point is on the plane.
  74785. Plane.EPSILON = 1e-5;
  74786. return Plane;
  74787. }());
  74788. // # class Polygon
  74789. // Represents a convex polygon. The vertices used to initialize a polygon must
  74790. // be coplanar and form a convex loop.
  74791. //
  74792. // Each convex polygon has a `shared` property, which is shared between all
  74793. // polygons that are clones of each other or were split from the same polygon.
  74794. // This can be used to define per-polygon properties (such as surface color).
  74795. var Polygon = /** @class */ (function () {
  74796. function Polygon(vertices, shared) {
  74797. this.vertices = vertices;
  74798. this.shared = shared;
  74799. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  74800. }
  74801. Polygon.prototype.clone = function () {
  74802. var vertices = this.vertices.map(function (v) { return v.clone(); });
  74803. return new Polygon(vertices, this.shared);
  74804. };
  74805. Polygon.prototype.flip = function () {
  74806. this.vertices.reverse().map(function (v) { v.flip(); });
  74807. this.plane.flip();
  74808. };
  74809. return Polygon;
  74810. }());
  74811. // # class Node
  74812. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  74813. // by picking a polygon to split along. That polygon (and all other coplanar
  74814. // polygons) are added directly to that node and the other polygons are added to
  74815. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  74816. // no distinction between internal and leaf nodes.
  74817. var Node = /** @class */ (function () {
  74818. function Node(polygons) {
  74819. this.plane = null;
  74820. this.front = null;
  74821. this.back = null;
  74822. this.polygons = new Array();
  74823. if (polygons) {
  74824. this.build(polygons);
  74825. }
  74826. }
  74827. Node.prototype.clone = function () {
  74828. var node = new Node();
  74829. node.plane = this.plane && this.plane.clone();
  74830. node.front = this.front && this.front.clone();
  74831. node.back = this.back && this.back.clone();
  74832. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  74833. return node;
  74834. };
  74835. // Convert solid space to empty space and empty space to solid space.
  74836. Node.prototype.invert = function () {
  74837. for (var i = 0; i < this.polygons.length; i++) {
  74838. this.polygons[i].flip();
  74839. }
  74840. if (this.plane) {
  74841. this.plane.flip();
  74842. }
  74843. if (this.front) {
  74844. this.front.invert();
  74845. }
  74846. if (this.back) {
  74847. this.back.invert();
  74848. }
  74849. var temp = this.front;
  74850. this.front = this.back;
  74851. this.back = temp;
  74852. };
  74853. // Recursively remove all polygons in `polygons` that are inside this BSP
  74854. // tree.
  74855. Node.prototype.clipPolygons = function (polygons) {
  74856. if (!this.plane)
  74857. return polygons.slice();
  74858. var front = new Array(), back = new Array();
  74859. for (var i = 0; i < polygons.length; i++) {
  74860. this.plane.splitPolygon(polygons[i], front, back, front, back);
  74861. }
  74862. if (this.front) {
  74863. front = this.front.clipPolygons(front);
  74864. }
  74865. if (this.back) {
  74866. back = this.back.clipPolygons(back);
  74867. }
  74868. else {
  74869. back = [];
  74870. }
  74871. return front.concat(back);
  74872. };
  74873. // Remove all polygons in this BSP tree that are inside the other BSP tree
  74874. // `bsp`.
  74875. Node.prototype.clipTo = function (bsp) {
  74876. this.polygons = bsp.clipPolygons(this.polygons);
  74877. if (this.front)
  74878. this.front.clipTo(bsp);
  74879. if (this.back)
  74880. this.back.clipTo(bsp);
  74881. };
  74882. // Return a list of all polygons in this BSP tree.
  74883. Node.prototype.allPolygons = function () {
  74884. var polygons = this.polygons.slice();
  74885. if (this.front)
  74886. polygons = polygons.concat(this.front.allPolygons());
  74887. if (this.back)
  74888. polygons = polygons.concat(this.back.allPolygons());
  74889. return polygons;
  74890. };
  74891. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  74892. // new polygons are filtered down to the bottom of the tree and become new
  74893. // nodes there. Each set of polygons is partitioned using the first polygon
  74894. // (no heuristic is used to pick a good split).
  74895. Node.prototype.build = function (polygons) {
  74896. if (!polygons.length)
  74897. return;
  74898. if (!this.plane)
  74899. this.plane = polygons[0].plane.clone();
  74900. var front = new Array(), back = new Array();
  74901. for (var i = 0; i < polygons.length; i++) {
  74902. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  74903. }
  74904. if (front.length) {
  74905. if (!this.front)
  74906. this.front = new Node();
  74907. this.front.build(front);
  74908. }
  74909. if (back.length) {
  74910. if (!this.back)
  74911. this.back = new Node();
  74912. this.back.build(back);
  74913. }
  74914. };
  74915. return Node;
  74916. }());
  74917. var CSG = /** @class */ (function () {
  74918. function CSG() {
  74919. this.polygons = new Array();
  74920. }
  74921. // Convert BABYLON.Mesh to BABYLON.CSG
  74922. CSG.FromMesh = function (mesh) {
  74923. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  74924. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  74925. if (mesh instanceof BABYLON.Mesh) {
  74926. mesh.computeWorldMatrix(true);
  74927. matrix = mesh.getWorldMatrix();
  74928. meshPosition = mesh.position.clone();
  74929. meshRotation = mesh.rotation.clone();
  74930. if (mesh.rotationQuaternion) {
  74931. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  74932. }
  74933. meshScaling = mesh.scaling.clone();
  74934. }
  74935. else {
  74936. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  74937. }
  74938. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74939. var subMeshes = mesh.subMeshes;
  74940. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  74941. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  74942. vertices = [];
  74943. for (var j = 0; j < 3; j++) {
  74944. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  74945. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  74946. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  74947. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  74948. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  74949. vertex = new Vertex(position, normal, uv);
  74950. vertices.push(vertex);
  74951. }
  74952. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  74953. // To handle the case of degenerated triangle
  74954. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  74955. if (polygon.plane)
  74956. polygons.push(polygon);
  74957. }
  74958. }
  74959. var csg = CSG.FromPolygons(polygons);
  74960. csg.matrix = matrix;
  74961. csg.position = meshPosition;
  74962. csg.rotation = meshRotation;
  74963. csg.scaling = meshScaling;
  74964. csg.rotationQuaternion = meshRotationQuaternion;
  74965. currentCSGMeshId++;
  74966. return csg;
  74967. };
  74968. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  74969. CSG.FromPolygons = function (polygons) {
  74970. var csg = new CSG();
  74971. csg.polygons = polygons;
  74972. return csg;
  74973. };
  74974. CSG.prototype.clone = function () {
  74975. var csg = new CSG();
  74976. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  74977. csg.copyTransformAttributes(this);
  74978. return csg;
  74979. };
  74980. CSG.prototype.union = function (csg) {
  74981. var a = new Node(this.clone().polygons);
  74982. var b = new Node(csg.clone().polygons);
  74983. a.clipTo(b);
  74984. b.clipTo(a);
  74985. b.invert();
  74986. b.clipTo(a);
  74987. b.invert();
  74988. a.build(b.allPolygons());
  74989. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74990. };
  74991. CSG.prototype.unionInPlace = function (csg) {
  74992. var a = new Node(this.polygons);
  74993. var b = new Node(csg.polygons);
  74994. a.clipTo(b);
  74995. b.clipTo(a);
  74996. b.invert();
  74997. b.clipTo(a);
  74998. b.invert();
  74999. a.build(b.allPolygons());
  75000. this.polygons = a.allPolygons();
  75001. };
  75002. CSG.prototype.subtract = function (csg) {
  75003. var a = new Node(this.clone().polygons);
  75004. var b = new Node(csg.clone().polygons);
  75005. a.invert();
  75006. a.clipTo(b);
  75007. b.clipTo(a);
  75008. b.invert();
  75009. b.clipTo(a);
  75010. b.invert();
  75011. a.build(b.allPolygons());
  75012. a.invert();
  75013. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75014. };
  75015. CSG.prototype.subtractInPlace = function (csg) {
  75016. var a = new Node(this.polygons);
  75017. var b = new Node(csg.polygons);
  75018. a.invert();
  75019. a.clipTo(b);
  75020. b.clipTo(a);
  75021. b.invert();
  75022. b.clipTo(a);
  75023. b.invert();
  75024. a.build(b.allPolygons());
  75025. a.invert();
  75026. this.polygons = a.allPolygons();
  75027. };
  75028. CSG.prototype.intersect = function (csg) {
  75029. var a = new Node(this.clone().polygons);
  75030. var b = new Node(csg.clone().polygons);
  75031. a.invert();
  75032. b.clipTo(a);
  75033. b.invert();
  75034. a.clipTo(b);
  75035. b.clipTo(a);
  75036. a.build(b.allPolygons());
  75037. a.invert();
  75038. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75039. };
  75040. CSG.prototype.intersectInPlace = function (csg) {
  75041. var a = new Node(this.polygons);
  75042. var b = new Node(csg.polygons);
  75043. a.invert();
  75044. b.clipTo(a);
  75045. b.invert();
  75046. a.clipTo(b);
  75047. b.clipTo(a);
  75048. a.build(b.allPolygons());
  75049. a.invert();
  75050. this.polygons = a.allPolygons();
  75051. };
  75052. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  75053. // not modified.
  75054. CSG.prototype.inverse = function () {
  75055. var csg = this.clone();
  75056. csg.inverseInPlace();
  75057. return csg;
  75058. };
  75059. CSG.prototype.inverseInPlace = function () {
  75060. this.polygons.map(function (p) { p.flip(); });
  75061. };
  75062. // This is used to keep meshes transformations so they can be restored
  75063. // when we build back a Babylon Mesh
  75064. // NB : All CSG operations are performed in world coordinates
  75065. CSG.prototype.copyTransformAttributes = function (csg) {
  75066. this.matrix = csg.matrix;
  75067. this.position = csg.position;
  75068. this.rotation = csg.rotation;
  75069. this.scaling = csg.scaling;
  75070. this.rotationQuaternion = csg.rotationQuaternion;
  75071. return this;
  75072. };
  75073. // Build Raw mesh from CSG
  75074. // Coordinates here are in world space
  75075. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  75076. var matrix = this.matrix.clone();
  75077. matrix.invert();
  75078. 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;
  75079. if (keepSubMeshes) {
  75080. // Sort Polygons, since subMeshes are indices range
  75081. polygons.sort(function (a, b) {
  75082. if (a.shared.meshId === b.shared.meshId) {
  75083. return a.shared.subMeshId - b.shared.subMeshId;
  75084. }
  75085. else {
  75086. return a.shared.meshId - b.shared.meshId;
  75087. }
  75088. });
  75089. }
  75090. for (var i = 0, il = polygons.length; i < il; i++) {
  75091. polygon = polygons[i];
  75092. // Building SubMeshes
  75093. if (!subMesh_dict[polygon.shared.meshId]) {
  75094. subMesh_dict[polygon.shared.meshId] = {};
  75095. }
  75096. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  75097. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  75098. indexStart: +Infinity,
  75099. indexEnd: -Infinity,
  75100. materialIndex: polygon.shared.materialIndex
  75101. };
  75102. }
  75103. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  75104. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  75105. polygonIndices[0] = 0;
  75106. polygonIndices[1] = j - 1;
  75107. polygonIndices[2] = j;
  75108. for (var k = 0; k < 3; k++) {
  75109. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  75110. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  75111. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  75112. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  75113. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  75114. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  75115. // Check if 2 points can be merged
  75116. if (!(typeof vertex_idx !== 'undefined' &&
  75117. normals[vertex_idx * 3] === localNormal.x &&
  75118. normals[vertex_idx * 3 + 1] === localNormal.y &&
  75119. normals[vertex_idx * 3 + 2] === localNormal.z &&
  75120. uvs[vertex_idx * 2] === uv.x &&
  75121. uvs[vertex_idx * 2 + 1] === uv.y)) {
  75122. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  75123. uvs.push(uv.x, uv.y);
  75124. normals.push(normal.x, normal.y, normal.z);
  75125. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  75126. }
  75127. indices.push(vertex_idx);
  75128. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  75129. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  75130. currentIndex++;
  75131. }
  75132. }
  75133. }
  75134. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  75135. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  75136. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  75137. mesh.setIndices(indices, null);
  75138. if (keepSubMeshes) {
  75139. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  75140. var materialIndexOffset = 0, materialMaxIndex;
  75141. mesh.subMeshes = new Array();
  75142. for (var m in subMesh_dict) {
  75143. materialMaxIndex = -1;
  75144. for (var sm in subMesh_dict[m]) {
  75145. subMesh_obj = subMesh_dict[m][sm];
  75146. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  75147. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  75148. }
  75149. materialIndexOffset += ++materialMaxIndex;
  75150. }
  75151. }
  75152. return mesh;
  75153. };
  75154. // Build Mesh from CSG taking material and transforms into account
  75155. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  75156. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  75157. mesh.material = material;
  75158. mesh.position.copyFrom(this.position);
  75159. mesh.rotation.copyFrom(this.rotation);
  75160. if (this.rotationQuaternion) {
  75161. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  75162. }
  75163. mesh.scaling.copyFrom(this.scaling);
  75164. mesh.computeWorldMatrix(true);
  75165. return mesh;
  75166. };
  75167. return CSG;
  75168. }());
  75169. BABYLON.CSG = CSG;
  75170. })(BABYLON || (BABYLON = {}));
  75171. //# sourceMappingURL=babylon.csg.js.map
  75172. var BABYLON;
  75173. (function (BABYLON) {
  75174. var LensFlare = /** @class */ (function () {
  75175. function LensFlare(size, position, color, imgUrl, system) {
  75176. this.size = size;
  75177. this.position = position;
  75178. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  75179. this.color = color || new BABYLON.Color3(1, 1, 1);
  75180. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  75181. this._system = system;
  75182. system.lensFlares.push(this);
  75183. }
  75184. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  75185. return new LensFlare(size, position, color, imgUrl, system);
  75186. };
  75187. LensFlare.prototype.dispose = function () {
  75188. if (this.texture) {
  75189. this.texture.dispose();
  75190. }
  75191. // Remove from scene
  75192. var index = this._system.lensFlares.indexOf(this);
  75193. this._system.lensFlares.splice(index, 1);
  75194. };
  75195. ;
  75196. return LensFlare;
  75197. }());
  75198. BABYLON.LensFlare = LensFlare;
  75199. })(BABYLON || (BABYLON = {}));
  75200. //# sourceMappingURL=babylon.lensFlare.js.map
  75201. var BABYLON;
  75202. (function (BABYLON) {
  75203. var LensFlareSystem = /** @class */ (function () {
  75204. function LensFlareSystem(name, emitter, scene) {
  75205. this.name = name;
  75206. this.lensFlares = new Array();
  75207. this.borderLimit = 300;
  75208. this.viewportBorder = 0;
  75209. this.layerMask = 0x0FFFFFFF;
  75210. this._vertexBuffers = {};
  75211. this._isEnabled = true;
  75212. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75213. this._emitter = emitter;
  75214. this.id = name;
  75215. scene.lensFlareSystems.push(this);
  75216. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  75217. var engine = scene.getEngine();
  75218. // VBO
  75219. var vertices = [];
  75220. vertices.push(1, 1);
  75221. vertices.push(-1, 1);
  75222. vertices.push(-1, -1);
  75223. vertices.push(1, -1);
  75224. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75225. // Indices
  75226. var indices = [];
  75227. indices.push(0);
  75228. indices.push(1);
  75229. indices.push(2);
  75230. indices.push(0);
  75231. indices.push(2);
  75232. indices.push(3);
  75233. this._indexBuffer = engine.createIndexBuffer(indices);
  75234. // Effects
  75235. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  75236. }
  75237. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  75238. get: function () {
  75239. return this._isEnabled;
  75240. },
  75241. set: function (value) {
  75242. this._isEnabled = value;
  75243. },
  75244. enumerable: true,
  75245. configurable: true
  75246. });
  75247. LensFlareSystem.prototype.getScene = function () {
  75248. return this._scene;
  75249. };
  75250. LensFlareSystem.prototype.getEmitter = function () {
  75251. return this._emitter;
  75252. };
  75253. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  75254. this._emitter = newEmitter;
  75255. };
  75256. LensFlareSystem.prototype.getEmitterPosition = function () {
  75257. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  75258. };
  75259. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  75260. var position = this.getEmitterPosition();
  75261. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  75262. this._positionX = position.x;
  75263. this._positionY = position.y;
  75264. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  75265. if (this.viewportBorder > 0) {
  75266. globalViewport.x -= this.viewportBorder;
  75267. globalViewport.y -= this.viewportBorder;
  75268. globalViewport.width += this.viewportBorder * 2;
  75269. globalViewport.height += this.viewportBorder * 2;
  75270. position.x += this.viewportBorder;
  75271. position.y += this.viewportBorder;
  75272. this._positionX += this.viewportBorder;
  75273. this._positionY += this.viewportBorder;
  75274. }
  75275. if (position.z > 0) {
  75276. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  75277. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  75278. return true;
  75279. }
  75280. return true;
  75281. }
  75282. return false;
  75283. };
  75284. LensFlareSystem.prototype._isVisible = function () {
  75285. if (!this._isEnabled || !this._scene.activeCamera) {
  75286. return false;
  75287. }
  75288. var emitterPosition = this.getEmitterPosition();
  75289. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  75290. var distance = direction.length();
  75291. direction.normalize();
  75292. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  75293. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  75294. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  75295. };
  75296. LensFlareSystem.prototype.render = function () {
  75297. if (!this._effect.isReady() || !this._scene.activeCamera)
  75298. return false;
  75299. var engine = this._scene.getEngine();
  75300. var viewport = this._scene.activeCamera.viewport;
  75301. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  75302. // Position
  75303. if (!this.computeEffectivePosition(globalViewport)) {
  75304. return false;
  75305. }
  75306. // Visibility
  75307. if (!this._isVisible()) {
  75308. return false;
  75309. }
  75310. // Intensity
  75311. var awayX;
  75312. var awayY;
  75313. if (this._positionX < this.borderLimit + globalViewport.x) {
  75314. awayX = this.borderLimit + globalViewport.x - this._positionX;
  75315. }
  75316. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  75317. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  75318. }
  75319. else {
  75320. awayX = 0;
  75321. }
  75322. if (this._positionY < this.borderLimit + globalViewport.y) {
  75323. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75324. }
  75325. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75326. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75327. }
  75328. else {
  75329. awayY = 0;
  75330. }
  75331. var away = (awayX > awayY) ? awayX : awayY;
  75332. away -= this.viewportBorder;
  75333. if (away > this.borderLimit) {
  75334. away = this.borderLimit;
  75335. }
  75336. var intensity = 1.0 - (away / this.borderLimit);
  75337. if (intensity < 0) {
  75338. return false;
  75339. }
  75340. if (intensity > 1.0) {
  75341. intensity = 1.0;
  75342. }
  75343. if (this.viewportBorder > 0) {
  75344. globalViewport.x += this.viewportBorder;
  75345. globalViewport.y += this.viewportBorder;
  75346. globalViewport.width -= this.viewportBorder * 2;
  75347. globalViewport.height -= this.viewportBorder * 2;
  75348. this._positionX -= this.viewportBorder;
  75349. this._positionY -= this.viewportBorder;
  75350. }
  75351. // Position
  75352. var centerX = globalViewport.x + globalViewport.width / 2;
  75353. var centerY = globalViewport.y + globalViewport.height / 2;
  75354. var distX = centerX - this._positionX;
  75355. var distY = centerY - this._positionY;
  75356. // Effects
  75357. engine.enableEffect(this._effect);
  75358. engine.setState(false);
  75359. engine.setDepthBuffer(false);
  75360. // VBOs
  75361. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  75362. // Flares
  75363. for (var index = 0; index < this.lensFlares.length; index++) {
  75364. var flare = this.lensFlares[index];
  75365. engine.setAlphaMode(flare.alphaMode);
  75366. var x = centerX - (distX * flare.position);
  75367. var y = centerY - (distY * flare.position);
  75368. var cw = flare.size;
  75369. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  75370. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  75371. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  75372. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  75373. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  75374. // Texture
  75375. this._effect.setTexture("textureSampler", flare.texture);
  75376. // Color
  75377. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  75378. // Draw order
  75379. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75380. }
  75381. engine.setDepthBuffer(true);
  75382. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75383. return true;
  75384. };
  75385. LensFlareSystem.prototype.dispose = function () {
  75386. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75387. if (vertexBuffer) {
  75388. vertexBuffer.dispose();
  75389. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75390. }
  75391. if (this._indexBuffer) {
  75392. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75393. this._indexBuffer = null;
  75394. }
  75395. while (this.lensFlares.length) {
  75396. this.lensFlares[0].dispose();
  75397. }
  75398. // Remove from scene
  75399. var index = this._scene.lensFlareSystems.indexOf(this);
  75400. this._scene.lensFlareSystems.splice(index, 1);
  75401. };
  75402. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  75403. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  75404. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  75405. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  75406. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  75407. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  75408. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  75409. var parsedFlare = parsedLensFlareSystem.flares[index];
  75410. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  75411. }
  75412. return lensFlareSystem;
  75413. };
  75414. LensFlareSystem.prototype.serialize = function () {
  75415. var serializationObject = {};
  75416. serializationObject.id = this.id;
  75417. serializationObject.name = this.name;
  75418. serializationObject.emitterId = this.getEmitter().id;
  75419. serializationObject.borderLimit = this.borderLimit;
  75420. serializationObject.flares = [];
  75421. for (var index = 0; index < this.lensFlares.length; index++) {
  75422. var flare = this.lensFlares[index];
  75423. serializationObject.flares.push({
  75424. size: flare.size,
  75425. position: flare.position,
  75426. color: flare.color.asArray(),
  75427. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  75428. });
  75429. }
  75430. return serializationObject;
  75431. };
  75432. return LensFlareSystem;
  75433. }());
  75434. BABYLON.LensFlareSystem = LensFlareSystem;
  75435. })(BABYLON || (BABYLON = {}));
  75436. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  75437. var BABYLON;
  75438. (function (BABYLON) {
  75439. /**
  75440. * This is a holder class for the physics joint created by the physics plugin.
  75441. * It holds a set of functions to control the underlying joint.
  75442. */
  75443. var PhysicsJoint = /** @class */ (function () {
  75444. function PhysicsJoint(type, jointData) {
  75445. this.type = type;
  75446. this.jointData = jointData;
  75447. jointData.nativeParams = jointData.nativeParams || {};
  75448. }
  75449. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  75450. get: function () {
  75451. return this._physicsJoint;
  75452. },
  75453. set: function (newJoint) {
  75454. if (this._physicsJoint) {
  75455. //remove from the wolrd
  75456. }
  75457. this._physicsJoint = newJoint;
  75458. },
  75459. enumerable: true,
  75460. configurable: true
  75461. });
  75462. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  75463. set: function (physicsPlugin) {
  75464. this._physicsPlugin = physicsPlugin;
  75465. },
  75466. enumerable: true,
  75467. configurable: true
  75468. });
  75469. /**
  75470. * Execute a function that is physics-plugin specific.
  75471. * @param {Function} func the function that will be executed.
  75472. * It accepts two parameters: the physics world and the physics joint.
  75473. */
  75474. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  75475. func(this._physicsPlugin.world, this._physicsJoint);
  75476. };
  75477. //TODO check if the native joints are the same
  75478. //Joint Types
  75479. PhysicsJoint.DistanceJoint = 0;
  75480. PhysicsJoint.HingeJoint = 1;
  75481. PhysicsJoint.BallAndSocketJoint = 2;
  75482. PhysicsJoint.WheelJoint = 3;
  75483. PhysicsJoint.SliderJoint = 4;
  75484. //OIMO
  75485. PhysicsJoint.PrismaticJoint = 5;
  75486. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  75487. PhysicsJoint.UniversalJoint = 6;
  75488. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  75489. //Cannon
  75490. //Similar to a Ball-Joint. Different in params
  75491. PhysicsJoint.PointToPointJoint = 8;
  75492. //Cannon only at the moment
  75493. PhysicsJoint.SpringJoint = 9;
  75494. PhysicsJoint.LockJoint = 10;
  75495. return PhysicsJoint;
  75496. }());
  75497. BABYLON.PhysicsJoint = PhysicsJoint;
  75498. /**
  75499. * A class representing a physics distance joint.
  75500. */
  75501. var DistanceJoint = /** @class */ (function (_super) {
  75502. __extends(DistanceJoint, _super);
  75503. function DistanceJoint(jointData) {
  75504. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  75505. }
  75506. /**
  75507. * Update the predefined distance.
  75508. */
  75509. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  75510. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  75511. };
  75512. return DistanceJoint;
  75513. }(PhysicsJoint));
  75514. BABYLON.DistanceJoint = DistanceJoint;
  75515. var MotorEnabledJoint = /** @class */ (function (_super) {
  75516. __extends(MotorEnabledJoint, _super);
  75517. function MotorEnabledJoint(type, jointData) {
  75518. return _super.call(this, type, jointData) || this;
  75519. }
  75520. /**
  75521. * Set the motor values.
  75522. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75523. * @param {number} force the force to apply
  75524. * @param {number} maxForce max force for this motor.
  75525. */
  75526. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  75527. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75528. };
  75529. /**
  75530. * Set the motor's limits.
  75531. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75532. */
  75533. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75534. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75535. };
  75536. return MotorEnabledJoint;
  75537. }(PhysicsJoint));
  75538. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  75539. /**
  75540. * This class represents a single hinge physics joint
  75541. */
  75542. var HingeJoint = /** @class */ (function (_super) {
  75543. __extends(HingeJoint, _super);
  75544. function HingeJoint(jointData) {
  75545. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  75546. }
  75547. /**
  75548. * Set the motor values.
  75549. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75550. * @param {number} force the force to apply
  75551. * @param {number} maxForce max force for this motor.
  75552. */
  75553. HingeJoint.prototype.setMotor = function (force, maxForce) {
  75554. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75555. };
  75556. /**
  75557. * Set the motor's limits.
  75558. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75559. */
  75560. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75561. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75562. };
  75563. return HingeJoint;
  75564. }(MotorEnabledJoint));
  75565. BABYLON.HingeJoint = HingeJoint;
  75566. /**
  75567. * This class represents a dual hinge physics joint (same as wheel joint)
  75568. */
  75569. var Hinge2Joint = /** @class */ (function (_super) {
  75570. __extends(Hinge2Joint, _super);
  75571. function Hinge2Joint(jointData) {
  75572. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  75573. }
  75574. /**
  75575. * Set the motor values.
  75576. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75577. * @param {number} force the force to apply
  75578. * @param {number} maxForce max force for this motor.
  75579. * @param {motorIndex} the motor's index, 0 or 1.
  75580. */
  75581. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  75582. if (motorIndex === void 0) { motorIndex = 0; }
  75583. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  75584. };
  75585. /**
  75586. * Set the motor limits.
  75587. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75588. * @param {number} upperLimit the upper limit
  75589. * @param {number} lowerLimit lower limit
  75590. * @param {motorIndex} the motor's index, 0 or 1.
  75591. */
  75592. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  75593. if (motorIndex === void 0) { motorIndex = 0; }
  75594. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  75595. };
  75596. return Hinge2Joint;
  75597. }(MotorEnabledJoint));
  75598. BABYLON.Hinge2Joint = Hinge2Joint;
  75599. })(BABYLON || (BABYLON = {}));
  75600. //# sourceMappingURL=babylon.physicsJoint.js.map
  75601. var BABYLON;
  75602. (function (BABYLON) {
  75603. var PhysicsImpostor = /** @class */ (function () {
  75604. function PhysicsImpostor(object, type, _options, _scene) {
  75605. if (_options === void 0) { _options = { mass: 0 }; }
  75606. var _this = this;
  75607. this.object = object;
  75608. this.type = type;
  75609. this._options = _options;
  75610. this._scene = _scene;
  75611. this._bodyUpdateRequired = false;
  75612. this._onBeforePhysicsStepCallbacks = new Array();
  75613. this._onAfterPhysicsStepCallbacks = new Array();
  75614. this._onPhysicsCollideCallbacks = [];
  75615. this._deltaPosition = BABYLON.Vector3.Zero();
  75616. this._isDisposed = false;
  75617. //temp variables for parent rotation calculations
  75618. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  75619. this._tmpQuat = new BABYLON.Quaternion();
  75620. this._tmpQuat2 = new BABYLON.Quaternion();
  75621. /**
  75622. * this function is executed by the physics engine.
  75623. */
  75624. this.beforeStep = function () {
  75625. if (!_this._physicsEngine) {
  75626. return;
  75627. }
  75628. _this.object.translate(_this._deltaPosition, -1);
  75629. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  75630. _this.object.computeWorldMatrix(false);
  75631. if (_this.object.parent && _this.object.rotationQuaternion) {
  75632. _this.getParentsRotation();
  75633. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  75634. }
  75635. else {
  75636. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  75637. }
  75638. if (!_this._options.disableBidirectionalTransformation) {
  75639. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  75640. }
  75641. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  75642. func(_this);
  75643. });
  75644. };
  75645. /**
  75646. * this function is executed by the physics engine.
  75647. */
  75648. this.afterStep = function () {
  75649. if (!_this._physicsEngine) {
  75650. return;
  75651. }
  75652. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  75653. func(_this);
  75654. });
  75655. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  75656. // object has now its world rotation. needs to be converted to local.
  75657. if (_this.object.parent && _this.object.rotationQuaternion) {
  75658. _this.getParentsRotation();
  75659. _this._tmpQuat.conjugateInPlace();
  75660. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  75661. }
  75662. // take the position set and make it the absolute position of this object.
  75663. _this.object.setAbsolutePosition(_this.object.position);
  75664. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  75665. _this.object.translate(_this._deltaPosition, 1);
  75666. };
  75667. /**
  75668. * Legacy collision detection event support
  75669. */
  75670. this.onCollideEvent = null;
  75671. //event and body object due to cannon's event-based architecture.
  75672. this.onCollide = function (e) {
  75673. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  75674. return;
  75675. }
  75676. if (!_this._physicsEngine) {
  75677. return;
  75678. }
  75679. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  75680. if (otherImpostor) {
  75681. // Legacy collision detection event support
  75682. if (_this.onCollideEvent) {
  75683. _this.onCollideEvent(_this, otherImpostor);
  75684. }
  75685. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  75686. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  75687. }).forEach(function (obj) {
  75688. obj.callback(_this, otherImpostor);
  75689. });
  75690. }
  75691. };
  75692. //sanity check!
  75693. if (!this.object) {
  75694. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  75695. return;
  75696. }
  75697. //legacy support for old syntax.
  75698. if (!this._scene && object.getScene) {
  75699. this._scene = object.getScene();
  75700. }
  75701. if (!this._scene) {
  75702. return;
  75703. }
  75704. this._physicsEngine = this._scene.getPhysicsEngine();
  75705. if (!this._physicsEngine) {
  75706. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  75707. }
  75708. else {
  75709. //set the object's quaternion, if not set
  75710. if (!this.object.rotationQuaternion) {
  75711. if (this.object.rotation) {
  75712. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  75713. }
  75714. else {
  75715. this.object.rotationQuaternion = new BABYLON.Quaternion();
  75716. }
  75717. }
  75718. //default options params
  75719. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  75720. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  75721. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  75722. this._joints = [];
  75723. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  75724. if (!this.object.parent || this._options.ignoreParent) {
  75725. this._init();
  75726. }
  75727. else if (this.object.parent.physicsImpostor) {
  75728. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  75729. }
  75730. }
  75731. }
  75732. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  75733. get: function () {
  75734. return this._isDisposed;
  75735. },
  75736. enumerable: true,
  75737. configurable: true
  75738. });
  75739. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  75740. get: function () {
  75741. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  75742. },
  75743. set: function (value) {
  75744. this.setMass(value);
  75745. },
  75746. enumerable: true,
  75747. configurable: true
  75748. });
  75749. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  75750. get: function () {
  75751. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  75752. },
  75753. set: function (value) {
  75754. if (!this._physicsEngine) {
  75755. return;
  75756. }
  75757. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  75758. },
  75759. enumerable: true,
  75760. configurable: true
  75761. });
  75762. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  75763. get: function () {
  75764. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  75765. },
  75766. set: function (value) {
  75767. if (!this._physicsEngine) {
  75768. return;
  75769. }
  75770. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  75771. },
  75772. enumerable: true,
  75773. configurable: true
  75774. });
  75775. /**
  75776. * This function will completly initialize this impostor.
  75777. * It will create a new body - but only if this mesh has no parent.
  75778. * If it has, this impostor will not be used other than to define the impostor
  75779. * of the child mesh.
  75780. */
  75781. PhysicsImpostor.prototype._init = function () {
  75782. if (!this._physicsEngine) {
  75783. return;
  75784. }
  75785. this._physicsEngine.removeImpostor(this);
  75786. this.physicsBody = null;
  75787. this._parent = this._parent || this._getPhysicsParent();
  75788. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  75789. this._physicsEngine.addImpostor(this);
  75790. }
  75791. };
  75792. PhysicsImpostor.prototype._getPhysicsParent = function () {
  75793. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  75794. var parentMesh = this.object.parent;
  75795. return parentMesh.physicsImpostor;
  75796. }
  75797. return null;
  75798. };
  75799. /**
  75800. * Should a new body be generated.
  75801. */
  75802. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  75803. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  75804. };
  75805. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  75806. this.forceUpdate();
  75807. };
  75808. /**
  75809. * Force a regeneration of this or the parent's impostor's body.
  75810. * Use under cautious - This will remove all joints already implemented.
  75811. */
  75812. PhysicsImpostor.prototype.forceUpdate = function () {
  75813. this._init();
  75814. if (this.parent && !this._options.ignoreParent) {
  75815. this.parent.forceUpdate();
  75816. }
  75817. };
  75818. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  75819. /*public get mesh(): AbstractMesh {
  75820. return this._mesh;
  75821. }*/
  75822. /**
  75823. * Gets the body that holds this impostor. Either its own, or its parent.
  75824. */
  75825. get: function () {
  75826. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  75827. },
  75828. /**
  75829. * Set the physics body. Used mainly by the physics engine/plugin
  75830. */
  75831. set: function (physicsBody) {
  75832. if (this._physicsBody && this._physicsEngine) {
  75833. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  75834. }
  75835. this._physicsBody = physicsBody;
  75836. this.resetUpdateFlags();
  75837. },
  75838. enumerable: true,
  75839. configurable: true
  75840. });
  75841. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  75842. get: function () {
  75843. return !this._options.ignoreParent && this._parent ? this._parent : null;
  75844. },
  75845. set: function (value) {
  75846. this._parent = value;
  75847. },
  75848. enumerable: true,
  75849. configurable: true
  75850. });
  75851. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  75852. this._bodyUpdateRequired = false;
  75853. };
  75854. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  75855. if (this.object.getBoundingInfo) {
  75856. var q = this.object.rotationQuaternion;
  75857. //reset rotation
  75858. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  75859. //calculate the world matrix with no rotation
  75860. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75861. var boundingInfo = this.object.getBoundingInfo();
  75862. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  75863. //bring back the rotation
  75864. this.object.rotationQuaternion = q;
  75865. //calculate the world matrix with the new rotation
  75866. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75867. return size;
  75868. }
  75869. else {
  75870. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  75871. }
  75872. };
  75873. PhysicsImpostor.prototype.getObjectCenter = function () {
  75874. if (this.object.getBoundingInfo) {
  75875. var boundingInfo = this.object.getBoundingInfo();
  75876. return boundingInfo.boundingBox.centerWorld;
  75877. }
  75878. else {
  75879. return this.object.position;
  75880. }
  75881. };
  75882. /**
  75883. * Get a specific parametes from the options parameter.
  75884. */
  75885. PhysicsImpostor.prototype.getParam = function (paramName) {
  75886. return this._options[paramName];
  75887. };
  75888. /**
  75889. * Sets a specific parameter in the options given to the physics plugin
  75890. */
  75891. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  75892. this._options[paramName] = value;
  75893. this._bodyUpdateRequired = true;
  75894. };
  75895. /**
  75896. * Specifically change the body's mass option. Won't recreate the physics body object
  75897. */
  75898. PhysicsImpostor.prototype.setMass = function (mass) {
  75899. if (this.getParam("mass") !== mass) {
  75900. this.setParam("mass", mass);
  75901. }
  75902. if (this._physicsEngine) {
  75903. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  75904. }
  75905. };
  75906. PhysicsImpostor.prototype.getLinearVelocity = function () {
  75907. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  75908. };
  75909. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  75910. if (this._physicsEngine) {
  75911. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  75912. }
  75913. };
  75914. PhysicsImpostor.prototype.getAngularVelocity = function () {
  75915. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  75916. };
  75917. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  75918. if (this._physicsEngine) {
  75919. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  75920. }
  75921. };
  75922. /**
  75923. * Execute a function with the physics plugin native code.
  75924. * Provide a function the will have two variables - the world object and the physics body object.
  75925. */
  75926. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  75927. if (this._physicsEngine) {
  75928. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  75929. }
  75930. };
  75931. /**
  75932. * Register a function that will be executed before the physics world is stepping forward.
  75933. */
  75934. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  75935. this._onBeforePhysicsStepCallbacks.push(func);
  75936. };
  75937. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  75938. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  75939. if (index > -1) {
  75940. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  75941. }
  75942. else {
  75943. BABYLON.Tools.Warn("Function to remove was not found");
  75944. }
  75945. };
  75946. /**
  75947. * Register a function that will be executed after the physics step
  75948. */
  75949. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  75950. this._onAfterPhysicsStepCallbacks.push(func);
  75951. };
  75952. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  75953. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  75954. if (index > -1) {
  75955. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  75956. }
  75957. else {
  75958. BABYLON.Tools.Warn("Function to remove was not found");
  75959. }
  75960. };
  75961. /**
  75962. * register a function that will be executed when this impostor collides against a different body.
  75963. */
  75964. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  75965. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75966. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  75967. };
  75968. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  75969. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75970. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  75971. if (index > -1) {
  75972. this._onPhysicsCollideCallbacks.splice(index, 1);
  75973. }
  75974. else {
  75975. BABYLON.Tools.Warn("Function to remove was not found");
  75976. }
  75977. };
  75978. PhysicsImpostor.prototype.getParentsRotation = function () {
  75979. var parent = this.object.parent;
  75980. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  75981. while (parent) {
  75982. if (parent.rotationQuaternion) {
  75983. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  75984. }
  75985. else {
  75986. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  75987. }
  75988. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  75989. parent = parent.parent;
  75990. }
  75991. return this._tmpQuat;
  75992. };
  75993. /**
  75994. * Apply a force
  75995. */
  75996. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  75997. if (this._physicsEngine) {
  75998. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  75999. }
  76000. return this;
  76001. };
  76002. /**
  76003. * Apply an impulse
  76004. */
  76005. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  76006. if (this._physicsEngine) {
  76007. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  76008. }
  76009. return this;
  76010. };
  76011. /**
  76012. * A help function to create a joint.
  76013. */
  76014. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  76015. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  76016. this.addJoint(otherImpostor, joint);
  76017. return this;
  76018. };
  76019. /**
  76020. * Add a joint to this impostor with a different impostor.
  76021. */
  76022. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  76023. this._joints.push({
  76024. otherImpostor: otherImpostor,
  76025. joint: joint
  76026. });
  76027. if (this._physicsEngine) {
  76028. this._physicsEngine.addJoint(this, otherImpostor, joint);
  76029. }
  76030. return this;
  76031. };
  76032. /**
  76033. * Will keep this body still, in a sleep mode.
  76034. */
  76035. PhysicsImpostor.prototype.sleep = function () {
  76036. if (this._physicsEngine) {
  76037. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  76038. }
  76039. return this;
  76040. };
  76041. /**
  76042. * Wake the body up.
  76043. */
  76044. PhysicsImpostor.prototype.wakeUp = function () {
  76045. if (this._physicsEngine) {
  76046. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  76047. }
  76048. return this;
  76049. };
  76050. PhysicsImpostor.prototype.clone = function (newObject) {
  76051. if (!newObject)
  76052. return null;
  76053. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  76054. };
  76055. PhysicsImpostor.prototype.dispose = function () {
  76056. var _this = this;
  76057. //no dispose if no physics engine is available.
  76058. if (!this._physicsEngine) {
  76059. return;
  76060. }
  76061. this._joints.forEach(function (j) {
  76062. if (_this._physicsEngine) {
  76063. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  76064. }
  76065. });
  76066. //dispose the physics body
  76067. this._physicsEngine.removeImpostor(this);
  76068. if (this.parent) {
  76069. this.parent.forceUpdate();
  76070. }
  76071. else {
  76072. /*this._object.getChildMeshes().forEach(function(mesh) {
  76073. if (mesh.physicsImpostor) {
  76074. if (disposeChildren) {
  76075. mesh.physicsImpostor.dispose();
  76076. mesh.physicsImpostor = null;
  76077. }
  76078. }
  76079. })*/
  76080. }
  76081. this._isDisposed = true;
  76082. };
  76083. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  76084. this._deltaPosition.copyFrom(position);
  76085. };
  76086. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  76087. if (!this._deltaRotation) {
  76088. this._deltaRotation = new BABYLON.Quaternion();
  76089. }
  76090. this._deltaRotation.copyFrom(rotation);
  76091. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  76092. };
  76093. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  76094. if (this._physicsEngine) {
  76095. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  76096. }
  76097. return this;
  76098. };
  76099. PhysicsImpostor.prototype.getRadius = function () {
  76100. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  76101. };
  76102. /**
  76103. * Sync a bone with this impostor
  76104. * @param bone The bone to sync to the impostor.
  76105. * @param boneMesh The mesh that the bone is influencing.
  76106. * @param jointPivot The pivot of the joint / bone in local space.
  76107. * @param distToJoint Optional distance from the impostor to the joint.
  76108. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76109. */
  76110. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  76111. var tempVec = PhysicsImpostor._tmpVecs[0];
  76112. var mesh = this.object;
  76113. if (mesh.rotationQuaternion) {
  76114. if (adjustRotation) {
  76115. var tempQuat = PhysicsImpostor._tmpQuat;
  76116. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  76117. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  76118. }
  76119. else {
  76120. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  76121. }
  76122. }
  76123. tempVec.x = 0;
  76124. tempVec.y = 0;
  76125. tempVec.z = 0;
  76126. if (jointPivot) {
  76127. tempVec.x = jointPivot.x;
  76128. tempVec.y = jointPivot.y;
  76129. tempVec.z = jointPivot.z;
  76130. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  76131. if (distToJoint === undefined || distToJoint === null) {
  76132. distToJoint = jointPivot.length();
  76133. }
  76134. tempVec.x *= distToJoint;
  76135. tempVec.y *= distToJoint;
  76136. tempVec.z *= distToJoint;
  76137. }
  76138. if (bone.getParent()) {
  76139. tempVec.addInPlace(mesh.getAbsolutePosition());
  76140. bone.setAbsolutePosition(tempVec, boneMesh);
  76141. }
  76142. else {
  76143. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  76144. boneMesh.position.x -= tempVec.x;
  76145. boneMesh.position.y -= tempVec.y;
  76146. boneMesh.position.z -= tempVec.z;
  76147. }
  76148. };
  76149. /**
  76150. * Sync impostor to a bone
  76151. * @param bone The bone that the impostor will be synced to.
  76152. * @param boneMesh The mesh that the bone is influencing.
  76153. * @param jointPivot The pivot of the joint / bone in local space.
  76154. * @param distToJoint Optional distance from the impostor to the joint.
  76155. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76156. * @param boneAxis Optional vector3 axis the bone is aligned with
  76157. */
  76158. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  76159. var mesh = this.object;
  76160. if (mesh.rotationQuaternion) {
  76161. if (adjustRotation) {
  76162. var tempQuat = PhysicsImpostor._tmpQuat;
  76163. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  76164. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  76165. }
  76166. else {
  76167. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  76168. }
  76169. }
  76170. var pos = PhysicsImpostor._tmpVecs[0];
  76171. var boneDir = PhysicsImpostor._tmpVecs[1];
  76172. if (!boneAxis) {
  76173. boneAxis = PhysicsImpostor._tmpVecs[2];
  76174. boneAxis.x = 0;
  76175. boneAxis.y = 1;
  76176. boneAxis.z = 0;
  76177. }
  76178. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  76179. bone.getAbsolutePositionToRef(boneMesh, pos);
  76180. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  76181. distToJoint = jointPivot.length();
  76182. }
  76183. if (distToJoint !== undefined && distToJoint !== null) {
  76184. pos.x += boneDir.x * distToJoint;
  76185. pos.y += boneDir.y * distToJoint;
  76186. pos.z += boneDir.z * distToJoint;
  76187. }
  76188. mesh.setAbsolutePosition(pos);
  76189. };
  76190. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  76191. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  76192. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76193. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  76194. //Impostor types
  76195. PhysicsImpostor.NoImpostor = 0;
  76196. PhysicsImpostor.SphereImpostor = 1;
  76197. PhysicsImpostor.BoxImpostor = 2;
  76198. PhysicsImpostor.PlaneImpostor = 3;
  76199. PhysicsImpostor.MeshImpostor = 4;
  76200. PhysicsImpostor.CylinderImpostor = 7;
  76201. PhysicsImpostor.ParticleImpostor = 8;
  76202. PhysicsImpostor.HeightmapImpostor = 9;
  76203. return PhysicsImpostor;
  76204. }());
  76205. BABYLON.PhysicsImpostor = PhysicsImpostor;
  76206. })(BABYLON || (BABYLON = {}));
  76207. //# sourceMappingURL=babylon.physicsImpostor.js.map
  76208. var BABYLON;
  76209. (function (BABYLON) {
  76210. var PhysicsEngine = /** @class */ (function () {
  76211. function PhysicsEngine(gravity, _physicsPlugin) {
  76212. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  76213. this._physicsPlugin = _physicsPlugin;
  76214. //new methods and parameters
  76215. this._impostors = [];
  76216. this._joints = [];
  76217. if (!this._physicsPlugin.isSupported()) {
  76218. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  76219. + "Please make sure it is included.");
  76220. }
  76221. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  76222. this.setGravity(gravity);
  76223. this.setTimeStep();
  76224. }
  76225. PhysicsEngine.prototype.setGravity = function (gravity) {
  76226. this.gravity = gravity;
  76227. this._physicsPlugin.setGravity(this.gravity);
  76228. };
  76229. /**
  76230. * Set the time step of the physics engine.
  76231. * default is 1/60.
  76232. * To slow it down, enter 1/600 for example.
  76233. * To speed it up, 1/30
  76234. * @param {number} newTimeStep the new timestep to apply to this world.
  76235. */
  76236. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  76237. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  76238. this._physicsPlugin.setTimeStep(newTimeStep);
  76239. };
  76240. /**
  76241. * Get the time step of the physics engine.
  76242. */
  76243. PhysicsEngine.prototype.getTimeStep = function () {
  76244. return this._physicsPlugin.getTimeStep();
  76245. };
  76246. PhysicsEngine.prototype.dispose = function () {
  76247. this._impostors.forEach(function (impostor) {
  76248. impostor.dispose();
  76249. });
  76250. this._physicsPlugin.dispose();
  76251. };
  76252. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  76253. return this._physicsPlugin.name;
  76254. };
  76255. /**
  76256. * Adding a new impostor for the impostor tracking.
  76257. * This will be done by the impostor itself.
  76258. * @param {PhysicsImpostor} impostor the impostor to add
  76259. */
  76260. PhysicsEngine.prototype.addImpostor = function (impostor) {
  76261. impostor.uniqueId = this._impostors.push(impostor);
  76262. //if no parent, generate the body
  76263. if (!impostor.parent) {
  76264. this._physicsPlugin.generatePhysicsBody(impostor);
  76265. }
  76266. };
  76267. /**
  76268. * Remove an impostor from the engine.
  76269. * This impostor and its mesh will not longer be updated by the physics engine.
  76270. * @param {PhysicsImpostor} impostor the impostor to remove
  76271. */
  76272. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  76273. var index = this._impostors.indexOf(impostor);
  76274. if (index > -1) {
  76275. var removed = this._impostors.splice(index, 1);
  76276. //Is it needed?
  76277. if (removed.length) {
  76278. //this will also remove it from the world.
  76279. removed[0].physicsBody = null;
  76280. }
  76281. }
  76282. };
  76283. /**
  76284. * Add a joint to the physics engine
  76285. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  76286. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  76287. * @param {PhysicsJoint} the joint that will connect both impostors.
  76288. */
  76289. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  76290. var impostorJoint = {
  76291. mainImpostor: mainImpostor,
  76292. connectedImpostor: connectedImpostor,
  76293. joint: joint
  76294. };
  76295. joint.physicsPlugin = this._physicsPlugin;
  76296. this._joints.push(impostorJoint);
  76297. this._physicsPlugin.generateJoint(impostorJoint);
  76298. };
  76299. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  76300. var matchingJoints = this._joints.filter(function (impostorJoint) {
  76301. return (impostorJoint.connectedImpostor === connectedImpostor
  76302. && impostorJoint.joint === joint
  76303. && impostorJoint.mainImpostor === mainImpostor);
  76304. });
  76305. if (matchingJoints.length) {
  76306. this._physicsPlugin.removeJoint(matchingJoints[0]);
  76307. //TODO remove it from the list as well
  76308. }
  76309. };
  76310. /**
  76311. * Called by the scene. no need to call it.
  76312. */
  76313. PhysicsEngine.prototype._step = function (delta) {
  76314. var _this = this;
  76315. //check if any mesh has no body / requires an update
  76316. this._impostors.forEach(function (impostor) {
  76317. if (impostor.isBodyInitRequired()) {
  76318. _this._physicsPlugin.generatePhysicsBody(impostor);
  76319. }
  76320. });
  76321. if (delta > 0.1) {
  76322. delta = 0.1;
  76323. }
  76324. else if (delta <= 0) {
  76325. delta = 1.0 / 60.0;
  76326. }
  76327. this._physicsPlugin.executeStep(delta, this._impostors);
  76328. };
  76329. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76330. return this._physicsPlugin;
  76331. };
  76332. PhysicsEngine.prototype.getImpostors = function () {
  76333. return this._impostors;
  76334. };
  76335. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76336. for (var i = 0; i < this._impostors.length; ++i) {
  76337. if (this._impostors[i].object === object) {
  76338. return this._impostors[i];
  76339. }
  76340. }
  76341. return null;
  76342. };
  76343. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76344. for (var i = 0; i < this._impostors.length; ++i) {
  76345. if (this._impostors[i].physicsBody === body) {
  76346. return this._impostors[i];
  76347. }
  76348. }
  76349. return null;
  76350. };
  76351. // Statics
  76352. PhysicsEngine.Epsilon = 0.001;
  76353. return PhysicsEngine;
  76354. }());
  76355. BABYLON.PhysicsEngine = PhysicsEngine;
  76356. })(BABYLON || (BABYLON = {}));
  76357. //# sourceMappingURL=babylon.physicsEngine.js.map
  76358. var BABYLON;
  76359. (function (BABYLON) {
  76360. var PhysicsHelper = /** @class */ (function () {
  76361. function PhysicsHelper(scene) {
  76362. this._scene = scene;
  76363. this._physicsEngine = this._scene.getPhysicsEngine();
  76364. if (!this._physicsEngine) {
  76365. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  76366. }
  76367. }
  76368. /**
  76369. * @param {Vector3} origin the origin of the explosion
  76370. * @param {number} radius the explosion radius
  76371. * @param {number} strength the explosion strength
  76372. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76373. */
  76374. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  76375. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76376. if (!this._physicsEngine) {
  76377. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  76378. return null;
  76379. }
  76380. var impostors = this._physicsEngine.getImpostors();
  76381. if (impostors.length === 0) {
  76382. return null;
  76383. }
  76384. var event = new PhysicsRadialExplosionEvent(this._scene);
  76385. impostors.forEach(function (impostor) {
  76386. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76387. if (!impostorForceAndContactPoint) {
  76388. return;
  76389. }
  76390. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76391. });
  76392. event.dispose(false);
  76393. return event;
  76394. };
  76395. /**
  76396. * @param {Vector3} origin the origin of the explosion
  76397. * @param {number} radius the explosion radius
  76398. * @param {number} strength the explosion strength
  76399. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76400. */
  76401. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  76402. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76403. if (!this._physicsEngine) {
  76404. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76405. return null;
  76406. }
  76407. var impostors = this._physicsEngine.getImpostors();
  76408. if (impostors.length === 0) {
  76409. return null;
  76410. }
  76411. var event = new PhysicsRadialExplosionEvent(this._scene);
  76412. impostors.forEach(function (impostor) {
  76413. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76414. if (!impostorForceAndContactPoint) {
  76415. return;
  76416. }
  76417. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76418. });
  76419. event.dispose(false);
  76420. return event;
  76421. };
  76422. /**
  76423. * @param {Vector3} origin the origin of the explosion
  76424. * @param {number} radius the explosion radius
  76425. * @param {number} strength the explosion strength
  76426. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76427. */
  76428. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  76429. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76430. if (!this._physicsEngine) {
  76431. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76432. return null;
  76433. }
  76434. var impostors = this._physicsEngine.getImpostors();
  76435. if (impostors.length === 0) {
  76436. return null;
  76437. }
  76438. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  76439. event.dispose(false);
  76440. return event;
  76441. };
  76442. /**
  76443. * @param {Vector3} origin the origin of the updraft
  76444. * @param {number} radius the radius of the updraft
  76445. * @param {number} strength the strength of the updraft
  76446. * @param {number} height the height of the updraft
  76447. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  76448. */
  76449. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  76450. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  76451. if (!this._physicsEngine) {
  76452. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76453. return null;
  76454. }
  76455. if (this._physicsEngine.getImpostors().length === 0) {
  76456. return null;
  76457. }
  76458. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  76459. event.dispose(false);
  76460. return event;
  76461. };
  76462. /**
  76463. * @param {Vector3} origin the of the vortex
  76464. * @param {number} radius the radius of the vortex
  76465. * @param {number} strength the strength of the vortex
  76466. * @param {number} height the height of the vortex
  76467. */
  76468. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  76469. if (!this._physicsEngine) {
  76470. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76471. return null;
  76472. }
  76473. if (this._physicsEngine.getImpostors().length === 0) {
  76474. return null;
  76475. }
  76476. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  76477. event.dispose(false);
  76478. return event;
  76479. };
  76480. return PhysicsHelper;
  76481. }());
  76482. BABYLON.PhysicsHelper = PhysicsHelper;
  76483. /***** Radial explosion *****/
  76484. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  76485. function PhysicsRadialExplosionEvent(scene) {
  76486. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  76487. this._rays = [];
  76488. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  76489. this._scene = scene;
  76490. }
  76491. /**
  76492. * Returns the data related to the radial explosion event (sphere & rays).
  76493. * @returns {PhysicsRadialExplosionEventData}
  76494. */
  76495. PhysicsRadialExplosionEvent.prototype.getData = function () {
  76496. this._dataFetched = true;
  76497. return {
  76498. sphere: this._sphere,
  76499. rays: this._rays,
  76500. };
  76501. };
  76502. /**
  76503. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  76504. * @param impostor
  76505. * @param {Vector3} origin the origin of the explosion
  76506. * @param {number} radius the explosion radius
  76507. * @param {number} strength the explosion strength
  76508. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  76509. * @returns {Nullable<PhysicsForceAndContactPoint>}
  76510. */
  76511. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  76512. if (impostor.mass === 0) {
  76513. return null;
  76514. }
  76515. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  76516. return null;
  76517. }
  76518. if (impostor.object.getClassName() !== 'Mesh') {
  76519. return null;
  76520. }
  76521. var impostorObject = impostor.object;
  76522. var impostorObjectCenter = impostor.getObjectCenter();
  76523. var direction = impostorObjectCenter.subtract(origin);
  76524. var ray = new BABYLON.Ray(origin, direction, radius);
  76525. this._rays.push(ray);
  76526. var hit = ray.intersectsMesh(impostorObject);
  76527. var contactPoint = hit.pickedPoint;
  76528. if (!contactPoint) {
  76529. return null;
  76530. }
  76531. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  76532. if (distanceFromOrigin > radius) {
  76533. return null;
  76534. }
  76535. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  76536. ? strength
  76537. : strength * (1 - (distanceFromOrigin / radius));
  76538. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76539. return { force: force, contactPoint: contactPoint };
  76540. };
  76541. /**
  76542. * Disposes the sphere.
  76543. * @param {bolean} force
  76544. */
  76545. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  76546. var _this = this;
  76547. if (force === void 0) { force = true; }
  76548. if (force) {
  76549. this._sphere.dispose();
  76550. }
  76551. else {
  76552. setTimeout(function () {
  76553. if (!_this._dataFetched) {
  76554. _this._sphere.dispose();
  76555. }
  76556. }, 0);
  76557. }
  76558. };
  76559. /*** Helpers ***/
  76560. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  76561. if (!this._sphere) {
  76562. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  76563. this._sphere.isVisible = false;
  76564. }
  76565. };
  76566. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  76567. var impostorObject = impostor.object;
  76568. this._prepareSphere();
  76569. this._sphere.position = origin;
  76570. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  76571. this._sphere._updateBoundingInfo();
  76572. this._sphere.computeWorldMatrix(true);
  76573. return this._sphere.intersectsMesh(impostorObject, true);
  76574. };
  76575. return PhysicsRadialExplosionEvent;
  76576. }());
  76577. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  76578. /***** Gravitational Field *****/
  76579. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  76580. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  76581. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76582. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76583. this._physicsHelper = physicsHelper;
  76584. this._scene = scene;
  76585. this._origin = origin;
  76586. this._radius = radius;
  76587. this._strength = strength;
  76588. this._falloff = falloff;
  76589. this._tickCallback = this._tick.bind(this);
  76590. }
  76591. /**
  76592. * Returns the data related to the gravitational field event (sphere).
  76593. * @returns {PhysicsGravitationalFieldEventData}
  76594. */
  76595. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  76596. this._dataFetched = true;
  76597. return {
  76598. sphere: this._sphere,
  76599. };
  76600. };
  76601. /**
  76602. * Enables the gravitational field.
  76603. */
  76604. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  76605. this._tickCallback.call(this);
  76606. this._scene.registerBeforeRender(this._tickCallback);
  76607. };
  76608. /**
  76609. * Disables the gravitational field.
  76610. */
  76611. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  76612. this._scene.unregisterBeforeRender(this._tickCallback);
  76613. };
  76614. /**
  76615. * Disposes the sphere.
  76616. * @param {bolean} force
  76617. */
  76618. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  76619. var _this = this;
  76620. if (force === void 0) { force = true; }
  76621. if (force) {
  76622. this._sphere.dispose();
  76623. }
  76624. else {
  76625. setTimeout(function () {
  76626. if (!_this._dataFetched) {
  76627. _this._sphere.dispose();
  76628. }
  76629. }, 0);
  76630. }
  76631. };
  76632. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  76633. // Since the params won't change, we fetch the event only once
  76634. if (this._sphere) {
  76635. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76636. }
  76637. else {
  76638. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76639. if (radialExplosionEvent) {
  76640. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  76641. }
  76642. }
  76643. };
  76644. return PhysicsGravitationalFieldEvent;
  76645. }());
  76646. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  76647. /***** Updraft *****/
  76648. var PhysicsUpdraftEvent = /** @class */ (function () {
  76649. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  76650. this._scene = _scene;
  76651. this._origin = _origin;
  76652. this._radius = _radius;
  76653. this._strength = _strength;
  76654. this._height = _height;
  76655. this._updraftMode = _updraftMode;
  76656. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76657. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  76658. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76659. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76660. this._physicsEngine = this._scene.getPhysicsEngine();
  76661. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76662. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76663. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76664. this._originDirection = this._origin.subtract(this._originTop).normalize();
  76665. }
  76666. this._tickCallback = this._tick.bind(this);
  76667. }
  76668. /**
  76669. * Returns the data related to the updraft event (cylinder).
  76670. * @returns {PhysicsUpdraftEventData}
  76671. */
  76672. PhysicsUpdraftEvent.prototype.getData = function () {
  76673. this._dataFetched = true;
  76674. return {
  76675. cylinder: this._cylinder,
  76676. };
  76677. };
  76678. /**
  76679. * Enables the updraft.
  76680. */
  76681. PhysicsUpdraftEvent.prototype.enable = function () {
  76682. this._tickCallback.call(this);
  76683. this._scene.registerBeforeRender(this._tickCallback);
  76684. };
  76685. /**
  76686. * Disables the cortex.
  76687. */
  76688. PhysicsUpdraftEvent.prototype.disable = function () {
  76689. this._scene.unregisterBeforeRender(this._tickCallback);
  76690. };
  76691. /**
  76692. * Disposes the sphere.
  76693. * @param {bolean} force
  76694. */
  76695. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  76696. var _this = this;
  76697. if (force === void 0) { force = true; }
  76698. if (force) {
  76699. this._cylinder.dispose();
  76700. }
  76701. else {
  76702. setTimeout(function () {
  76703. if (!_this._dataFetched) {
  76704. _this._cylinder.dispose();
  76705. }
  76706. }, 0);
  76707. }
  76708. };
  76709. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76710. if (impostor.mass === 0) {
  76711. return null;
  76712. }
  76713. if (!this._intersectsWithCylinder(impostor)) {
  76714. return null;
  76715. }
  76716. var impostorObjectCenter = impostor.getObjectCenter();
  76717. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76718. var direction = this._originDirection;
  76719. }
  76720. else {
  76721. var direction = impostorObjectCenter.subtract(this._originTop);
  76722. }
  76723. var multiplier = this._strength * -1;
  76724. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76725. return { force: force, contactPoint: impostorObjectCenter };
  76726. };
  76727. PhysicsUpdraftEvent.prototype._tick = function () {
  76728. var _this = this;
  76729. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76730. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76731. if (!impostorForceAndContactPoint) {
  76732. return;
  76733. }
  76734. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76735. });
  76736. };
  76737. /*** Helpers ***/
  76738. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  76739. if (!this._cylinder) {
  76740. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  76741. height: this._height,
  76742. diameter: this._radius * 2,
  76743. }, this._scene);
  76744. this._cylinder.isVisible = false;
  76745. }
  76746. };
  76747. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  76748. var impostorObject = impostor.object;
  76749. this._prepareCylinder();
  76750. this._cylinder.position = this._cylinderPosition;
  76751. return this._cylinder.intersectsMesh(impostorObject, true);
  76752. };
  76753. return PhysicsUpdraftEvent;
  76754. }());
  76755. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  76756. /***** Vortex *****/
  76757. var PhysicsVortexEvent = /** @class */ (function () {
  76758. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  76759. this._scene = _scene;
  76760. this._origin = _origin;
  76761. this._radius = _radius;
  76762. this._strength = _strength;
  76763. this._height = _height;
  76764. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76765. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  76766. this._updraftMultiplier = 0.02;
  76767. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76768. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76769. this._physicsEngine = this._scene.getPhysicsEngine();
  76770. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76771. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76772. this._tickCallback = this._tick.bind(this);
  76773. }
  76774. /**
  76775. * Returns the data related to the vortex event (cylinder).
  76776. * @returns {PhysicsVortexEventData}
  76777. */
  76778. PhysicsVortexEvent.prototype.getData = function () {
  76779. this._dataFetched = true;
  76780. return {
  76781. cylinder: this._cylinder,
  76782. };
  76783. };
  76784. /**
  76785. * Enables the vortex.
  76786. */
  76787. PhysicsVortexEvent.prototype.enable = function () {
  76788. this._tickCallback.call(this);
  76789. this._scene.registerBeforeRender(this._tickCallback);
  76790. };
  76791. /**
  76792. * Disables the cortex.
  76793. */
  76794. PhysicsVortexEvent.prototype.disable = function () {
  76795. this._scene.unregisterBeforeRender(this._tickCallback);
  76796. };
  76797. /**
  76798. * Disposes the sphere.
  76799. * @param {bolean} force
  76800. */
  76801. PhysicsVortexEvent.prototype.dispose = function (force) {
  76802. var _this = this;
  76803. if (force === void 0) { force = true; }
  76804. if (force) {
  76805. this._cylinder.dispose();
  76806. }
  76807. else {
  76808. setTimeout(function () {
  76809. if (!_this._dataFetched) {
  76810. _this._cylinder.dispose();
  76811. }
  76812. }, 0);
  76813. }
  76814. };
  76815. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76816. if (impostor.mass === 0) {
  76817. return null;
  76818. }
  76819. if (!this._intersectsWithCylinder(impostor)) {
  76820. return null;
  76821. }
  76822. if (impostor.object.getClassName() !== 'Mesh') {
  76823. return null;
  76824. }
  76825. var impostorObject = impostor.object;
  76826. var impostorObjectCenter = impostor.getObjectCenter();
  76827. 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)
  76828. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  76829. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  76830. var hit = ray.intersectsMesh(impostorObject);
  76831. var contactPoint = hit.pickedPoint;
  76832. if (!contactPoint) {
  76833. return null;
  76834. }
  76835. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  76836. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  76837. var directionToOrigin = contactPoint.normalize();
  76838. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76839. directionToOrigin = directionToOrigin.negate();
  76840. }
  76841. // TODO: find a more physically based solution
  76842. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76843. var forceX = directionToOrigin.x * this._strength / 8;
  76844. var forceY = directionToOrigin.y * this._updraftMultiplier;
  76845. var forceZ = directionToOrigin.z * this._strength / 8;
  76846. }
  76847. else {
  76848. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  76849. var forceY = this._originTop.y * this._updraftMultiplier;
  76850. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  76851. }
  76852. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  76853. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  76854. return { force: force, contactPoint: impostorObjectCenter };
  76855. };
  76856. PhysicsVortexEvent.prototype._tick = function () {
  76857. var _this = this;
  76858. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76859. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76860. if (!impostorForceAndContactPoint) {
  76861. return;
  76862. }
  76863. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76864. });
  76865. };
  76866. /*** Helpers ***/
  76867. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  76868. if (!this._cylinder) {
  76869. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  76870. height: this._height,
  76871. diameter: this._radius * 2,
  76872. }, this._scene);
  76873. this._cylinder.isVisible = false;
  76874. }
  76875. };
  76876. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  76877. var impostorObject = impostor.object;
  76878. this._prepareCylinder();
  76879. this._cylinder.position = this._cylinderPosition;
  76880. return this._cylinder.intersectsMesh(impostorObject, true);
  76881. };
  76882. return PhysicsVortexEvent;
  76883. }());
  76884. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  76885. /***** Enums *****/
  76886. /**
  76887. * The strenght of the force in correspondence to the distance of the affected object
  76888. */
  76889. var PhysicsRadialImpulseFalloff;
  76890. (function (PhysicsRadialImpulseFalloff) {
  76891. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  76892. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  76893. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  76894. /**
  76895. * The strenght of the force in correspondence to the distance of the affected object
  76896. */
  76897. var PhysicsUpdraftMode;
  76898. (function (PhysicsUpdraftMode) {
  76899. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  76900. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  76901. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  76902. })(BABYLON || (BABYLON = {}));
  76903. //# sourceMappingURL=babylon.physicsHelper.js.map
  76904. var BABYLON;
  76905. (function (BABYLON) {
  76906. var CannonJSPlugin = /** @class */ (function () {
  76907. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  76908. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  76909. if (iterations === void 0) { iterations = 10; }
  76910. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  76911. this.name = "CannonJSPlugin";
  76912. this._physicsMaterials = new Array();
  76913. this._fixedTimeStep = 1 / 60;
  76914. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  76915. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(17) : undefined);
  76916. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  76917. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  76918. this._tmpPosition = BABYLON.Vector3.Zero();
  76919. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  76920. this._tmpUnityRotation = new BABYLON.Quaternion();
  76921. if (!this.isSupported()) {
  76922. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  76923. return;
  76924. }
  76925. this._extendNamespace();
  76926. this.world = new this.BJSCANNON.World();
  76927. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  76928. this.world.solver.iterations = iterations;
  76929. }
  76930. CannonJSPlugin.prototype.setGravity = function (gravity) {
  76931. this.world.gravity.copy(gravity);
  76932. };
  76933. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  76934. this._fixedTimeStep = timeStep;
  76935. };
  76936. CannonJSPlugin.prototype.getTimeStep = function () {
  76937. return this._fixedTimeStep;
  76938. };
  76939. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  76940. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  76941. };
  76942. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76943. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76944. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76945. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  76946. };
  76947. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76948. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76949. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76950. impostor.physicsBody.applyForce(impulse, worldPoint);
  76951. };
  76952. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76953. //parent-child relationship. Does this impostor has a parent impostor?
  76954. if (impostor.parent) {
  76955. if (impostor.physicsBody) {
  76956. this.removePhysicsBody(impostor);
  76957. //TODO is that needed?
  76958. impostor.forceUpdate();
  76959. }
  76960. return;
  76961. }
  76962. //should a new body be created for this impostor?
  76963. if (impostor.isBodyInitRequired()) {
  76964. var shape = this._createShape(impostor);
  76965. //unregister events, if body is being changed
  76966. var oldBody = impostor.physicsBody;
  76967. if (oldBody) {
  76968. this.removePhysicsBody(impostor);
  76969. }
  76970. //create the body and material
  76971. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  76972. var bodyCreationObject = {
  76973. mass: impostor.getParam("mass"),
  76974. material: material
  76975. };
  76976. // A simple extend, in case native options were used.
  76977. var nativeOptions = impostor.getParam("nativeOptions");
  76978. for (var key in nativeOptions) {
  76979. if (nativeOptions.hasOwnProperty(key)) {
  76980. bodyCreationObject[key] = nativeOptions[key];
  76981. }
  76982. }
  76983. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  76984. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  76985. this.world.addEventListener("preStep", impostor.beforeStep);
  76986. this.world.addEventListener("postStep", impostor.afterStep);
  76987. impostor.physicsBody.addShape(shape);
  76988. this.world.add(impostor.physicsBody);
  76989. //try to keep the body moving in the right direction by taking old properties.
  76990. //Should be tested!
  76991. if (oldBody) {
  76992. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  76993. impostor.physicsBody[param].copy(oldBody[param]);
  76994. });
  76995. }
  76996. this._processChildMeshes(impostor);
  76997. }
  76998. //now update the body's transformation
  76999. this._updatePhysicsBodyTransformation(impostor);
  77000. };
  77001. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  77002. var _this = this;
  77003. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  77004. var currentRotation = mainImpostor.object.rotationQuaternion;
  77005. if (meshChildren.length) {
  77006. var processMesh = function (localPosition, mesh) {
  77007. if (!currentRotation || !mesh.rotationQuaternion) {
  77008. return;
  77009. }
  77010. var childImpostor = mesh.getPhysicsImpostor();
  77011. if (childImpostor) {
  77012. var parent = childImpostor.parent;
  77013. if (parent !== mainImpostor) {
  77014. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  77015. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  77016. if (childImpostor.physicsBody) {
  77017. _this.removePhysicsBody(childImpostor);
  77018. childImpostor.physicsBody = null;
  77019. }
  77020. childImpostor.parent = mainImpostor;
  77021. childImpostor.resetUpdateFlags();
  77022. 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));
  77023. //Add the mass of the children.
  77024. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  77025. }
  77026. }
  77027. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  77028. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  77029. };
  77030. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  77031. }
  77032. };
  77033. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77034. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  77035. this.world.removeEventListener("preStep", impostor.beforeStep);
  77036. this.world.removeEventListener("postStep", impostor.afterStep);
  77037. this.world.remove(impostor.physicsBody);
  77038. };
  77039. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77040. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77041. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77042. if (!mainBody || !connectedBody) {
  77043. return;
  77044. }
  77045. var constraint;
  77046. var jointData = impostorJoint.joint.jointData;
  77047. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  77048. var constraintData = {
  77049. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  77050. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  77051. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  77052. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  77053. maxForce: jointData.nativeParams.maxForce,
  77054. collideConnected: !!jointData.collision
  77055. };
  77056. switch (impostorJoint.joint.type) {
  77057. case BABYLON.PhysicsJoint.HingeJoint:
  77058. case BABYLON.PhysicsJoint.Hinge2Joint:
  77059. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  77060. break;
  77061. case BABYLON.PhysicsJoint.DistanceJoint:
  77062. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  77063. break;
  77064. case BABYLON.PhysicsJoint.SpringJoint:
  77065. var springData = jointData;
  77066. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  77067. restLength: springData.length,
  77068. stiffness: springData.stiffness,
  77069. damping: springData.damping,
  77070. localAnchorA: constraintData.pivotA,
  77071. localAnchorB: constraintData.pivotB
  77072. });
  77073. break;
  77074. case BABYLON.PhysicsJoint.LockJoint:
  77075. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  77076. break;
  77077. case BABYLON.PhysicsJoint.PointToPointJoint:
  77078. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77079. default:
  77080. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  77081. break;
  77082. }
  77083. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  77084. constraint.collideConnected = !!jointData.collision;
  77085. impostorJoint.joint.physicsJoint = constraint;
  77086. //don't add spring as constraint, as it is not one.
  77087. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  77088. this.world.addConstraint(constraint);
  77089. }
  77090. else {
  77091. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  77092. constraint.applyForce();
  77093. });
  77094. }
  77095. };
  77096. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77097. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  77098. };
  77099. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  77100. var index;
  77101. var mat;
  77102. for (index = 0; index < this._physicsMaterials.length; index++) {
  77103. mat = this._physicsMaterials[index];
  77104. if (mat.friction === friction && mat.restitution === restitution) {
  77105. return mat;
  77106. }
  77107. }
  77108. var currentMat = new this.BJSCANNON.Material(name);
  77109. currentMat.friction = friction;
  77110. currentMat.restitution = restitution;
  77111. this._physicsMaterials.push(currentMat);
  77112. return currentMat;
  77113. };
  77114. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  77115. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  77116. };
  77117. CannonJSPlugin.prototype._createShape = function (impostor) {
  77118. var object = impostor.object;
  77119. var returnValue;
  77120. var extendSize = impostor.getObjectExtendSize();
  77121. switch (impostor.type) {
  77122. case BABYLON.PhysicsImpostor.SphereImpostor:
  77123. var radiusX = extendSize.x;
  77124. var radiusY = extendSize.y;
  77125. var radiusZ = extendSize.z;
  77126. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  77127. break;
  77128. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  77129. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77130. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  77131. break;
  77132. case BABYLON.PhysicsImpostor.BoxImpostor:
  77133. var box = extendSize.scale(0.5);
  77134. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  77135. break;
  77136. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77137. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  77138. returnValue = new this.BJSCANNON.Plane();
  77139. break;
  77140. case BABYLON.PhysicsImpostor.MeshImpostor:
  77141. // should transform the vertex data to world coordinates!!
  77142. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  77143. var rawFaces = object.getIndices ? object.getIndices() : [];
  77144. if (!rawVerts)
  77145. return;
  77146. // get only scale! so the object could transform correctly.
  77147. var oldPosition = object.position.clone();
  77148. var oldRotation = object.rotation && object.rotation.clone();
  77149. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  77150. object.position.copyFromFloats(0, 0, 0);
  77151. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77152. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77153. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77154. var transform = object.computeWorldMatrix(true);
  77155. // convert rawVerts to object space
  77156. var temp = new Array();
  77157. var index;
  77158. for (index = 0; index < rawVerts.length; index += 3) {
  77159. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  77160. }
  77161. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  77162. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  77163. //now set back the transformation!
  77164. object.position.copyFrom(oldPosition);
  77165. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  77166. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  77167. break;
  77168. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  77169. var oldPosition2 = object.position.clone();
  77170. var oldRotation2 = object.rotation && object.rotation.clone();
  77171. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  77172. object.position.copyFromFloats(0, 0, 0);
  77173. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77174. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77175. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77176. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  77177. returnValue = this._createHeightmap(object);
  77178. object.position.copyFrom(oldPosition2);
  77179. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  77180. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  77181. object.computeWorldMatrix(true);
  77182. break;
  77183. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77184. returnValue = new this.BJSCANNON.Particle();
  77185. break;
  77186. }
  77187. return returnValue;
  77188. };
  77189. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  77190. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77191. var transform = object.computeWorldMatrix(true);
  77192. // convert rawVerts to object space
  77193. var temp = new Array();
  77194. var index;
  77195. for (index = 0; index < pos.length; index += 3) {
  77196. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  77197. }
  77198. pos = temp;
  77199. var matrix = new Array();
  77200. //For now pointDepth will not be used and will be automatically calculated.
  77201. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  77202. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  77203. var boundingInfo = object.getBoundingInfo();
  77204. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  77205. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  77206. var elementSize = dim * 2 / arraySize;
  77207. for (var i = 0; i < pos.length; i = i + 3) {
  77208. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  77209. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  77210. var y = -pos[i + 2] + minY;
  77211. if (!matrix[x]) {
  77212. matrix[x] = [];
  77213. }
  77214. if (!matrix[x][z]) {
  77215. matrix[x][z] = y;
  77216. }
  77217. matrix[x][z] = Math.max(y, matrix[x][z]);
  77218. }
  77219. for (var x = 0; x <= arraySize; ++x) {
  77220. if (!matrix[x]) {
  77221. var loc = 1;
  77222. while (!matrix[(x + loc) % arraySize]) {
  77223. loc++;
  77224. }
  77225. matrix[x] = matrix[(x + loc) % arraySize].slice();
  77226. //console.log("missing x", x);
  77227. }
  77228. for (var z = 0; z <= arraySize; ++z) {
  77229. if (!matrix[x][z]) {
  77230. var loc = 1;
  77231. var newValue;
  77232. while (newValue === undefined) {
  77233. newValue = matrix[x][(z + loc++) % arraySize];
  77234. }
  77235. matrix[x][z] = newValue;
  77236. }
  77237. }
  77238. }
  77239. var shape = new this.BJSCANNON.Heightfield(matrix, {
  77240. elementSize: elementSize
  77241. });
  77242. //For future reference, needed for body transformation
  77243. shape.minY = minY;
  77244. return shape;
  77245. };
  77246. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  77247. var object = impostor.object;
  77248. //make sure it is updated...
  77249. object.computeWorldMatrix && object.computeWorldMatrix(true);
  77250. // The delta between the mesh position and the mesh bounding box center
  77251. var bInfo = object.getBoundingInfo();
  77252. if (!bInfo)
  77253. return;
  77254. var center = impostor.getObjectCenter();
  77255. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  77256. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  77257. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  77258. this._tmpPosition.copyFrom(center);
  77259. var quaternion = object.rotationQuaternion;
  77260. if (!quaternion) {
  77261. return;
  77262. }
  77263. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  77264. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  77265. //-90 DEG in X, precalculated
  77266. quaternion = quaternion.multiply(this._minus90X);
  77267. //Invert! (Precalculated, 90 deg in X)
  77268. //No need to clone. this will never change.
  77269. impostor.setDeltaRotation(this._plus90X);
  77270. }
  77271. //If it is a heightfield, if should be centered.
  77272. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  77273. var mesh = object;
  77274. var boundingInfo = mesh.getBoundingInfo();
  77275. //calculate the correct body position:
  77276. var rotationQuaternion = mesh.rotationQuaternion;
  77277. mesh.rotationQuaternion = this._tmpUnityRotation;
  77278. mesh.computeWorldMatrix(true);
  77279. //get original center with no rotation
  77280. var c = center.clone();
  77281. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  77282. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  77283. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  77284. mesh.setPreTransformMatrix(p);
  77285. mesh.computeWorldMatrix(true);
  77286. //calculate the translation
  77287. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  77288. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  77289. //add it inverted to the delta
  77290. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  77291. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  77292. //rotation is back
  77293. mesh.rotationQuaternion = rotationQuaternion;
  77294. mesh.setPreTransformMatrix(oldPivot);
  77295. mesh.computeWorldMatrix(true);
  77296. }
  77297. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  77298. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  77299. //this._tmpPosition.copyFrom(object.position);
  77300. }
  77301. impostor.setDeltaPosition(this._tmpDeltaPosition);
  77302. //Now update the impostor object
  77303. impostor.physicsBody.position.copy(this._tmpPosition);
  77304. impostor.physicsBody.quaternion.copy(quaternion);
  77305. };
  77306. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77307. impostor.object.position.copyFrom(impostor.physicsBody.position);
  77308. if (impostor.object.rotationQuaternion) {
  77309. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  77310. }
  77311. };
  77312. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77313. impostor.physicsBody.position.copy(newPosition);
  77314. impostor.physicsBody.quaternion.copy(newRotation);
  77315. };
  77316. CannonJSPlugin.prototype.isSupported = function () {
  77317. return this.BJSCANNON !== undefined;
  77318. };
  77319. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77320. impostor.physicsBody.velocity.copy(velocity);
  77321. };
  77322. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77323. impostor.physicsBody.angularVelocity.copy(velocity);
  77324. };
  77325. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77326. var v = impostor.physicsBody.velocity;
  77327. if (!v) {
  77328. return null;
  77329. }
  77330. return new BABYLON.Vector3(v.x, v.y, v.z);
  77331. };
  77332. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77333. var v = impostor.physicsBody.angularVelocity;
  77334. if (!v) {
  77335. return null;
  77336. }
  77337. return new BABYLON.Vector3(v.x, v.y, v.z);
  77338. };
  77339. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77340. impostor.physicsBody.mass = mass;
  77341. impostor.physicsBody.updateMassProperties();
  77342. };
  77343. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77344. return impostor.physicsBody.mass;
  77345. };
  77346. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  77347. return impostor.physicsBody.material.friction;
  77348. };
  77349. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77350. impostor.physicsBody.material.friction = friction;
  77351. };
  77352. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77353. return impostor.physicsBody.material.restitution;
  77354. };
  77355. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77356. impostor.physicsBody.material.restitution = restitution;
  77357. };
  77358. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  77359. impostor.physicsBody.sleep();
  77360. };
  77361. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  77362. impostor.physicsBody.wakeUp();
  77363. };
  77364. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77365. joint.physicsJoint.distance = maxDistance;
  77366. };
  77367. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77368. // if (!motorIndex) {
  77369. // joint.physicsJoint.enableMotor();
  77370. // }
  77371. // }
  77372. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77373. // if (!motorIndex) {
  77374. // joint.physicsJoint.disableMotor();
  77375. // }
  77376. // }
  77377. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77378. if (!motorIndex) {
  77379. joint.physicsJoint.enableMotor();
  77380. joint.physicsJoint.setMotorSpeed(speed);
  77381. if (maxForce) {
  77382. this.setLimit(joint, maxForce);
  77383. }
  77384. }
  77385. };
  77386. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  77387. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  77388. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  77389. };
  77390. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77391. var body = impostor.physicsBody;
  77392. mesh.position.x = body.position.x;
  77393. mesh.position.y = body.position.y;
  77394. mesh.position.z = body.position.z;
  77395. if (mesh.rotationQuaternion) {
  77396. mesh.rotationQuaternion.x = body.quaternion.x;
  77397. mesh.rotationQuaternion.y = body.quaternion.y;
  77398. mesh.rotationQuaternion.z = body.quaternion.z;
  77399. mesh.rotationQuaternion.w = body.quaternion.w;
  77400. }
  77401. };
  77402. CannonJSPlugin.prototype.getRadius = function (impostor) {
  77403. var shape = impostor.physicsBody.shapes[0];
  77404. return shape.boundingSphereRadius;
  77405. };
  77406. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77407. var shape = impostor.physicsBody.shapes[0];
  77408. result.x = shape.halfExtents.x * 2;
  77409. result.y = shape.halfExtents.y * 2;
  77410. result.z = shape.halfExtents.z * 2;
  77411. };
  77412. CannonJSPlugin.prototype.dispose = function () {
  77413. };
  77414. CannonJSPlugin.prototype._extendNamespace = function () {
  77415. //this will force cannon to execute at least one step when using interpolation
  77416. var step_tmp1 = new this.BJSCANNON.Vec3();
  77417. var Engine = this.BJSCANNON;
  77418. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  77419. maxSubSteps = maxSubSteps || 10;
  77420. timeSinceLastCalled = timeSinceLastCalled || 0;
  77421. if (timeSinceLastCalled === 0) {
  77422. this.internalStep(dt);
  77423. this.time += dt;
  77424. }
  77425. else {
  77426. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  77427. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  77428. var t0 = performance.now();
  77429. for (var i = 0; i !== internalSteps; i++) {
  77430. this.internalStep(dt);
  77431. if (performance.now() - t0 > dt * 1000) {
  77432. break;
  77433. }
  77434. }
  77435. this.time += timeSinceLastCalled;
  77436. var h = this.time % dt;
  77437. var h_div_dt = h / dt;
  77438. var interpvelo = step_tmp1;
  77439. var bodies = this.bodies;
  77440. for (var j = 0; j !== bodies.length; j++) {
  77441. var b = bodies[j];
  77442. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  77443. b.position.vsub(b.previousPosition, interpvelo);
  77444. interpvelo.scale(h_div_dt, interpvelo);
  77445. b.position.vadd(interpvelo, b.interpolatedPosition);
  77446. }
  77447. else {
  77448. b.interpolatedPosition.copy(b.position);
  77449. b.interpolatedQuaternion.copy(b.quaternion);
  77450. }
  77451. }
  77452. }
  77453. };
  77454. };
  77455. return CannonJSPlugin;
  77456. }());
  77457. BABYLON.CannonJSPlugin = CannonJSPlugin;
  77458. })(BABYLON || (BABYLON = {}));
  77459. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  77460. var BABYLON;
  77461. (function (BABYLON) {
  77462. var OimoJSPlugin = /** @class */ (function () {
  77463. function OimoJSPlugin(iterations) {
  77464. this.name = "OimoJSPlugin";
  77465. this._tmpImpostorsArray = [];
  77466. this._tmpPositionVector = BABYLON.Vector3.Zero();
  77467. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(18) : undefined);
  77468. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  77469. this.world.worldscale(1);
  77470. this.world.clear();
  77471. //making sure no stats are calculated
  77472. this.world.isNoStat = true;
  77473. }
  77474. OimoJSPlugin.prototype.setGravity = function (gravity) {
  77475. this.world.gravity.copy(gravity);
  77476. };
  77477. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  77478. this.world.timeStep = timeStep;
  77479. };
  77480. OimoJSPlugin.prototype.getTimeStep = function () {
  77481. return this.world.timeStep;
  77482. };
  77483. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  77484. var _this = this;
  77485. impostors.forEach(function (impostor) {
  77486. impostor.beforeStep();
  77487. });
  77488. this.world.step();
  77489. impostors.forEach(function (impostor) {
  77490. impostor.afterStep();
  77491. //update the ordered impostors array
  77492. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  77493. });
  77494. //check for collisions
  77495. var contact = this.world.contacts;
  77496. while (contact !== null) {
  77497. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  77498. contact = contact.next;
  77499. continue;
  77500. }
  77501. //is this body colliding with any other? get the impostor
  77502. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  77503. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  77504. if (!mainImpostor || !collidingImpostor) {
  77505. contact = contact.next;
  77506. continue;
  77507. }
  77508. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  77509. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  77510. contact = contact.next;
  77511. }
  77512. };
  77513. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77514. var mass = impostor.physicsBody.massInfo.mass;
  77515. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  77516. };
  77517. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77518. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  77519. this.applyImpulse(impostor, force, contactPoint);
  77520. };
  77521. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77522. var _this = this;
  77523. //parent-child relationship. Does this impostor has a parent impostor?
  77524. if (impostor.parent) {
  77525. if (impostor.physicsBody) {
  77526. this.removePhysicsBody(impostor);
  77527. //TODO is that needed?
  77528. impostor.forceUpdate();
  77529. }
  77530. return;
  77531. }
  77532. if (impostor.isBodyInitRequired()) {
  77533. var bodyConfig = {
  77534. name: impostor.uniqueId,
  77535. //Oimo must have mass, also for static objects.
  77536. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  77537. size: [],
  77538. type: [],
  77539. pos: [],
  77540. rot: [],
  77541. move: impostor.getParam("mass") !== 0,
  77542. //Supporting older versions of Oimo
  77543. world: this.world
  77544. };
  77545. var impostors = [impostor];
  77546. var addToArray = function (parent) {
  77547. if (!parent.getChildMeshes)
  77548. return;
  77549. parent.getChildMeshes().forEach(function (m) {
  77550. if (m.physicsImpostor) {
  77551. impostors.push(m.physicsImpostor);
  77552. //m.physicsImpostor._init();
  77553. }
  77554. });
  77555. };
  77556. addToArray(impostor.object);
  77557. var checkWithEpsilon_1 = function (value) {
  77558. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  77559. };
  77560. impostors.forEach(function (i) {
  77561. if (!impostor.object.rotationQuaternion) {
  77562. return;
  77563. }
  77564. //get the correct bounding box
  77565. var oldQuaternion = i.object.rotationQuaternion;
  77566. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  77567. x: impostor.object.rotationQuaternion.x,
  77568. y: impostor.object.rotationQuaternion.y,
  77569. z: impostor.object.rotationQuaternion.z,
  77570. s: impostor.object.rotationQuaternion.w
  77571. });
  77572. var extendSize = i.getObjectExtendSize();
  77573. if (i === impostor) {
  77574. var center = impostor.getObjectCenter();
  77575. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  77576. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  77577. //Can also use Array.prototype.push.apply
  77578. bodyConfig.pos.push(center.x);
  77579. bodyConfig.pos.push(center.y);
  77580. bodyConfig.pos.push(center.z);
  77581. //tmp solution
  77582. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77583. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77584. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77585. }
  77586. else {
  77587. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  77588. bodyConfig.pos.push(localPosition.x);
  77589. bodyConfig.pos.push(localPosition.y);
  77590. bodyConfig.pos.push(localPosition.z);
  77591. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  77592. bodyConfig.rot.push(0);
  77593. bodyConfig.rot.push(0);
  77594. bodyConfig.rot.push(0);
  77595. }
  77596. // register mesh
  77597. switch (i.type) {
  77598. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77599. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  77600. case BABYLON.PhysicsImpostor.SphereImpostor:
  77601. var radiusX = extendSize.x;
  77602. var radiusY = extendSize.y;
  77603. var radiusZ = extendSize.z;
  77604. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  77605. bodyConfig.type.push('sphere');
  77606. //due to the way oimo works with compounds, add 3 times
  77607. bodyConfig.size.push(size);
  77608. bodyConfig.size.push(size);
  77609. bodyConfig.size.push(size);
  77610. break;
  77611. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77612. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  77613. var sizeY = checkWithEpsilon_1(extendSize.y);
  77614. bodyConfig.type.push('cylinder');
  77615. bodyConfig.size.push(sizeX);
  77616. bodyConfig.size.push(sizeY);
  77617. //due to the way oimo works with compounds, add one more value.
  77618. bodyConfig.size.push(sizeY);
  77619. break;
  77620. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77621. case BABYLON.PhysicsImpostor.BoxImpostor:
  77622. default:
  77623. var sizeX = checkWithEpsilon_1(extendSize.x);
  77624. var sizeY = checkWithEpsilon_1(extendSize.y);
  77625. var sizeZ = checkWithEpsilon_1(extendSize.z);
  77626. bodyConfig.type.push('box');
  77627. bodyConfig.size.push(sizeX);
  77628. bodyConfig.size.push(sizeY);
  77629. bodyConfig.size.push(sizeZ);
  77630. break;
  77631. }
  77632. //actually not needed, but hey...
  77633. i.object.rotationQuaternion = oldQuaternion;
  77634. });
  77635. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  77636. }
  77637. else {
  77638. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  77639. }
  77640. impostor.setDeltaPosition(this._tmpPositionVector);
  77641. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  77642. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  77643. };
  77644. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77645. //impostor.physicsBody.dispose();
  77646. //Same as : (older oimo versions)
  77647. this.world.removeRigidBody(impostor.physicsBody);
  77648. };
  77649. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77650. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77651. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77652. if (!mainBody || !connectedBody) {
  77653. return;
  77654. }
  77655. var jointData = impostorJoint.joint.jointData;
  77656. var options = jointData.nativeParams || {};
  77657. var type;
  77658. var nativeJointData = {
  77659. body1: mainBody,
  77660. body2: connectedBody,
  77661. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  77662. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  77663. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  77664. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  77665. min: options.min,
  77666. max: options.max,
  77667. collision: options.collision || jointData.collision,
  77668. spring: options.spring,
  77669. //supporting older version of Oimo
  77670. world: this.world
  77671. };
  77672. switch (impostorJoint.joint.type) {
  77673. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77674. type = "jointBall";
  77675. break;
  77676. case BABYLON.PhysicsJoint.SpringJoint:
  77677. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  77678. var springData = jointData;
  77679. nativeJointData.min = springData.length || nativeJointData.min;
  77680. //Max should also be set, just make sure it is at least min
  77681. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  77682. case BABYLON.PhysicsJoint.DistanceJoint:
  77683. type = "jointDistance";
  77684. nativeJointData.max = jointData.maxDistance;
  77685. break;
  77686. case BABYLON.PhysicsJoint.PrismaticJoint:
  77687. type = "jointPrisme";
  77688. break;
  77689. case BABYLON.PhysicsJoint.SliderJoint:
  77690. type = "jointSlide";
  77691. break;
  77692. case BABYLON.PhysicsJoint.WheelJoint:
  77693. type = "jointWheel";
  77694. break;
  77695. case BABYLON.PhysicsJoint.HingeJoint:
  77696. default:
  77697. type = "jointHinge";
  77698. break;
  77699. }
  77700. nativeJointData.type = type;
  77701. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  77702. };
  77703. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77704. //Bug in Oimo prevents us from disposing a joint in the playground
  77705. //joint.joint.physicsJoint.dispose();
  77706. //So we will bruteforce it!
  77707. try {
  77708. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  77709. }
  77710. catch (e) {
  77711. BABYLON.Tools.Warn(e);
  77712. }
  77713. };
  77714. OimoJSPlugin.prototype.isSupported = function () {
  77715. return this.BJSOIMO !== undefined;
  77716. };
  77717. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77718. if (!impostor.physicsBody.sleeping) {
  77719. //TODO check that
  77720. if (impostor.physicsBody.shapes.next) {
  77721. var parentShape = this._getLastShape(impostor.physicsBody);
  77722. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  77723. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  77724. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  77725. }
  77726. else {
  77727. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  77728. }
  77729. if (impostor.object.rotationQuaternion) {
  77730. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  77731. impostor.object.rotationQuaternion.normalize();
  77732. }
  77733. }
  77734. };
  77735. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77736. var body = impostor.physicsBody;
  77737. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  77738. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  77739. body.syncShapes();
  77740. body.awake();
  77741. };
  77742. OimoJSPlugin.prototype._getLastShape = function (body) {
  77743. var lastShape = body.shapes;
  77744. while (lastShape.next) {
  77745. lastShape = lastShape.next;
  77746. }
  77747. return lastShape;
  77748. };
  77749. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77750. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  77751. };
  77752. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77753. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  77754. };
  77755. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77756. var v = impostor.physicsBody.linearVelocity;
  77757. if (!v) {
  77758. return null;
  77759. }
  77760. return new BABYLON.Vector3(v.x, v.y, v.z);
  77761. };
  77762. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77763. var v = impostor.physicsBody.angularVelocity;
  77764. if (!v) {
  77765. return null;
  77766. }
  77767. return new BABYLON.Vector3(v.x, v.y, v.z);
  77768. };
  77769. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77770. var staticBody = mass === 0;
  77771. //this will actually set the body's density and not its mass.
  77772. //But this is how oimo treats the mass variable.
  77773. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  77774. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  77775. };
  77776. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  77777. return impostor.physicsBody.shapes.density;
  77778. };
  77779. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  77780. return impostor.physicsBody.shapes.friction;
  77781. };
  77782. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77783. impostor.physicsBody.shapes.friction = friction;
  77784. };
  77785. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77786. return impostor.physicsBody.shapes.restitution;
  77787. };
  77788. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77789. impostor.physicsBody.shapes.restitution = restitution;
  77790. };
  77791. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  77792. impostor.physicsBody.sleep();
  77793. };
  77794. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  77795. impostor.physicsBody.awake();
  77796. };
  77797. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77798. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  77799. if (minDistance !== void 0) {
  77800. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  77801. }
  77802. };
  77803. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77804. //TODO separate rotational and transational motors.
  77805. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77806. if (motor) {
  77807. motor.setMotor(speed, maxForce);
  77808. }
  77809. };
  77810. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  77811. //TODO separate rotational and transational motors.
  77812. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77813. if (motor) {
  77814. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  77815. }
  77816. };
  77817. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77818. var body = impostor.physicsBody;
  77819. mesh.position.x = body.position.x;
  77820. mesh.position.y = body.position.y;
  77821. mesh.position.z = body.position.z;
  77822. if (mesh.rotationQuaternion) {
  77823. mesh.rotationQuaternion.x = body.orientation.x;
  77824. mesh.rotationQuaternion.y = body.orientation.y;
  77825. mesh.rotationQuaternion.z = body.orientation.z;
  77826. mesh.rotationQuaternion.w = body.orientation.s;
  77827. }
  77828. };
  77829. OimoJSPlugin.prototype.getRadius = function (impostor) {
  77830. return impostor.physicsBody.shapes.radius;
  77831. };
  77832. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77833. var shape = impostor.physicsBody.shapes;
  77834. result.x = shape.halfWidth * 2;
  77835. result.y = shape.halfHeight * 2;
  77836. result.z = shape.halfDepth * 2;
  77837. };
  77838. OimoJSPlugin.prototype.dispose = function () {
  77839. this.world.clear();
  77840. };
  77841. return OimoJSPlugin;
  77842. }());
  77843. BABYLON.OimoJSPlugin = OimoJSPlugin;
  77844. })(BABYLON || (BABYLON = {}));
  77845. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  77846. var BABYLON;
  77847. (function (BABYLON) {
  77848. /*
  77849. * Based on jsTGALoader - Javascript loader for TGA file
  77850. * By Vincent Thibault
  77851. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  77852. */
  77853. var TGATools = /** @class */ (function () {
  77854. function TGATools() {
  77855. }
  77856. TGATools.GetTGAHeader = function (data) {
  77857. var offset = 0;
  77858. var header = {
  77859. id_length: data[offset++],
  77860. colormap_type: data[offset++],
  77861. image_type: data[offset++],
  77862. colormap_index: data[offset++] | data[offset++] << 8,
  77863. colormap_length: data[offset++] | data[offset++] << 8,
  77864. colormap_size: data[offset++],
  77865. origin: [
  77866. data[offset++] | data[offset++] << 8,
  77867. data[offset++] | data[offset++] << 8
  77868. ],
  77869. width: data[offset++] | data[offset++] << 8,
  77870. height: data[offset++] | data[offset++] << 8,
  77871. pixel_size: data[offset++],
  77872. flags: data[offset++]
  77873. };
  77874. return header;
  77875. };
  77876. TGATools.UploadContent = function (gl, data) {
  77877. // Not enough data to contain header ?
  77878. if (data.length < 19) {
  77879. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  77880. return;
  77881. }
  77882. // Read Header
  77883. var offset = 18;
  77884. var header = TGATools.GetTGAHeader(data);
  77885. // Assume it's a valid Targa file.
  77886. if (header.id_length + offset > data.length) {
  77887. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  77888. return;
  77889. }
  77890. // Skip not needed data
  77891. offset += header.id_length;
  77892. var use_rle = false;
  77893. var use_pal = false;
  77894. var use_grey = false;
  77895. // Get some informations.
  77896. switch (header.image_type) {
  77897. case TGATools._TYPE_RLE_INDEXED:
  77898. use_rle = true;
  77899. case TGATools._TYPE_INDEXED:
  77900. use_pal = true;
  77901. break;
  77902. case TGATools._TYPE_RLE_RGB:
  77903. use_rle = true;
  77904. case TGATools._TYPE_RGB:
  77905. // use_rgb = true;
  77906. break;
  77907. case TGATools._TYPE_RLE_GREY:
  77908. use_rle = true;
  77909. case TGATools._TYPE_GREY:
  77910. use_grey = true;
  77911. break;
  77912. }
  77913. var pixel_data;
  77914. // var numAlphaBits = header.flags & 0xf;
  77915. var pixel_size = header.pixel_size >> 3;
  77916. var pixel_total = header.width * header.height * pixel_size;
  77917. // Read palettes
  77918. var palettes;
  77919. if (use_pal) {
  77920. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  77921. }
  77922. // Read LRE
  77923. if (use_rle) {
  77924. pixel_data = new Uint8Array(pixel_total);
  77925. var c, count, i;
  77926. var localOffset = 0;
  77927. var pixels = new Uint8Array(pixel_size);
  77928. while (offset < pixel_total && localOffset < pixel_total) {
  77929. c = data[offset++];
  77930. count = (c & 0x7f) + 1;
  77931. // RLE pixels
  77932. if (c & 0x80) {
  77933. // Bind pixel tmp array
  77934. for (i = 0; i < pixel_size; ++i) {
  77935. pixels[i] = data[offset++];
  77936. }
  77937. // Copy pixel array
  77938. for (i = 0; i < count; ++i) {
  77939. pixel_data.set(pixels, localOffset + i * pixel_size);
  77940. }
  77941. localOffset += pixel_size * count;
  77942. }
  77943. else {
  77944. count *= pixel_size;
  77945. for (i = 0; i < count; ++i) {
  77946. pixel_data[localOffset + i] = data[offset++];
  77947. }
  77948. localOffset += count;
  77949. }
  77950. }
  77951. }
  77952. else {
  77953. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  77954. }
  77955. // Load to texture
  77956. var x_start, y_start, x_step, y_step, y_end, x_end;
  77957. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  77958. default:
  77959. case TGATools._ORIGIN_UL:
  77960. x_start = 0;
  77961. x_step = 1;
  77962. x_end = header.width;
  77963. y_start = 0;
  77964. y_step = 1;
  77965. y_end = header.height;
  77966. break;
  77967. case TGATools._ORIGIN_BL:
  77968. x_start = 0;
  77969. x_step = 1;
  77970. x_end = header.width;
  77971. y_start = header.height - 1;
  77972. y_step = -1;
  77973. y_end = -1;
  77974. break;
  77975. case TGATools._ORIGIN_UR:
  77976. x_start = header.width - 1;
  77977. x_step = -1;
  77978. x_end = -1;
  77979. y_start = 0;
  77980. y_step = 1;
  77981. y_end = header.height;
  77982. break;
  77983. case TGATools._ORIGIN_BR:
  77984. x_start = header.width - 1;
  77985. x_step = -1;
  77986. x_end = -1;
  77987. y_start = header.height - 1;
  77988. y_step = -1;
  77989. y_end = -1;
  77990. break;
  77991. }
  77992. // Load the specify method
  77993. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  77994. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  77995. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  77996. };
  77997. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77998. var image = pixel_data, colormap = palettes;
  77999. var width = header.width, height = header.height;
  78000. var color, i = 0, x, y;
  78001. var imageData = new Uint8Array(width * height * 4);
  78002. for (y = y_start; y !== y_end; y += y_step) {
  78003. for (x = x_start; x !== x_end; x += x_step, i++) {
  78004. color = image[i];
  78005. imageData[(x + width * y) * 4 + 3] = 255;
  78006. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  78007. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  78008. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  78009. }
  78010. }
  78011. return imageData;
  78012. };
  78013. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78014. var image = pixel_data;
  78015. var width = header.width, height = header.height;
  78016. var color, i = 0, x, y;
  78017. var imageData = new Uint8Array(width * height * 4);
  78018. for (y = y_start; y !== y_end; y += y_step) {
  78019. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78020. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  78021. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  78022. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  78023. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  78024. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  78025. }
  78026. }
  78027. return imageData;
  78028. };
  78029. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78030. var image = pixel_data;
  78031. var width = header.width, height = header.height;
  78032. var i = 0, x, y;
  78033. var imageData = new Uint8Array(width * height * 4);
  78034. for (y = y_start; y !== y_end; y += y_step) {
  78035. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  78036. imageData[(x + width * y) * 4 + 3] = 255;
  78037. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78038. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78039. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78040. }
  78041. }
  78042. return imageData;
  78043. };
  78044. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78045. var image = pixel_data;
  78046. var width = header.width, height = header.height;
  78047. var i = 0, x, y;
  78048. var imageData = new Uint8Array(width * height * 4);
  78049. for (y = y_start; y !== y_end; y += y_step) {
  78050. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  78051. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78052. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78053. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78054. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  78055. }
  78056. }
  78057. return imageData;
  78058. };
  78059. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78060. var image = pixel_data;
  78061. var width = header.width, height = header.height;
  78062. var color, i = 0, x, y;
  78063. var imageData = new Uint8Array(width * height * 4);
  78064. for (y = y_start; y !== y_end; y += y_step) {
  78065. for (x = x_start; x !== x_end; x += x_step, i++) {
  78066. color = image[i];
  78067. imageData[(x + width * y) * 4 + 0] = color;
  78068. imageData[(x + width * y) * 4 + 1] = color;
  78069. imageData[(x + width * y) * 4 + 2] = color;
  78070. imageData[(x + width * y) * 4 + 3] = 255;
  78071. }
  78072. }
  78073. return imageData;
  78074. };
  78075. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78076. var image = pixel_data;
  78077. var width = header.width, height = header.height;
  78078. var i = 0, x, y;
  78079. var imageData = new Uint8Array(width * height * 4);
  78080. for (y = y_start; y !== y_end; y += y_step) {
  78081. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78082. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  78083. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  78084. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78085. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  78086. }
  78087. }
  78088. return imageData;
  78089. };
  78090. //private static _TYPE_NO_DATA = 0;
  78091. TGATools._TYPE_INDEXED = 1;
  78092. TGATools._TYPE_RGB = 2;
  78093. TGATools._TYPE_GREY = 3;
  78094. TGATools._TYPE_RLE_INDEXED = 9;
  78095. TGATools._TYPE_RLE_RGB = 10;
  78096. TGATools._TYPE_RLE_GREY = 11;
  78097. TGATools._ORIGIN_MASK = 0x30;
  78098. TGATools._ORIGIN_SHIFT = 0x04;
  78099. TGATools._ORIGIN_BL = 0x00;
  78100. TGATools._ORIGIN_BR = 0x01;
  78101. TGATools._ORIGIN_UL = 0x02;
  78102. TGATools._ORIGIN_UR = 0x03;
  78103. return TGATools;
  78104. }());
  78105. BABYLON.TGATools = TGATools;
  78106. })(BABYLON || (BABYLON = {}));
  78107. //# sourceMappingURL=babylon.tga.js.map
  78108. var BABYLON;
  78109. (function (BABYLON) {
  78110. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  78111. // All values and structures referenced from:
  78112. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  78113. var DDS_MAGIC = 0x20534444;
  78114. var
  78115. //DDSD_CAPS = 0x1,
  78116. //DDSD_HEIGHT = 0x2,
  78117. //DDSD_WIDTH = 0x4,
  78118. //DDSD_PITCH = 0x8,
  78119. //DDSD_PIXELFORMAT = 0x1000,
  78120. DDSD_MIPMAPCOUNT = 0x20000;
  78121. //DDSD_LINEARSIZE = 0x80000,
  78122. //DDSD_DEPTH = 0x800000;
  78123. // var DDSCAPS_COMPLEX = 0x8,
  78124. // DDSCAPS_MIPMAP = 0x400000,
  78125. // DDSCAPS_TEXTURE = 0x1000;
  78126. var DDSCAPS2_CUBEMAP = 0x200;
  78127. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  78128. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  78129. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  78130. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  78131. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  78132. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  78133. // DDSCAPS2_VOLUME = 0x200000;
  78134. var
  78135. //DDPF_ALPHAPIXELS = 0x1,
  78136. //DDPF_ALPHA = 0x2,
  78137. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  78138. //DDPF_YUV = 0x200,
  78139. DDPF_LUMINANCE = 0x20000;
  78140. function FourCCToInt32(value) {
  78141. return value.charCodeAt(0) +
  78142. (value.charCodeAt(1) << 8) +
  78143. (value.charCodeAt(2) << 16) +
  78144. (value.charCodeAt(3) << 24);
  78145. }
  78146. function Int32ToFourCC(value) {
  78147. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  78148. }
  78149. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  78150. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  78151. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  78152. var FOURCC_DX10 = FourCCToInt32("DX10");
  78153. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  78154. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  78155. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  78156. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  78157. var headerLengthInt = 31; // The header length in 32 bit ints
  78158. // Offsets into the header array
  78159. var off_magic = 0;
  78160. var off_size = 1;
  78161. var off_flags = 2;
  78162. var off_height = 3;
  78163. var off_width = 4;
  78164. var off_mipmapCount = 7;
  78165. var off_pfFlags = 20;
  78166. var off_pfFourCC = 21;
  78167. var off_RGBbpp = 22;
  78168. var off_RMask = 23;
  78169. var off_GMask = 24;
  78170. var off_BMask = 25;
  78171. var off_AMask = 26;
  78172. // var off_caps1 = 27;
  78173. var off_caps2 = 28;
  78174. // var off_caps3 = 29;
  78175. // var off_caps4 = 30;
  78176. var off_dxgiFormat = 32;
  78177. ;
  78178. var DDSTools = /** @class */ (function () {
  78179. function DDSTools() {
  78180. }
  78181. DDSTools.GetDDSInfo = function (arrayBuffer) {
  78182. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78183. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  78184. var mipmapCount = 1;
  78185. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  78186. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78187. }
  78188. var fourCC = header[off_pfFourCC];
  78189. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  78190. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78191. switch (fourCC) {
  78192. case FOURCC_D3DFMT_R16G16B16A16F:
  78193. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78194. break;
  78195. case FOURCC_D3DFMT_R32G32B32A32F:
  78196. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78197. break;
  78198. case FOURCC_DX10:
  78199. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  78200. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78201. break;
  78202. }
  78203. }
  78204. return {
  78205. width: header[off_width],
  78206. height: header[off_height],
  78207. mipmapCount: mipmapCount,
  78208. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  78209. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  78210. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  78211. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  78212. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  78213. dxgiFormat: dxgiFormat,
  78214. textureType: textureType
  78215. };
  78216. };
  78217. DDSTools._ToHalfFloat = function (value) {
  78218. if (!DDSTools._FloatView) {
  78219. DDSTools._FloatView = new Float32Array(1);
  78220. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  78221. }
  78222. DDSTools._FloatView[0] = value;
  78223. var x = DDSTools._Int32View[0];
  78224. var bits = (x >> 16) & 0x8000; /* Get the sign */
  78225. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  78226. var e = (x >> 23) & 0xff; /* Using int is faster here */
  78227. /* If zero, or denormal, or exponent underflows too much for a denormal
  78228. * half, return signed zero. */
  78229. if (e < 103) {
  78230. return bits;
  78231. }
  78232. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  78233. if (e > 142) {
  78234. bits |= 0x7c00;
  78235. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  78236. * not Inf, so make sure we set one mantissa bit too. */
  78237. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  78238. return bits;
  78239. }
  78240. /* If exponent underflows but not too much, return a denormal */
  78241. if (e < 113) {
  78242. m |= 0x0800;
  78243. /* Extra rounding may overflow and set mantissa to 0 and exponent
  78244. * to 1, which is OK. */
  78245. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  78246. return bits;
  78247. }
  78248. bits |= ((e - 112) << 10) | (m >> 1);
  78249. bits += m & 1;
  78250. return bits;
  78251. };
  78252. DDSTools._FromHalfFloat = function (value) {
  78253. var s = (value & 0x8000) >> 15;
  78254. var e = (value & 0x7C00) >> 10;
  78255. var f = value & 0x03FF;
  78256. if (e === 0) {
  78257. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  78258. }
  78259. else if (e == 0x1F) {
  78260. return f ? NaN : ((s ? -1 : 1) * Infinity);
  78261. }
  78262. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  78263. };
  78264. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78265. var destArray = new Float32Array(dataLength);
  78266. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78267. var index = 0;
  78268. for (var y = 0; y < height; y++) {
  78269. for (var x = 0; x < width; x++) {
  78270. var srcPos = (x + y * width) * 4;
  78271. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  78272. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  78273. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  78274. if (DDSTools.StoreLODInAlphaChannel) {
  78275. destArray[index + 3] = lod;
  78276. }
  78277. else {
  78278. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  78279. }
  78280. index += 4;
  78281. }
  78282. }
  78283. return destArray;
  78284. };
  78285. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78286. if (DDSTools.StoreLODInAlphaChannel) {
  78287. var destArray = new Uint16Array(dataLength);
  78288. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78289. var index = 0;
  78290. for (var y = 0; y < height; y++) {
  78291. for (var x = 0; x < width; x++) {
  78292. var srcPos = (x + y * width) * 4;
  78293. destArray[index] = srcData[srcPos];
  78294. destArray[index + 1] = srcData[srcPos + 1];
  78295. destArray[index + 2] = srcData[srcPos + 2];
  78296. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  78297. index += 4;
  78298. }
  78299. }
  78300. return destArray;
  78301. }
  78302. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  78303. };
  78304. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78305. if (DDSTools.StoreLODInAlphaChannel) {
  78306. var destArray = new Float32Array(dataLength);
  78307. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78308. var index = 0;
  78309. for (var y = 0; y < height; y++) {
  78310. for (var x = 0; x < width; x++) {
  78311. var srcPos = (x + y * width) * 4;
  78312. destArray[index] = srcData[srcPos];
  78313. destArray[index + 1] = srcData[srcPos + 1];
  78314. destArray[index + 2] = srcData[srcPos + 2];
  78315. destArray[index + 3] = lod;
  78316. index += 4;
  78317. }
  78318. }
  78319. return destArray;
  78320. }
  78321. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78322. };
  78323. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78324. var destArray = new Uint8Array(dataLength);
  78325. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78326. var index = 0;
  78327. for (var y = 0; y < height; y++) {
  78328. for (var x = 0; x < width; x++) {
  78329. var srcPos = (x + y * width) * 4;
  78330. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78331. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78332. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78333. if (DDSTools.StoreLODInAlphaChannel) {
  78334. destArray[index + 3] = lod;
  78335. }
  78336. else {
  78337. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  78338. }
  78339. index += 4;
  78340. }
  78341. }
  78342. return destArray;
  78343. };
  78344. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78345. var destArray = new Uint8Array(dataLength);
  78346. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78347. var index = 0;
  78348. for (var y = 0; y < height; y++) {
  78349. for (var x = 0; x < width; x++) {
  78350. var srcPos = (x + y * width) * 4;
  78351. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  78352. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  78353. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  78354. if (DDSTools.StoreLODInAlphaChannel) {
  78355. destArray[index + 3] = lod;
  78356. }
  78357. else {
  78358. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  78359. }
  78360. index += 4;
  78361. }
  78362. }
  78363. return destArray;
  78364. };
  78365. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  78366. var byteArray = new Uint8Array(dataLength);
  78367. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78368. var index = 0;
  78369. for (var y = 0; y < height; y++) {
  78370. for (var x = 0; x < width; x++) {
  78371. var srcPos = (x + y * width) * 4;
  78372. byteArray[index] = srcData[srcPos + rOffset];
  78373. byteArray[index + 1] = srcData[srcPos + gOffset];
  78374. byteArray[index + 2] = srcData[srcPos + bOffset];
  78375. byteArray[index + 3] = srcData[srcPos + aOffset];
  78376. index += 4;
  78377. }
  78378. }
  78379. return byteArray;
  78380. };
  78381. DDSTools._ExtractLongWordOrder = function (value) {
  78382. if (value === 0 || value === 255 || value === -16777216) {
  78383. return 0;
  78384. }
  78385. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  78386. };
  78387. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  78388. var byteArray = new Uint8Array(dataLength);
  78389. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78390. var index = 0;
  78391. for (var y = 0; y < height; y++) {
  78392. for (var x = 0; x < width; x++) {
  78393. var srcPos = (x + y * width) * 3;
  78394. byteArray[index] = srcData[srcPos + rOffset];
  78395. byteArray[index + 1] = srcData[srcPos + gOffset];
  78396. byteArray[index + 2] = srcData[srcPos + bOffset];
  78397. index += 3;
  78398. }
  78399. }
  78400. return byteArray;
  78401. };
  78402. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  78403. var byteArray = new Uint8Array(dataLength);
  78404. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78405. var index = 0;
  78406. for (var y = 0; y < height; y++) {
  78407. for (var x = 0; x < width; x++) {
  78408. var srcPos = (x + y * width);
  78409. byteArray[index] = srcData[srcPos];
  78410. index++;
  78411. }
  78412. }
  78413. return byteArray;
  78414. };
  78415. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  78416. if (lodIndex === void 0) { lodIndex = -1; }
  78417. var ext = engine.getCaps().s3tc;
  78418. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78419. var fourCC, width, height, dataLength = 0, dataOffset;
  78420. var byteArray, mipmapCount, mip;
  78421. var internalFormat = 0;
  78422. var format = 0;
  78423. var blockBytes = 1;
  78424. if (header[off_magic] !== DDS_MAGIC) {
  78425. BABYLON.Tools.Error("Invalid magic number in DDS header");
  78426. return;
  78427. }
  78428. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  78429. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  78430. return;
  78431. }
  78432. if (info.isCompressed && !ext) {
  78433. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  78434. return;
  78435. }
  78436. var bpp = header[off_RGBbpp];
  78437. dataOffset = header[off_size] + 4;
  78438. var computeFormats = false;
  78439. if (info.isFourCC) {
  78440. fourCC = header[off_pfFourCC];
  78441. switch (fourCC) {
  78442. case FOURCC_DXT1:
  78443. blockBytes = 8;
  78444. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  78445. break;
  78446. case FOURCC_DXT3:
  78447. blockBytes = 16;
  78448. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  78449. break;
  78450. case FOURCC_DXT5:
  78451. blockBytes = 16;
  78452. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  78453. break;
  78454. case FOURCC_D3DFMT_R16G16B16A16F:
  78455. computeFormats = true;
  78456. break;
  78457. case FOURCC_D3DFMT_R32G32B32A32F:
  78458. computeFormats = true;
  78459. break;
  78460. case FOURCC_DX10:
  78461. // There is an additionnal header so dataOffset need to be changed
  78462. dataOffset += 5 * 4; // 5 uints
  78463. var supported = false;
  78464. switch (info.dxgiFormat) {
  78465. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  78466. computeFormats = true;
  78467. supported = true;
  78468. break;
  78469. case DXGI_FORMAT_B8G8R8X8_UNORM:
  78470. info.isRGB = true;
  78471. info.isFourCC = false;
  78472. bpp = 32;
  78473. supported = true;
  78474. break;
  78475. }
  78476. if (supported) {
  78477. break;
  78478. }
  78479. default:
  78480. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  78481. return;
  78482. }
  78483. }
  78484. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  78485. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  78486. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  78487. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  78488. if (computeFormats) {
  78489. format = engine._getWebGLTextureType(info.textureType);
  78490. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78491. }
  78492. mipmapCount = 1;
  78493. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  78494. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78495. }
  78496. for (var face = 0; face < faces; face++) {
  78497. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  78498. width = header[off_width];
  78499. height = header[off_height];
  78500. for (mip = 0; mip < mipmapCount; ++mip) {
  78501. if (lodIndex === -1 || lodIndex === mip) {
  78502. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  78503. var i = (lodIndex === -1) ? mip : 0;
  78504. if (!info.isCompressed && info.isFourCC) {
  78505. dataLength = width * height * 4;
  78506. var floatArray = null;
  78507. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  78508. if (bpp === 128) {
  78509. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78510. }
  78511. else if (bpp === 64) {
  78512. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78513. }
  78514. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78515. format = engine._getWebGLTextureType(info.textureType);
  78516. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78517. }
  78518. else {
  78519. if (bpp === 128) {
  78520. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78521. }
  78522. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  78523. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78524. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78525. format = engine._getWebGLTextureType(info.textureType);
  78526. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78527. }
  78528. else {
  78529. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78530. }
  78531. }
  78532. if (floatArray) {
  78533. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  78534. }
  78535. }
  78536. else if (info.isRGB) {
  78537. if (bpp === 24) {
  78538. dataLength = width * height * 3;
  78539. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  78540. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  78541. }
  78542. else {
  78543. dataLength = width * height * 4;
  78544. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  78545. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  78546. }
  78547. }
  78548. else if (info.isLuminance) {
  78549. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  78550. var unpaddedRowSize = width;
  78551. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  78552. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  78553. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  78554. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  78555. }
  78556. else {
  78557. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  78558. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  78559. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  78560. }
  78561. }
  78562. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  78563. width *= 0.5;
  78564. height *= 0.5;
  78565. width = Math.max(1.0, width);
  78566. height = Math.max(1.0, height);
  78567. }
  78568. if (currentFace !== undefined) {
  78569. // Loading a single face
  78570. break;
  78571. }
  78572. }
  78573. };
  78574. DDSTools.StoreLODInAlphaChannel = false;
  78575. return DDSTools;
  78576. }());
  78577. BABYLON.DDSTools = DDSTools;
  78578. })(BABYLON || (BABYLON = {}));
  78579. //# sourceMappingURL=babylon.dds.js.map
  78580. var BABYLON;
  78581. (function (BABYLON) {
  78582. /**
  78583. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  78584. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  78585. */
  78586. var KhronosTextureContainer = /** @class */ (function () {
  78587. /**
  78588. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  78589. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  78590. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  78591. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  78592. */
  78593. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  78594. this.arrayBuffer = arrayBuffer;
  78595. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  78596. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  78597. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  78598. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  78599. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  78600. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  78601. BABYLON.Tools.Error("texture missing KTX identifier");
  78602. return;
  78603. }
  78604. // load the reset of the header in native 32 bit int
  78605. var header = new Int32Array(this.arrayBuffer, 12, 13);
  78606. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  78607. var oppositeEndianess = header[0] === 0x01020304;
  78608. // read all the header elements in order they exist in the file, without modification (sans endainness)
  78609. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  78610. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  78611. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  78612. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  78613. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  78614. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  78615. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  78616. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  78617. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  78618. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  78619. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  78620. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  78621. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  78622. if (this.glType !== 0) {
  78623. BABYLON.Tools.Error("only compressed formats currently supported");
  78624. return;
  78625. }
  78626. else {
  78627. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  78628. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  78629. }
  78630. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  78631. BABYLON.Tools.Error("only 2D textures currently supported");
  78632. return;
  78633. }
  78634. if (this.numberOfArrayElements !== 0) {
  78635. BABYLON.Tools.Error("texture arrays not currently supported");
  78636. return;
  78637. }
  78638. if (this.numberOfFaces !== facesExpected) {
  78639. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  78640. return;
  78641. }
  78642. // we now have a completely validated file, so could use existence of loadType as success
  78643. // would need to make this more elaborate & adjust checks above to support more than one load type
  78644. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  78645. }
  78646. // not as fast hardware based, but will probably never need to use
  78647. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  78648. return ((val & 0xFF) << 24)
  78649. | ((val & 0xFF00) << 8)
  78650. | ((val >> 8) & 0xFF00)
  78651. | ((val >> 24) & 0xFF);
  78652. };
  78653. /**
  78654. * It is assumed that the texture has already been created & is currently bound
  78655. */
  78656. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  78657. switch (this.loadType) {
  78658. case KhronosTextureContainer.COMPRESSED_2D:
  78659. this._upload2DCompressedLevels(gl, loadMipmaps);
  78660. break;
  78661. case KhronosTextureContainer.TEX_2D:
  78662. case KhronosTextureContainer.COMPRESSED_3D:
  78663. case KhronosTextureContainer.TEX_3D:
  78664. }
  78665. };
  78666. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  78667. // initialize width & height for level 1
  78668. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  78669. var width = this.pixelWidth;
  78670. var height = this.pixelHeight;
  78671. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  78672. for (var level = 0; level < mipmapCount; level++) {
  78673. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  78674. for (var face = 0; face < this.numberOfFaces; face++) {
  78675. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  78676. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  78677. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  78678. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  78679. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  78680. }
  78681. width = Math.max(1.0, width * 0.5);
  78682. height = Math.max(1.0, height * 0.5);
  78683. }
  78684. };
  78685. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  78686. // load types
  78687. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  78688. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  78689. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  78690. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  78691. return KhronosTextureContainer;
  78692. }());
  78693. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  78694. })(BABYLON || (BABYLON = {}));
  78695. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  78696. var BABYLON;
  78697. (function (BABYLON) {
  78698. var Debug = /** @class */ (function () {
  78699. function Debug() {
  78700. }
  78701. Debug.AxesViewer = /** @class */ (function () {
  78702. function AxesViewer(scene, scaleLines) {
  78703. if (scaleLines === void 0) { scaleLines = 1; }
  78704. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78705. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78706. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78707. this.scaleLines = 1;
  78708. this.scaleLines = scaleLines;
  78709. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  78710. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  78711. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  78712. this._xmesh.renderingGroupId = 2;
  78713. this._ymesh.renderingGroupId = 2;
  78714. this._zmesh.renderingGroupId = 2;
  78715. this._xmesh.material.checkReadyOnlyOnce = true;
  78716. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  78717. this._ymesh.material.checkReadyOnlyOnce = true;
  78718. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  78719. this._zmesh.material.checkReadyOnlyOnce = true;
  78720. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  78721. this.scene = scene;
  78722. }
  78723. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  78724. var scaleLines = this.scaleLines;
  78725. if (this._xmesh) {
  78726. this._xmesh.position.copyFrom(position);
  78727. }
  78728. if (this._ymesh) {
  78729. this._ymesh.position.copyFrom(position);
  78730. }
  78731. if (this._zmesh) {
  78732. this._zmesh.position.copyFrom(position);
  78733. }
  78734. var point2 = this._xline[1];
  78735. point2.x = xaxis.x * scaleLines;
  78736. point2.y = xaxis.y * scaleLines;
  78737. point2.z = xaxis.z * scaleLines;
  78738. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  78739. point2 = this._yline[1];
  78740. point2.x = yaxis.x * scaleLines;
  78741. point2.y = yaxis.y * scaleLines;
  78742. point2.z = yaxis.z * scaleLines;
  78743. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  78744. point2 = this._zline[1];
  78745. point2.x = zaxis.x * scaleLines;
  78746. point2.y = zaxis.y * scaleLines;
  78747. point2.z = zaxis.z * scaleLines;
  78748. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  78749. };
  78750. AxesViewer.prototype.dispose = function () {
  78751. if (this._xmesh) {
  78752. this._xmesh.dispose();
  78753. }
  78754. if (this._ymesh) {
  78755. this._ymesh.dispose();
  78756. }
  78757. if (this._zmesh) {
  78758. this._zmesh.dispose();
  78759. }
  78760. this._xmesh = null;
  78761. this._ymesh = null;
  78762. this._zmesh = null;
  78763. this.scene = null;
  78764. };
  78765. return AxesViewer;
  78766. }());
  78767. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  78768. __extends(BoneAxesViewer, _super);
  78769. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  78770. if (scaleLines === void 0) { scaleLines = 1; }
  78771. var _this = _super.call(this, scene, scaleLines) || this;
  78772. _this.pos = BABYLON.Vector3.Zero();
  78773. _this.xaxis = BABYLON.Vector3.Zero();
  78774. _this.yaxis = BABYLON.Vector3.Zero();
  78775. _this.zaxis = BABYLON.Vector3.Zero();
  78776. _this.mesh = mesh;
  78777. _this.bone = bone;
  78778. return _this;
  78779. }
  78780. BoneAxesViewer.prototype.update = function () {
  78781. if (!this.mesh || !this.bone) {
  78782. return;
  78783. }
  78784. var bone = this.bone;
  78785. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  78786. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  78787. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  78788. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  78789. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  78790. };
  78791. BoneAxesViewer.prototype.dispose = function () {
  78792. if (this.mesh) {
  78793. this.mesh = null;
  78794. this.bone = null;
  78795. _super.prototype.dispose.call(this);
  78796. }
  78797. };
  78798. return BoneAxesViewer;
  78799. }(Debug.AxesViewer));
  78800. Debug.PhysicsViewer = /** @class */ (function () {
  78801. function PhysicsViewer(scene) {
  78802. this._impostors = [];
  78803. this._meshes = [];
  78804. this._numMeshes = 0;
  78805. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78806. var physicEngine = this._scene.getPhysicsEngine();
  78807. if (physicEngine) {
  78808. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  78809. }
  78810. }
  78811. PhysicsViewer.prototype._updateDebugMeshes = function () {
  78812. var plugin = this._physicsEnginePlugin;
  78813. for (var i = 0; i < this._numMeshes; i++) {
  78814. var impostor = this._impostors[i];
  78815. if (!impostor) {
  78816. continue;
  78817. }
  78818. if (impostor.isDisposed) {
  78819. this.hideImpostor(this._impostors[i--]);
  78820. }
  78821. else {
  78822. var mesh = this._meshes[i];
  78823. if (mesh && plugin) {
  78824. plugin.syncMeshWithImpostor(mesh, impostor);
  78825. }
  78826. }
  78827. }
  78828. };
  78829. PhysicsViewer.prototype.showImpostor = function (impostor) {
  78830. if (!this._scene) {
  78831. return;
  78832. }
  78833. for (var i = 0; i < this._numMeshes; i++) {
  78834. if (this._impostors[i] == impostor) {
  78835. return;
  78836. }
  78837. }
  78838. var debugMesh = this._getDebugMesh(impostor, this._scene);
  78839. if (debugMesh) {
  78840. this._impostors[this._numMeshes] = impostor;
  78841. this._meshes[this._numMeshes] = debugMesh;
  78842. if (this._numMeshes === 0) {
  78843. this._renderFunction = this._updateDebugMeshes.bind(this);
  78844. this._scene.registerBeforeRender(this._renderFunction);
  78845. }
  78846. this._numMeshes++;
  78847. }
  78848. };
  78849. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  78850. if (!impostor || !this._scene) {
  78851. return;
  78852. }
  78853. var removed = false;
  78854. for (var i = 0; i < this._numMeshes; i++) {
  78855. if (this._impostors[i] == impostor) {
  78856. var mesh = this._meshes[i];
  78857. if (!mesh) {
  78858. continue;
  78859. }
  78860. this._scene.removeMesh(mesh);
  78861. mesh.dispose();
  78862. this._numMeshes--;
  78863. if (this._numMeshes > 0) {
  78864. this._meshes[i] = this._meshes[this._numMeshes];
  78865. this._impostors[i] = this._impostors[this._numMeshes];
  78866. this._meshes[this._numMeshes] = null;
  78867. this._impostors[this._numMeshes] = null;
  78868. }
  78869. else {
  78870. this._meshes[0] = null;
  78871. this._impostors[0] = null;
  78872. }
  78873. removed = true;
  78874. break;
  78875. }
  78876. }
  78877. if (removed && this._numMeshes === 0) {
  78878. this._scene.unregisterBeforeRender(this._renderFunction);
  78879. }
  78880. };
  78881. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  78882. if (!this._debugMaterial) {
  78883. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  78884. this._debugMaterial.wireframe = true;
  78885. }
  78886. return this._debugMaterial;
  78887. };
  78888. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  78889. if (!this._debugBoxMesh) {
  78890. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  78891. this._debugBoxMesh.renderingGroupId = 1;
  78892. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78893. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  78894. scene.removeMesh(this._debugBoxMesh);
  78895. }
  78896. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  78897. };
  78898. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  78899. if (!this._debugSphereMesh) {
  78900. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  78901. this._debugSphereMesh.renderingGroupId = 1;
  78902. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78903. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  78904. scene.removeMesh(this._debugSphereMesh);
  78905. }
  78906. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  78907. };
  78908. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  78909. var mesh = null;
  78910. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  78911. mesh = this._getDebugBoxMesh(scene);
  78912. impostor.getBoxSizeToRef(mesh.scaling);
  78913. }
  78914. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  78915. mesh = this._getDebugSphereMesh(scene);
  78916. var radius = impostor.getRadius();
  78917. mesh.scaling.x = radius * 2;
  78918. mesh.scaling.y = radius * 2;
  78919. mesh.scaling.z = radius * 2;
  78920. }
  78921. return mesh;
  78922. };
  78923. PhysicsViewer.prototype.dispose = function () {
  78924. for (var i = 0; i < this._numMeshes; i++) {
  78925. this.hideImpostor(this._impostors[i]);
  78926. }
  78927. if (this._debugBoxMesh) {
  78928. this._debugBoxMesh.dispose();
  78929. }
  78930. if (this._debugSphereMesh) {
  78931. this._debugSphereMesh.dispose();
  78932. }
  78933. if (this._debugMaterial) {
  78934. this._debugMaterial.dispose();
  78935. }
  78936. this._impostors.length = 0;
  78937. this._scene = null;
  78938. this._physicsEnginePlugin = null;
  78939. };
  78940. return PhysicsViewer;
  78941. }());
  78942. Debug.SkeletonViewer = /** @class */ (function () {
  78943. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  78944. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  78945. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  78946. this.skeleton = skeleton;
  78947. this.mesh = mesh;
  78948. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  78949. this.renderingGroupId = renderingGroupId;
  78950. this.color = BABYLON.Color3.White();
  78951. this._debugLines = new Array();
  78952. this._isEnabled = false;
  78953. this._scene = scene;
  78954. this.update();
  78955. this._renderFunction = this.update.bind(this);
  78956. }
  78957. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  78958. get: function () {
  78959. return this._isEnabled;
  78960. },
  78961. set: function (value) {
  78962. if (this._isEnabled === value) {
  78963. return;
  78964. }
  78965. this._isEnabled = value;
  78966. if (value) {
  78967. this._scene.registerBeforeRender(this._renderFunction);
  78968. }
  78969. else {
  78970. this._scene.unregisterBeforeRender(this._renderFunction);
  78971. }
  78972. },
  78973. enumerable: true,
  78974. configurable: true
  78975. });
  78976. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  78977. if (x === void 0) { x = 0; }
  78978. if (y === void 0) { y = 0; }
  78979. if (z === void 0) { z = 0; }
  78980. var tmat = BABYLON.Tmp.Matrix[0];
  78981. var parentBone = bone.getParent();
  78982. tmat.copyFrom(bone.getLocalMatrix());
  78983. if (x !== 0 || y !== 0 || z !== 0) {
  78984. var tmat2 = BABYLON.Tmp.Matrix[1];
  78985. BABYLON.Matrix.IdentityToRef(tmat2);
  78986. tmat2.m[12] = x;
  78987. tmat2.m[13] = y;
  78988. tmat2.m[14] = z;
  78989. tmat2.multiplyToRef(tmat, tmat);
  78990. }
  78991. if (parentBone) {
  78992. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  78993. }
  78994. tmat.multiplyToRef(meshMat, tmat);
  78995. position.x = tmat.m[12];
  78996. position.y = tmat.m[13];
  78997. position.z = tmat.m[14];
  78998. };
  78999. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  79000. var len = bones.length;
  79001. var meshPos = this.mesh.position;
  79002. for (var i = 0; i < len; i++) {
  79003. var bone = bones[i];
  79004. var points = this._debugLines[i];
  79005. if (!points) {
  79006. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79007. this._debugLines[i] = points;
  79008. }
  79009. this._getBonePosition(points[0], bone, meshMat);
  79010. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  79011. points[0].subtractInPlace(meshPos);
  79012. points[1].subtractInPlace(meshPos);
  79013. }
  79014. };
  79015. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  79016. var len = bones.length;
  79017. var boneNum = 0;
  79018. var meshPos = this.mesh.position;
  79019. for (var i = len - 1; i >= 0; i--) {
  79020. var childBone = bones[i];
  79021. var parentBone = childBone.getParent();
  79022. if (!parentBone) {
  79023. continue;
  79024. }
  79025. var points = this._debugLines[boneNum];
  79026. if (!points) {
  79027. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79028. this._debugLines[boneNum] = points;
  79029. }
  79030. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  79031. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  79032. points[0].subtractInPlace(meshPos);
  79033. points[1].subtractInPlace(meshPos);
  79034. boneNum++;
  79035. }
  79036. };
  79037. SkeletonViewer.prototype.update = function () {
  79038. if (this.autoUpdateBonesMatrices) {
  79039. this.skeleton.computeAbsoluteTransforms();
  79040. }
  79041. if (this.skeleton.bones[0].length === undefined) {
  79042. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79043. }
  79044. else {
  79045. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79046. }
  79047. if (!this._debugMesh) {
  79048. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  79049. this._debugMesh.renderingGroupId = this.renderingGroupId;
  79050. }
  79051. else {
  79052. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  79053. }
  79054. this._debugMesh.position.copyFrom(this.mesh.position);
  79055. this._debugMesh.color = this.color;
  79056. };
  79057. SkeletonViewer.prototype.dispose = function () {
  79058. if (this._debugMesh) {
  79059. this.isEnabled = false;
  79060. this._debugMesh.dispose();
  79061. this._debugMesh = null;
  79062. }
  79063. };
  79064. return SkeletonViewer;
  79065. }());
  79066. return Debug;
  79067. }());
  79068. BABYLON.Debug = Debug;
  79069. })(BABYLON || (BABYLON = {}));
  79070. //# sourceMappingURL=babylon.debugModules.js.map
  79071. var BABYLON;
  79072. (function (BABYLON) {
  79073. var RayHelper = /** @class */ (function () {
  79074. function RayHelper(ray) {
  79075. this.ray = ray;
  79076. }
  79077. RayHelper.CreateAndShow = function (ray, scene, color) {
  79078. var helper = new RayHelper(ray);
  79079. helper.show(scene, color);
  79080. return helper;
  79081. };
  79082. RayHelper.prototype.show = function (scene, color) {
  79083. if (!this._renderFunction && this.ray) {
  79084. var ray = this.ray;
  79085. this._renderFunction = this._render.bind(this);
  79086. this._scene = scene;
  79087. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  79088. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  79089. if (this._renderFunction) {
  79090. this._scene.registerBeforeRender(this._renderFunction);
  79091. }
  79092. }
  79093. if (color && this._renderLine) {
  79094. this._renderLine.color.copyFrom(color);
  79095. }
  79096. };
  79097. RayHelper.prototype.hide = function () {
  79098. if (this._renderFunction && this._scene) {
  79099. this._scene.unregisterBeforeRender(this._renderFunction);
  79100. this._scene = null;
  79101. this._renderFunction = null;
  79102. if (this._renderLine) {
  79103. this._renderLine.dispose();
  79104. this._renderLine = null;
  79105. }
  79106. this._renderPoints = [];
  79107. }
  79108. };
  79109. RayHelper.prototype._render = function () {
  79110. var ray = this.ray;
  79111. if (!ray) {
  79112. return;
  79113. }
  79114. var point = this._renderPoints[1];
  79115. var len = Math.min(ray.length, 1000000);
  79116. point.copyFrom(ray.direction);
  79117. point.scaleInPlace(len);
  79118. point.addInPlace(ray.origin);
  79119. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  79120. };
  79121. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  79122. this._attachedToMesh = mesh;
  79123. var ray = this.ray;
  79124. if (!ray) {
  79125. return;
  79126. }
  79127. if (!ray.direction) {
  79128. ray.direction = BABYLON.Vector3.Zero();
  79129. }
  79130. if (!ray.origin) {
  79131. ray.origin = BABYLON.Vector3.Zero();
  79132. }
  79133. if (length) {
  79134. ray.length = length;
  79135. }
  79136. if (!meshSpaceOrigin) {
  79137. meshSpaceOrigin = BABYLON.Vector3.Zero();
  79138. }
  79139. if (!meshSpaceDirection) {
  79140. // -1 so that this will work with Mesh.lookAt
  79141. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  79142. }
  79143. if (!this._meshSpaceDirection) {
  79144. this._meshSpaceDirection = meshSpaceDirection.clone();
  79145. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  79146. }
  79147. else {
  79148. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  79149. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  79150. }
  79151. if (!this._updateToMeshFunction) {
  79152. this._updateToMeshFunction = this._updateToMesh.bind(this);
  79153. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  79154. }
  79155. this._updateToMesh();
  79156. };
  79157. RayHelper.prototype.detachFromMesh = function () {
  79158. if (this._attachedToMesh) {
  79159. if (this._updateToMeshFunction) {
  79160. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  79161. }
  79162. this._attachedToMesh = null;
  79163. this._updateToMeshFunction = null;
  79164. }
  79165. };
  79166. RayHelper.prototype._updateToMesh = function () {
  79167. var ray = this.ray;
  79168. if (!this._attachedToMesh || !ray) {
  79169. return;
  79170. }
  79171. if (this._attachedToMesh._isDisposed) {
  79172. this.detachFromMesh();
  79173. return;
  79174. }
  79175. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  79176. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  79177. };
  79178. RayHelper.prototype.dispose = function () {
  79179. this.hide();
  79180. this.detachFromMesh();
  79181. this.ray = null;
  79182. };
  79183. return RayHelper;
  79184. }());
  79185. BABYLON.RayHelper = RayHelper;
  79186. })(BABYLON || (BABYLON = {}));
  79187. //# sourceMappingURL=babylon.rayHelper.js.map
  79188. var BABYLON;
  79189. (function (BABYLON) {
  79190. // load the inspector using require, if not present in the global namespace.
  79191. var DebugLayer = /** @class */ (function () {
  79192. function DebugLayer(scene) {
  79193. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79194. this._scene = scene;
  79195. // load inspector using require, if it doesn't exist on the global namespace.
  79196. }
  79197. /** Creates the inspector window. */
  79198. DebugLayer.prototype._createInspector = function (config) {
  79199. if (config === void 0) { config = {}; }
  79200. var popup = config.popup || false;
  79201. var initialTab = config.initialTab || 0;
  79202. var parentElement = config.parentElement || null;
  79203. if (!this._inspector) {
  79204. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79205. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  79206. } // else nothing to do,; instance is already existing
  79207. };
  79208. DebugLayer.prototype.isVisible = function () {
  79209. if (!this._inspector) {
  79210. return false;
  79211. }
  79212. return true;
  79213. };
  79214. DebugLayer.prototype.hide = function () {
  79215. if (this._inspector) {
  79216. try {
  79217. this._inspector.dispose();
  79218. }
  79219. catch (e) {
  79220. // If the inspector has been removed directly from the inspector tool
  79221. }
  79222. this._inspector = null;
  79223. }
  79224. };
  79225. DebugLayer.prototype.show = function (config) {
  79226. if (config === void 0) { config = {}; }
  79227. if (typeof this.BJSINSPECTOR == 'undefined') {
  79228. // Load inspector and add it to the DOM
  79229. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  79230. }
  79231. else {
  79232. // Otherwise creates the inspector
  79233. this._createInspector(config);
  79234. }
  79235. };
  79236. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  79237. return DebugLayer;
  79238. }());
  79239. BABYLON.DebugLayer = DebugLayer;
  79240. })(BABYLON || (BABYLON = {}));
  79241. //# sourceMappingURL=babylon.debugLayer.js.map
  79242. var BABYLON;
  79243. (function (BABYLON) {
  79244. var BoundingBoxRenderer = /** @class */ (function () {
  79245. function BoundingBoxRenderer(scene) {
  79246. this.frontColor = new BABYLON.Color3(1, 1, 1);
  79247. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  79248. this.showBackLines = true;
  79249. this.renderList = new BABYLON.SmartArray(32);
  79250. this._vertexBuffers = {};
  79251. this._scene = scene;
  79252. }
  79253. BoundingBoxRenderer.prototype._prepareRessources = function () {
  79254. if (this._colorShader) {
  79255. return;
  79256. }
  79257. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  79258. attributes: [BABYLON.VertexBuffer.PositionKind],
  79259. uniforms: ["world", "viewProjection", "color"]
  79260. });
  79261. var engine = this._scene.getEngine();
  79262. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  79263. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  79264. this._createIndexBuffer();
  79265. };
  79266. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  79267. var engine = this._scene.getEngine();
  79268. 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]);
  79269. };
  79270. BoundingBoxRenderer.prototype._rebuild = function () {
  79271. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79272. if (vb) {
  79273. vb._rebuild();
  79274. }
  79275. this._createIndexBuffer();
  79276. };
  79277. BoundingBoxRenderer.prototype.reset = function () {
  79278. this.renderList.reset();
  79279. };
  79280. BoundingBoxRenderer.prototype.render = function () {
  79281. if (this.renderList.length === 0) {
  79282. return;
  79283. }
  79284. this._prepareRessources();
  79285. if (!this._colorShader.isReady()) {
  79286. return;
  79287. }
  79288. var engine = this._scene.getEngine();
  79289. engine.setDepthWrite(false);
  79290. this._colorShader._preBind();
  79291. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  79292. var boundingBox = this.renderList.data[boundingBoxIndex];
  79293. var min = boundingBox.minimum;
  79294. var max = boundingBox.maximum;
  79295. var diff = max.subtract(min);
  79296. var median = min.add(diff.scale(0.5));
  79297. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79298. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79299. .multiply(boundingBox.getWorldMatrix());
  79300. // VBOs
  79301. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79302. if (this.showBackLines) {
  79303. // Back
  79304. engine.setDepthFunctionToGreaterOrEqual();
  79305. this._scene.resetCachedMaterial();
  79306. this._colorShader.setColor4("color", this.backColor.toColor4());
  79307. this._colorShader.bind(worldMatrix);
  79308. // Draw order
  79309. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79310. }
  79311. // Front
  79312. engine.setDepthFunctionToLess();
  79313. this._scene.resetCachedMaterial();
  79314. this._colorShader.setColor4("color", this.frontColor.toColor4());
  79315. this._colorShader.bind(worldMatrix);
  79316. // Draw order
  79317. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79318. }
  79319. this._colorShader.unbind();
  79320. engine.setDepthFunctionToLessOrEqual();
  79321. engine.setDepthWrite(true);
  79322. };
  79323. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79324. this._prepareRessources();
  79325. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79326. return;
  79327. }
  79328. var engine = this._scene.getEngine();
  79329. engine.setDepthWrite(false);
  79330. engine.setColorWrite(false);
  79331. this._colorShader._preBind();
  79332. var boundingBox = mesh._boundingInfo.boundingBox;
  79333. var min = boundingBox.minimum;
  79334. var max = boundingBox.maximum;
  79335. var diff = max.subtract(min);
  79336. var median = min.add(diff.scale(0.5));
  79337. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79338. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79339. .multiply(boundingBox.getWorldMatrix());
  79340. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79341. engine.setDepthFunctionToLess();
  79342. this._scene.resetCachedMaterial();
  79343. this._colorShader.bind(worldMatrix);
  79344. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79345. this._colorShader.unbind();
  79346. engine.setDepthFunctionToLessOrEqual();
  79347. engine.setDepthWrite(true);
  79348. engine.setColorWrite(true);
  79349. };
  79350. BoundingBoxRenderer.prototype.dispose = function () {
  79351. if (!this._colorShader) {
  79352. return;
  79353. }
  79354. this.renderList.dispose();
  79355. this._colorShader.dispose();
  79356. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79357. if (buffer) {
  79358. buffer.dispose();
  79359. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79360. }
  79361. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79362. };
  79363. return BoundingBoxRenderer;
  79364. }());
  79365. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  79366. })(BABYLON || (BABYLON = {}));
  79367. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  79368. var BABYLON;
  79369. (function (BABYLON) {
  79370. var MorphTarget = /** @class */ (function () {
  79371. function MorphTarget(name, influence) {
  79372. if (influence === void 0) { influence = 0; }
  79373. this.name = name;
  79374. this.animations = new Array();
  79375. this._positions = null;
  79376. this._normals = null;
  79377. this._tangents = null;
  79378. this.onInfluenceChanged = new BABYLON.Observable();
  79379. this.influence = influence;
  79380. }
  79381. Object.defineProperty(MorphTarget.prototype, "influence", {
  79382. get: function () {
  79383. return this._influence;
  79384. },
  79385. set: function (influence) {
  79386. if (this._influence === influence) {
  79387. return;
  79388. }
  79389. var previous = this._influence;
  79390. this._influence = influence;
  79391. if (this.onInfluenceChanged.hasObservers) {
  79392. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  79393. }
  79394. },
  79395. enumerable: true,
  79396. configurable: true
  79397. });
  79398. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  79399. get: function () {
  79400. return !!this._positions;
  79401. },
  79402. enumerable: true,
  79403. configurable: true
  79404. });
  79405. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  79406. get: function () {
  79407. return !!this._normals;
  79408. },
  79409. enumerable: true,
  79410. configurable: true
  79411. });
  79412. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  79413. get: function () {
  79414. return !!this._tangents;
  79415. },
  79416. enumerable: true,
  79417. configurable: true
  79418. });
  79419. MorphTarget.prototype.setPositions = function (data) {
  79420. this._positions = data;
  79421. };
  79422. MorphTarget.prototype.getPositions = function () {
  79423. return this._positions;
  79424. };
  79425. MorphTarget.prototype.setNormals = function (data) {
  79426. this._normals = data;
  79427. };
  79428. MorphTarget.prototype.getNormals = function () {
  79429. return this._normals;
  79430. };
  79431. MorphTarget.prototype.setTangents = function (data) {
  79432. this._tangents = data;
  79433. };
  79434. MorphTarget.prototype.getTangents = function () {
  79435. return this._tangents;
  79436. };
  79437. /**
  79438. * Serializes the current target into a Serialization object.
  79439. * Returns the serialized object.
  79440. */
  79441. MorphTarget.prototype.serialize = function () {
  79442. var serializationObject = {};
  79443. serializationObject.name = this.name;
  79444. serializationObject.influence = this.influence;
  79445. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  79446. if (this.hasNormals) {
  79447. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  79448. }
  79449. if (this.hasTangents) {
  79450. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  79451. }
  79452. // Animations
  79453. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  79454. return serializationObject;
  79455. };
  79456. // Statics
  79457. MorphTarget.Parse = function (serializationObject) {
  79458. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  79459. result.setPositions(serializationObject.positions);
  79460. if (serializationObject.normals) {
  79461. result.setNormals(serializationObject.normals);
  79462. }
  79463. if (serializationObject.tangents) {
  79464. result.setTangents(serializationObject.tangents);
  79465. }
  79466. // Animations
  79467. if (serializationObject.animations) {
  79468. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  79469. var parsedAnimation = serializationObject.animations[animationIndex];
  79470. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  79471. }
  79472. }
  79473. return result;
  79474. };
  79475. MorphTarget.FromMesh = function (mesh, name, influence) {
  79476. if (!name) {
  79477. name = mesh.name;
  79478. }
  79479. var result = new MorphTarget(name, influence);
  79480. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79481. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79482. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  79483. }
  79484. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  79485. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  79486. }
  79487. return result;
  79488. };
  79489. return MorphTarget;
  79490. }());
  79491. BABYLON.MorphTarget = MorphTarget;
  79492. })(BABYLON || (BABYLON = {}));
  79493. //# sourceMappingURL=babylon.morphTarget.js.map
  79494. var BABYLON;
  79495. (function (BABYLON) {
  79496. var MorphTargetManager = /** @class */ (function () {
  79497. function MorphTargetManager(scene) {
  79498. if (scene === void 0) { scene = null; }
  79499. this._targets = new Array();
  79500. this._targetObservable = new Array();
  79501. this._activeTargets = new BABYLON.SmartArray(16);
  79502. this._supportsNormals = false;
  79503. this._supportsTangents = false;
  79504. this._vertexCount = 0;
  79505. this._uniqueId = 0;
  79506. this._tempInfluences = new Array();
  79507. if (!scene) {
  79508. scene = BABYLON.Engine.LastCreatedScene;
  79509. }
  79510. this._scene = scene;
  79511. if (this._scene) {
  79512. this._scene.morphTargetManagers.push(this);
  79513. this._uniqueId = this._scene.getUniqueId();
  79514. }
  79515. }
  79516. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  79517. get: function () {
  79518. return this._uniqueId;
  79519. },
  79520. enumerable: true,
  79521. configurable: true
  79522. });
  79523. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  79524. get: function () {
  79525. return this._vertexCount;
  79526. },
  79527. enumerable: true,
  79528. configurable: true
  79529. });
  79530. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  79531. get: function () {
  79532. return this._supportsNormals;
  79533. },
  79534. enumerable: true,
  79535. configurable: true
  79536. });
  79537. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  79538. get: function () {
  79539. return this._supportsTangents;
  79540. },
  79541. enumerable: true,
  79542. configurable: true
  79543. });
  79544. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  79545. get: function () {
  79546. return this._targets.length;
  79547. },
  79548. enumerable: true,
  79549. configurable: true
  79550. });
  79551. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  79552. get: function () {
  79553. return this._activeTargets.length;
  79554. },
  79555. enumerable: true,
  79556. configurable: true
  79557. });
  79558. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  79559. get: function () {
  79560. return this._influences;
  79561. },
  79562. enumerable: true,
  79563. configurable: true
  79564. });
  79565. MorphTargetManager.prototype.getActiveTarget = function (index) {
  79566. return this._activeTargets.data[index];
  79567. };
  79568. MorphTargetManager.prototype.getTarget = function (index) {
  79569. return this._targets[index];
  79570. };
  79571. MorphTargetManager.prototype.addTarget = function (target) {
  79572. var _this = this;
  79573. this._targets.push(target);
  79574. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  79575. _this._syncActiveTargets(needUpdate);
  79576. }));
  79577. this._syncActiveTargets(true);
  79578. };
  79579. MorphTargetManager.prototype.removeTarget = function (target) {
  79580. var index = this._targets.indexOf(target);
  79581. if (index >= 0) {
  79582. this._targets.splice(index, 1);
  79583. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  79584. this._syncActiveTargets(true);
  79585. }
  79586. };
  79587. /**
  79588. * Serializes the current manager into a Serialization object.
  79589. * Returns the serialized object.
  79590. */
  79591. MorphTargetManager.prototype.serialize = function () {
  79592. var serializationObject = {};
  79593. serializationObject.id = this.uniqueId;
  79594. serializationObject.targets = [];
  79595. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79596. var target = _a[_i];
  79597. serializationObject.targets.push(target.serialize());
  79598. }
  79599. return serializationObject;
  79600. };
  79601. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  79602. var influenceCount = 0;
  79603. this._activeTargets.reset();
  79604. this._supportsNormals = true;
  79605. this._supportsTangents = true;
  79606. this._vertexCount = 0;
  79607. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79608. var target = _a[_i];
  79609. this._activeTargets.push(target);
  79610. this._tempInfluences[influenceCount++] = target.influence;
  79611. var positions = target.getPositions();
  79612. if (positions) {
  79613. this._supportsNormals = this._supportsNormals && target.hasNormals;
  79614. this._supportsTangents = this._supportsTangents && target.hasTangents;
  79615. var vertexCount = positions.length / 3;
  79616. if (this._vertexCount === 0) {
  79617. this._vertexCount = vertexCount;
  79618. }
  79619. else if (this._vertexCount !== vertexCount) {
  79620. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  79621. return;
  79622. }
  79623. }
  79624. }
  79625. if (!this._influences || this._influences.length !== influenceCount) {
  79626. this._influences = new Float32Array(influenceCount);
  79627. }
  79628. for (var index = 0; index < influenceCount; index++) {
  79629. this._influences[index] = this._tempInfluences[index];
  79630. }
  79631. if (needUpdate && this._scene) {
  79632. // Flag meshes as dirty to resync with the active targets
  79633. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  79634. var mesh = _c[_b];
  79635. if (mesh.morphTargetManager === this) {
  79636. mesh._syncGeometryWithMorphTargetManager();
  79637. }
  79638. }
  79639. }
  79640. };
  79641. // Statics
  79642. MorphTargetManager.Parse = function (serializationObject, scene) {
  79643. var result = new MorphTargetManager(scene);
  79644. result._uniqueId = serializationObject.id;
  79645. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  79646. var targetData = _a[_i];
  79647. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  79648. }
  79649. return result;
  79650. };
  79651. return MorphTargetManager;
  79652. }());
  79653. BABYLON.MorphTargetManager = MorphTargetManager;
  79654. })(BABYLON || (BABYLON = {}));
  79655. //# sourceMappingURL=babylon.morphTargetManager.js.map
  79656. var BABYLON;
  79657. (function (BABYLON) {
  79658. var Octree = /** @class */ (function () {
  79659. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  79660. if (maxDepth === void 0) { maxDepth = 2; }
  79661. this.maxDepth = maxDepth;
  79662. this.dynamicContent = new Array();
  79663. this._maxBlockCapacity = maxBlockCapacity || 64;
  79664. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  79665. this._creationFunc = creationFunc;
  79666. }
  79667. // Methods
  79668. Octree.prototype.update = function (worldMin, worldMax, entries) {
  79669. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  79670. };
  79671. Octree.prototype.addMesh = function (entry) {
  79672. for (var index = 0; index < this.blocks.length; index++) {
  79673. var block = this.blocks[index];
  79674. block.addEntry(entry);
  79675. }
  79676. };
  79677. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  79678. this._selectionContent.reset();
  79679. for (var index = 0; index < this.blocks.length; index++) {
  79680. var block = this.blocks[index];
  79681. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  79682. }
  79683. if (allowDuplicate) {
  79684. this._selectionContent.concat(this.dynamicContent);
  79685. }
  79686. else {
  79687. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79688. }
  79689. return this._selectionContent;
  79690. };
  79691. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  79692. this._selectionContent.reset();
  79693. for (var index = 0; index < this.blocks.length; index++) {
  79694. var block = this.blocks[index];
  79695. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  79696. }
  79697. if (allowDuplicate) {
  79698. this._selectionContent.concat(this.dynamicContent);
  79699. }
  79700. else {
  79701. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79702. }
  79703. return this._selectionContent;
  79704. };
  79705. Octree.prototype.intersectsRay = function (ray) {
  79706. this._selectionContent.reset();
  79707. for (var index = 0; index < this.blocks.length; index++) {
  79708. var block = this.blocks[index];
  79709. block.intersectsRay(ray, this._selectionContent);
  79710. }
  79711. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79712. return this._selectionContent;
  79713. };
  79714. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  79715. target.blocks = new Array();
  79716. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  79717. // Segmenting space
  79718. for (var x = 0; x < 2; x++) {
  79719. for (var y = 0; y < 2; y++) {
  79720. for (var z = 0; z < 2; z++) {
  79721. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  79722. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  79723. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  79724. block.addEntries(entries);
  79725. target.blocks.push(block);
  79726. }
  79727. }
  79728. }
  79729. };
  79730. Octree.CreationFuncForMeshes = function (entry, block) {
  79731. var boundingInfo = entry.getBoundingInfo();
  79732. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79733. block.entries.push(entry);
  79734. }
  79735. };
  79736. Octree.CreationFuncForSubMeshes = function (entry, block) {
  79737. var boundingInfo = entry.getBoundingInfo();
  79738. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79739. block.entries.push(entry);
  79740. }
  79741. };
  79742. return Octree;
  79743. }());
  79744. BABYLON.Octree = Octree;
  79745. })(BABYLON || (BABYLON = {}));
  79746. //# sourceMappingURL=babylon.octree.js.map
  79747. var BABYLON;
  79748. (function (BABYLON) {
  79749. var OctreeBlock = /** @class */ (function () {
  79750. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  79751. this.entries = new Array();
  79752. this._boundingVectors = new Array();
  79753. this._capacity = capacity;
  79754. this._depth = depth;
  79755. this._maxDepth = maxDepth;
  79756. this._creationFunc = creationFunc;
  79757. this._minPoint = minPoint;
  79758. this._maxPoint = maxPoint;
  79759. this._boundingVectors.push(minPoint.clone());
  79760. this._boundingVectors.push(maxPoint.clone());
  79761. this._boundingVectors.push(minPoint.clone());
  79762. this._boundingVectors[2].x = maxPoint.x;
  79763. this._boundingVectors.push(minPoint.clone());
  79764. this._boundingVectors[3].y = maxPoint.y;
  79765. this._boundingVectors.push(minPoint.clone());
  79766. this._boundingVectors[4].z = maxPoint.z;
  79767. this._boundingVectors.push(maxPoint.clone());
  79768. this._boundingVectors[5].z = minPoint.z;
  79769. this._boundingVectors.push(maxPoint.clone());
  79770. this._boundingVectors[6].x = minPoint.x;
  79771. this._boundingVectors.push(maxPoint.clone());
  79772. this._boundingVectors[7].y = minPoint.y;
  79773. }
  79774. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  79775. // Property
  79776. get: function () {
  79777. return this._capacity;
  79778. },
  79779. enumerable: true,
  79780. configurable: true
  79781. });
  79782. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  79783. get: function () {
  79784. return this._minPoint;
  79785. },
  79786. enumerable: true,
  79787. configurable: true
  79788. });
  79789. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  79790. get: function () {
  79791. return this._maxPoint;
  79792. },
  79793. enumerable: true,
  79794. configurable: true
  79795. });
  79796. // Methods
  79797. OctreeBlock.prototype.addEntry = function (entry) {
  79798. if (this.blocks) {
  79799. for (var index = 0; index < this.blocks.length; index++) {
  79800. var block = this.blocks[index];
  79801. block.addEntry(entry);
  79802. }
  79803. return;
  79804. }
  79805. this._creationFunc(entry, this);
  79806. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  79807. this.createInnerBlocks();
  79808. }
  79809. };
  79810. OctreeBlock.prototype.addEntries = function (entries) {
  79811. for (var index = 0; index < entries.length; index++) {
  79812. var mesh = entries[index];
  79813. this.addEntry(mesh);
  79814. }
  79815. };
  79816. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  79817. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  79818. if (this.blocks) {
  79819. for (var index = 0; index < this.blocks.length; index++) {
  79820. var block = this.blocks[index];
  79821. block.select(frustumPlanes, selection, allowDuplicate);
  79822. }
  79823. return;
  79824. }
  79825. if (allowDuplicate) {
  79826. selection.concat(this.entries);
  79827. }
  79828. else {
  79829. selection.concatWithNoDuplicate(this.entries);
  79830. }
  79831. }
  79832. };
  79833. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  79834. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  79835. if (this.blocks) {
  79836. for (var index = 0; index < this.blocks.length; index++) {
  79837. var block = this.blocks[index];
  79838. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  79839. }
  79840. return;
  79841. }
  79842. if (allowDuplicate) {
  79843. selection.concat(this.entries);
  79844. }
  79845. else {
  79846. selection.concatWithNoDuplicate(this.entries);
  79847. }
  79848. }
  79849. };
  79850. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  79851. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  79852. if (this.blocks) {
  79853. for (var index = 0; index < this.blocks.length; index++) {
  79854. var block = this.blocks[index];
  79855. block.intersectsRay(ray, selection);
  79856. }
  79857. return;
  79858. }
  79859. selection.concatWithNoDuplicate(this.entries);
  79860. }
  79861. };
  79862. OctreeBlock.prototype.createInnerBlocks = function () {
  79863. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  79864. };
  79865. return OctreeBlock;
  79866. }());
  79867. BABYLON.OctreeBlock = OctreeBlock;
  79868. })(BABYLON || (BABYLON = {}));
  79869. //# sourceMappingURL=babylon.octreeBlock.js.map
  79870. var BABYLON;
  79871. (function (BABYLON) {
  79872. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  79873. __extends(VRDistortionCorrectionPostProcess, _super);
  79874. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  79875. var _this = _super.call(this, name, "vrDistortionCorrection", [
  79876. 'LensCenter',
  79877. 'Scale',
  79878. 'ScaleIn',
  79879. 'HmdWarpParam'
  79880. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  79881. _this._isRightEye = isRightEye;
  79882. _this._distortionFactors = vrMetrics.distortionK;
  79883. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  79884. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  79885. _this.adaptScaleToCurrentViewport = true;
  79886. _this.onSizeChangedObservable.add(function () {
  79887. _this.aspectRatio = _this.width * .5 / _this.height;
  79888. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  79889. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  79890. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  79891. });
  79892. _this.onApplyObservable.add(function (effect) {
  79893. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  79894. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  79895. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  79896. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  79897. });
  79898. return _this;
  79899. }
  79900. return VRDistortionCorrectionPostProcess;
  79901. }(BABYLON.PostProcess));
  79902. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  79903. })(BABYLON || (BABYLON = {}));
  79904. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  79905. var BABYLON;
  79906. (function (BABYLON) {
  79907. var AnaglyphPostProcess = /** @class */ (function (_super) {
  79908. __extends(AnaglyphPostProcess, _super);
  79909. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  79910. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  79911. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79912. _this.onApplyObservable.add(function (effect) {
  79913. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  79914. });
  79915. return _this;
  79916. }
  79917. return AnaglyphPostProcess;
  79918. }(BABYLON.PostProcess));
  79919. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  79920. })(BABYLON || (BABYLON = {}));
  79921. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  79922. var BABYLON;
  79923. (function (BABYLON) {
  79924. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  79925. __extends(StereoscopicInterlacePostProcess, _super);
  79926. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  79927. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  79928. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79929. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79930. _this.onSizeChangedObservable.add(function () {
  79931. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79932. });
  79933. _this.onApplyObservable.add(function (effect) {
  79934. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  79935. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  79936. });
  79937. return _this;
  79938. }
  79939. return StereoscopicInterlacePostProcess;
  79940. }(BABYLON.PostProcess));
  79941. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  79942. })(BABYLON || (BABYLON = {}));
  79943. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  79944. var BABYLON;
  79945. (function (BABYLON) {
  79946. /**
  79947. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  79948. * Screen rotation is taken into account.
  79949. */
  79950. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  79951. function FreeCameraDeviceOrientationInput() {
  79952. var _this = this;
  79953. this._screenOrientationAngle = 0;
  79954. this._screenQuaternion = new BABYLON.Quaternion();
  79955. this._alpha = 0;
  79956. this._beta = 0;
  79957. this._gamma = 0;
  79958. this._orientationChanged = function () {
  79959. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  79960. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  79961. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  79962. };
  79963. this._deviceOrientation = function (evt) {
  79964. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  79965. _this._beta = evt.beta !== null ? evt.beta : 0;
  79966. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  79967. };
  79968. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  79969. this._orientationChanged();
  79970. }
  79971. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  79972. get: function () {
  79973. return this._camera;
  79974. },
  79975. set: function (camera) {
  79976. this._camera = camera;
  79977. if (this._camera != null && !this._camera.rotationQuaternion) {
  79978. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  79979. }
  79980. },
  79981. enumerable: true,
  79982. configurable: true
  79983. });
  79984. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79985. window.addEventListener("orientationchange", this._orientationChanged);
  79986. window.addEventListener("deviceorientation", this._deviceOrientation);
  79987. //In certain cases, the attach control is called AFTER orientation was changed,
  79988. //So this is needed.
  79989. this._orientationChanged();
  79990. };
  79991. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  79992. window.removeEventListener("orientationchange", this._orientationChanged);
  79993. window.removeEventListener("deviceorientation", this._deviceOrientation);
  79994. };
  79995. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  79996. //if no device orientation provided, don't update the rotation.
  79997. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  79998. if (!this._alpha)
  79999. return;
  80000. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  80001. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  80002. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  80003. //Mirror on XY Plane
  80004. this._camera.rotationQuaternion.z *= -1;
  80005. this._camera.rotationQuaternion.w *= -1;
  80006. };
  80007. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  80008. return "FreeCameraDeviceOrientationInput";
  80009. };
  80010. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  80011. return "deviceOrientation";
  80012. };
  80013. return FreeCameraDeviceOrientationInput;
  80014. }());
  80015. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  80016. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  80017. })(BABYLON || (BABYLON = {}));
  80018. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  80019. var BABYLON;
  80020. (function (BABYLON) {
  80021. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  80022. function ArcRotateCameraVRDeviceOrientationInput() {
  80023. this.alphaCorrection = 1;
  80024. this.betaCorrection = 1;
  80025. this.gammaCorrection = 1;
  80026. this._alpha = 0;
  80027. this._gamma = 0;
  80028. this._dirty = false;
  80029. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  80030. }
  80031. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80032. this.camera.attachControl(element, noPreventDefault);
  80033. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  80034. };
  80035. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  80036. if (evt.alpha !== null) {
  80037. this._alpha = +evt.alpha | 0;
  80038. }
  80039. if (evt.gamma !== null) {
  80040. this._gamma = +evt.gamma | 0;
  80041. }
  80042. this._dirty = true;
  80043. };
  80044. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  80045. if (this._dirty) {
  80046. this._dirty = false;
  80047. if (this._gamma < 0) {
  80048. this._gamma = 180 + this._gamma;
  80049. }
  80050. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  80051. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  80052. }
  80053. };
  80054. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  80055. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  80056. };
  80057. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  80058. return "ArcRotateCameraVRDeviceOrientationInput";
  80059. };
  80060. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  80061. return "VRDeviceOrientation";
  80062. };
  80063. return ArcRotateCameraVRDeviceOrientationInput;
  80064. }());
  80065. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  80066. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  80067. })(BABYLON || (BABYLON = {}));
  80068. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  80069. var BABYLON;
  80070. (function (BABYLON) {
  80071. var VRCameraMetrics = /** @class */ (function () {
  80072. function VRCameraMetrics() {
  80073. this.compensateDistortion = true;
  80074. }
  80075. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  80076. get: function () {
  80077. return this.hResolution / (2 * this.vResolution);
  80078. },
  80079. enumerable: true,
  80080. configurable: true
  80081. });
  80082. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  80083. get: function () {
  80084. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  80085. },
  80086. enumerable: true,
  80087. configurable: true
  80088. });
  80089. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  80090. get: function () {
  80091. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80092. var h = (4 * meters) / this.hScreenSize;
  80093. return BABYLON.Matrix.Translation(h, 0, 0);
  80094. },
  80095. enumerable: true,
  80096. configurable: true
  80097. });
  80098. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  80099. get: function () {
  80100. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80101. var h = (4 * meters) / this.hScreenSize;
  80102. return BABYLON.Matrix.Translation(-h, 0, 0);
  80103. },
  80104. enumerable: true,
  80105. configurable: true
  80106. });
  80107. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  80108. get: function () {
  80109. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  80110. },
  80111. enumerable: true,
  80112. configurable: true
  80113. });
  80114. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  80115. get: function () {
  80116. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  80117. },
  80118. enumerable: true,
  80119. configurable: true
  80120. });
  80121. VRCameraMetrics.GetDefault = function () {
  80122. var result = new VRCameraMetrics();
  80123. result.hResolution = 1280;
  80124. result.vResolution = 800;
  80125. result.hScreenSize = 0.149759993;
  80126. result.vScreenSize = 0.0935999975;
  80127. result.vScreenCenter = 0.0467999987;
  80128. result.eyeToScreenDistance = 0.0410000011;
  80129. result.lensSeparationDistance = 0.0635000020;
  80130. result.interpupillaryDistance = 0.0640000030;
  80131. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  80132. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  80133. result.postProcessScaleFactor = 1.714605507808412;
  80134. result.lensCenterOffset = 0.151976421;
  80135. return result;
  80136. };
  80137. return VRCameraMetrics;
  80138. }());
  80139. BABYLON.VRCameraMetrics = VRCameraMetrics;
  80140. })(BABYLON || (BABYLON = {}));
  80141. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  80142. var BABYLON;
  80143. (function (BABYLON) {
  80144. /**
  80145. * This represents a WebVR camera.
  80146. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  80147. * @example http://doc.babylonjs.com/how_to/webvr_camera
  80148. */
  80149. var WebVRFreeCamera = /** @class */ (function (_super) {
  80150. __extends(WebVRFreeCamera, _super);
  80151. /**
  80152. * Instantiates a WebVRFreeCamera.
  80153. * @param name The name of the WebVRFreeCamera
  80154. * @param position The starting anchor position for the camera
  80155. * @param scene The scene the camera belongs to
  80156. * @param webVROptions a set of customizable options for the webVRCamera
  80157. */
  80158. function WebVRFreeCamera(name, position, scene, webVROptions) {
  80159. if (webVROptions === void 0) { webVROptions = {}; }
  80160. var _this = _super.call(this, name, position, scene) || this;
  80161. _this.webVROptions = webVROptions;
  80162. /**
  80163. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  80164. */
  80165. _this._vrDevice = null;
  80166. /**
  80167. * The rawPose of the vrDevice.
  80168. */
  80169. _this.rawPose = null;
  80170. _this._specsVersion = "1.1";
  80171. _this._attached = false;
  80172. _this._descendants = [];
  80173. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80174. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80175. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  80176. _this._standingMatrix = null;
  80177. /**
  80178. * Represents device position in babylon space.
  80179. */
  80180. _this.devicePosition = BABYLON.Vector3.Zero();
  80181. /**
  80182. * Represents device rotation in babylon space.
  80183. */
  80184. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  80185. /**
  80186. * The scale of the device to be used when translating from device space to babylon space.
  80187. */
  80188. _this.deviceScaleFactor = 1;
  80189. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80190. _this._worldToDevice = BABYLON.Matrix.Identity();
  80191. /**
  80192. * References to the webVR controllers for the vrDevice.
  80193. */
  80194. _this.controllers = [];
  80195. /**
  80196. * Emits an event when a controller is attached.
  80197. */
  80198. _this.onControllersAttachedObservable = new BABYLON.Observable();
  80199. /**
  80200. * Emits an event when a controller's mesh has been loaded;
  80201. */
  80202. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80203. /**
  80204. * If the rig cameras be used as parent instead of this camera.
  80205. */
  80206. _this.rigParenting = true;
  80207. _this._defaultHeight = undefined;
  80208. _this._workingVector = BABYLON.Vector3.Zero();
  80209. _this._oneVector = BABYLON.Vector3.One();
  80210. _this._workingMatrix = BABYLON.Matrix.Identity();
  80211. _this._cache.position = BABYLON.Vector3.Zero();
  80212. if (webVROptions.defaultHeight) {
  80213. _this._defaultHeight = webVROptions.defaultHeight;
  80214. _this.position.y = _this._defaultHeight;
  80215. }
  80216. _this.minZ = 0.1;
  80217. //legacy support - the compensation boolean was removed.
  80218. if (arguments.length === 5) {
  80219. _this.webVROptions = arguments[4];
  80220. }
  80221. // default webVR options
  80222. if (_this.webVROptions.trackPosition == undefined) {
  80223. _this.webVROptions.trackPosition = true;
  80224. }
  80225. if (_this.webVROptions.controllerMeshes == undefined) {
  80226. _this.webVROptions.controllerMeshes = true;
  80227. }
  80228. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  80229. _this.webVROptions.defaultLightingOnControllers = true;
  80230. }
  80231. _this.rotationQuaternion = new BABYLON.Quaternion();
  80232. if (_this.webVROptions && _this.webVROptions.positionScale) {
  80233. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  80234. }
  80235. //enable VR
  80236. var engine = _this.getEngine();
  80237. _this._onVREnabled = function (success) { if (success) {
  80238. _this.initControllers();
  80239. } };
  80240. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  80241. engine.initWebVR().add(function (event) {
  80242. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  80243. return;
  80244. }
  80245. _this._vrDevice = event.vrDisplay;
  80246. //reset the rig parameters.
  80247. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  80248. if (_this._attached) {
  80249. _this.getEngine().enableVR();
  80250. }
  80251. });
  80252. if (typeof (VRFrameData) !== "undefined")
  80253. _this._frameData = new VRFrameData();
  80254. /**
  80255. * The idea behind the following lines:
  80256. * objects that have the camera as parent should actually have the rig cameras as a parent.
  80257. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  80258. * the second will not show it correctly.
  80259. *
  80260. * To solve this - each object that has the camera as parent will be added to a protected array.
  80261. * When the rig camera renders, it will take this array and set all of those to be its children.
  80262. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  80263. * Amazing!
  80264. */
  80265. scene.onBeforeCameraRenderObservable.add(function (camera) {
  80266. if (camera.parent === _this && _this.rigParenting) {
  80267. _this._descendants = _this.getDescendants(true, function (n) {
  80268. // don't take the cameras or the controllers!
  80269. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  80270. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  80271. return !isController && !isRigCamera;
  80272. });
  80273. _this._descendants.forEach(function (node) {
  80274. node.parent = camera;
  80275. });
  80276. }
  80277. });
  80278. scene.onAfterCameraRenderObservable.add(function (camera) {
  80279. if (camera.parent === _this && _this.rigParenting) {
  80280. _this._descendants.forEach(function (node) {
  80281. node.parent = _this;
  80282. });
  80283. }
  80284. });
  80285. return _this;
  80286. }
  80287. /**
  80288. * Gets the device distance from the ground in meters.
  80289. * @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.
  80290. */
  80291. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  80292. if (this._standingMatrix) {
  80293. // Add standing matrix offset to get real offset from ground in room
  80294. this._standingMatrix.getTranslationToRef(this._workingVector);
  80295. return this._deviceRoomPosition.y + this._workingVector.y;
  80296. }
  80297. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  80298. return this._defaultHeight || 0;
  80299. };
  80300. /**
  80301. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80302. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  80303. */
  80304. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  80305. var _this = this;
  80306. if (callback === void 0) { callback = function (bool) { }; }
  80307. // Use standing matrix if available
  80308. this.getEngine().initWebVRAsync().then(function (result) {
  80309. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  80310. callback(false);
  80311. }
  80312. else {
  80313. _this._standingMatrix = new BABYLON.Matrix();
  80314. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  80315. if (!_this.getScene().useRightHandedSystem) {
  80316. [2, 6, 8, 9, 14].forEach(function (num) {
  80317. if (_this._standingMatrix) {
  80318. _this._standingMatrix.m[num] *= -1;
  80319. }
  80320. });
  80321. }
  80322. callback(true);
  80323. }
  80324. });
  80325. };
  80326. /**
  80327. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80328. * @returns A promise with a boolean set to if the standing matrix is supported.
  80329. */
  80330. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  80331. var _this = this;
  80332. return new Promise(function (res, rej) {
  80333. _this.useStandingMatrix(function (supported) {
  80334. res(supported);
  80335. });
  80336. });
  80337. };
  80338. /**
  80339. * Disposes the camera
  80340. */
  80341. WebVRFreeCamera.prototype.dispose = function () {
  80342. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  80343. _super.prototype.dispose.call(this);
  80344. };
  80345. /**
  80346. * Gets a vrController by name.
  80347. * @param name The name of the controller to retreive
  80348. * @returns the controller matching the name specified or null if not found
  80349. */
  80350. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  80351. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  80352. var gp = _a[_i];
  80353. if (gp.hand === name) {
  80354. return gp;
  80355. }
  80356. }
  80357. return null;
  80358. };
  80359. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  80360. /**
  80361. * The controller corrisponding to the users left hand.
  80362. */
  80363. get: function () {
  80364. if (!this._leftController) {
  80365. this._leftController = this.getControllerByName("left");
  80366. }
  80367. return this._leftController;
  80368. },
  80369. enumerable: true,
  80370. configurable: true
  80371. });
  80372. ;
  80373. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  80374. /**
  80375. * The controller corrisponding to the users right hand.
  80376. */
  80377. get: function () {
  80378. if (!this._rightController) {
  80379. this._rightController = this.getControllerByName("right");
  80380. }
  80381. return this._rightController;
  80382. },
  80383. enumerable: true,
  80384. configurable: true
  80385. });
  80386. ;
  80387. /**
  80388. * Casts a ray forward from the vrCamera's gaze.
  80389. * @param length Length of the ray (default: 100)
  80390. * @returns the ray corrisponding to the gaze
  80391. */
  80392. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  80393. if (length === void 0) { length = 100; }
  80394. if (this.leftCamera) {
  80395. // Use left eye to avoid computation to compute center on every call
  80396. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  80397. }
  80398. else {
  80399. return _super.prototype.getForwardRay.call(this, length);
  80400. }
  80401. };
  80402. /**
  80403. * Updates the camera based on device's frame data
  80404. */
  80405. WebVRFreeCamera.prototype._checkInputs = function () {
  80406. if (this._vrDevice && this._vrDevice.isPresenting) {
  80407. this._vrDevice.getFrameData(this._frameData);
  80408. this.updateFromDevice(this._frameData.pose);
  80409. }
  80410. _super.prototype._checkInputs.call(this);
  80411. };
  80412. /**
  80413. * Updates the poseControlled values based on the input device pose.
  80414. * @param poseData Pose coming from the device
  80415. */
  80416. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  80417. if (poseData && poseData.orientation) {
  80418. this.rawPose = poseData;
  80419. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  80420. if (this.getScene().useRightHandedSystem) {
  80421. this._deviceRoomRotationQuaternion.z *= -1;
  80422. this._deviceRoomRotationQuaternion.w *= -1;
  80423. }
  80424. if (this.webVROptions.trackPosition && this.rawPose.position) {
  80425. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  80426. if (this.getScene().useRightHandedSystem) {
  80427. this._deviceRoomPosition.z *= -1;
  80428. }
  80429. }
  80430. }
  80431. };
  80432. /**
  80433. * WebVR's attach control will start broadcasting frames to the device.
  80434. * Note that in certain browsers (chrome for example) this function must be called
  80435. * within a user-interaction callback. Example:
  80436. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  80437. *
  80438. * @param element html element to attach the vrDevice to
  80439. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  80440. */
  80441. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  80442. _super.prototype.attachControl.call(this, element, noPreventDefault);
  80443. this._attached = true;
  80444. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  80445. if (this._vrDevice) {
  80446. this.getEngine().enableVR();
  80447. }
  80448. };
  80449. /**
  80450. * Detaches the camera from the html element and disables VR
  80451. *
  80452. * @param element html element to detach from
  80453. */
  80454. WebVRFreeCamera.prototype.detachControl = function (element) {
  80455. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80456. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80457. _super.prototype.detachControl.call(this, element);
  80458. this._attached = false;
  80459. this.getEngine().disableVR();
  80460. };
  80461. /**
  80462. * @returns the name of this class
  80463. */
  80464. WebVRFreeCamera.prototype.getClassName = function () {
  80465. return "WebVRFreeCamera";
  80466. };
  80467. /**
  80468. * Calls resetPose on the vrDisplay
  80469. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  80470. */
  80471. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  80472. //uses the vrDisplay's "resetPose()".
  80473. //pitch and roll won't be affected.
  80474. this._vrDevice.resetPose();
  80475. };
  80476. /**
  80477. * Updates the rig cameras (left and right eye)
  80478. */
  80479. WebVRFreeCamera.prototype._updateRigCameras = function () {
  80480. var camLeft = this._rigCameras[0];
  80481. var camRight = this._rigCameras[1];
  80482. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80483. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80484. camLeft.position.copyFrom(this._deviceRoomPosition);
  80485. camRight.position.copyFrom(this._deviceRoomPosition);
  80486. };
  80487. /**
  80488. * Updates the cached values of the camera
  80489. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  80490. */
  80491. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  80492. var _this = this;
  80493. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  80494. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  80495. if (!this.updateCacheCalled) {
  80496. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  80497. this.updateCacheCalled = true;
  80498. this.update();
  80499. }
  80500. // Set working vector to the device position in room space rotated by the new rotation
  80501. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  80502. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  80503. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  80504. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  80505. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  80506. // Add translation from anchor position
  80507. this._deviceToWorld.getTranslationToRef(this._workingVector);
  80508. this._workingVector.addInPlace(this.position);
  80509. this._workingVector.subtractInPlace(this._cache.position);
  80510. this._deviceToWorld.setTranslation(this._workingVector);
  80511. // Set an inverted matrix to be used when updating the camera
  80512. this._deviceToWorld.invertToRef(this._worldToDevice);
  80513. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  80514. this.controllers.forEach(function (controller) {
  80515. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  80516. controller.update();
  80517. });
  80518. }
  80519. if (!ignoreParentClass) {
  80520. _super.prototype._updateCache.call(this);
  80521. }
  80522. this.updateCacheCalled = false;
  80523. };
  80524. /**
  80525. * Updates the current device position and rotation in the babylon world
  80526. */
  80527. WebVRFreeCamera.prototype.update = function () {
  80528. // Get current device position in babylon world
  80529. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  80530. // Get current device rotation in babylon world
  80531. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  80532. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  80533. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80534. _super.prototype.update.call(this);
  80535. };
  80536. /**
  80537. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  80538. * @returns an identity matrix
  80539. */
  80540. WebVRFreeCamera.prototype._getViewMatrix = function () {
  80541. return BABYLON.Matrix.Identity();
  80542. };
  80543. /**
  80544. * This function is called by the two RIG cameras.
  80545. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  80546. */
  80547. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  80548. var _this = this;
  80549. // Update the parent camera prior to using a child camera to avoid desynchronization
  80550. var parentCamera = this._cameraRigParams["parentCamera"];
  80551. parentCamera._updateCache();
  80552. //WebVR 1.1
  80553. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  80554. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  80555. if (!this.getScene().useRightHandedSystem) {
  80556. [2, 6, 8, 9, 14].forEach(function (num) {
  80557. _this._webvrViewMatrix.m[num] *= -1;
  80558. });
  80559. }
  80560. // update the camera rotation matrix
  80561. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  80562. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  80563. // Computing target and final matrix
  80564. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  80565. // should the view matrix be updated with scale and position offset?
  80566. if (parentCamera.deviceScaleFactor !== 1) {
  80567. this._webvrViewMatrix.invert();
  80568. // scale the position, if set
  80569. if (parentCamera.deviceScaleFactor) {
  80570. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  80571. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  80572. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  80573. }
  80574. this._webvrViewMatrix.invert();
  80575. }
  80576. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  80577. return this._webvrViewMatrix;
  80578. };
  80579. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  80580. var _this = this;
  80581. var parentCamera = this.parent;
  80582. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  80583. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  80584. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  80585. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  80586. //babylon compatible matrix
  80587. if (!this.getScene().useRightHandedSystem) {
  80588. [8, 9, 10, 11].forEach(function (num) {
  80589. _this._projectionMatrix.m[num] *= -1;
  80590. });
  80591. }
  80592. return this._projectionMatrix;
  80593. };
  80594. /**
  80595. * Initializes the controllers and their meshes
  80596. */
  80597. WebVRFreeCamera.prototype.initControllers = function () {
  80598. var _this = this;
  80599. this.controllers = [];
  80600. var manager = this.getScene().gamepadManager;
  80601. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80602. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80603. var webVrController = gamepad;
  80604. if (webVrController.defaultModel) {
  80605. webVrController.defaultModel.setEnabled(false);
  80606. }
  80607. if (webVrController.hand === "right") {
  80608. _this._rightController = null;
  80609. }
  80610. if (webVrController.hand === "left") {
  80611. _this._leftController = null;
  80612. }
  80613. var controllerIndex = _this.controllers.indexOf(webVrController);
  80614. if (controllerIndex !== -1) {
  80615. _this.controllers.splice(controllerIndex, 1);
  80616. }
  80617. }
  80618. });
  80619. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80620. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80621. var webVrController_1 = gamepad;
  80622. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  80623. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  80624. if (_this.webVROptions.controllerMeshes) {
  80625. if (webVrController_1.defaultModel) {
  80626. webVrController_1.defaultModel.setEnabled(true);
  80627. }
  80628. else {
  80629. // Load the meshes
  80630. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  80631. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  80632. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  80633. if (_this.webVROptions.defaultLightingOnControllers) {
  80634. if (!_this._lightOnControllers) {
  80635. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  80636. }
  80637. var activateLightOnSubMeshes_1 = function (mesh, light) {
  80638. var children = mesh.getChildren();
  80639. if (children.length !== 0) {
  80640. children.forEach(function (mesh) {
  80641. light.includedOnlyMeshes.push(mesh);
  80642. activateLightOnSubMeshes_1(mesh, light);
  80643. });
  80644. }
  80645. };
  80646. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  80647. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  80648. }
  80649. });
  80650. }
  80651. }
  80652. webVrController_1.attachToPoseControlledCamera(_this);
  80653. // since this is async - sanity check. Is the controller already stored?
  80654. if (_this.controllers.indexOf(webVrController_1) === -1) {
  80655. //add to the controllers array
  80656. _this.controllers.push(webVrController_1);
  80657. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  80658. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  80659. // So we're overriding setting left & right manually to be sure
  80660. var firstViveWandDetected = false;
  80661. for (var i = 0; i < _this.controllers.length; i++) {
  80662. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80663. if (!firstViveWandDetected) {
  80664. firstViveWandDetected = true;
  80665. _this.controllers[i].hand = "left";
  80666. }
  80667. else {
  80668. _this.controllers[i].hand = "right";
  80669. }
  80670. }
  80671. }
  80672. //did we find enough controllers? Great! let the developer know.
  80673. if (_this.controllers.length >= 2) {
  80674. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  80675. }
  80676. }
  80677. }
  80678. });
  80679. };
  80680. return WebVRFreeCamera;
  80681. }(BABYLON.FreeCamera));
  80682. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  80683. })(BABYLON || (BABYLON = {}));
  80684. //# sourceMappingURL=babylon.webVRCamera.js.map
  80685. var BABYLON;
  80686. (function (BABYLON) {
  80687. // We're mainly based on the logic defined into the FreeCamera code
  80688. /**
  80689. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  80690. * being tilted forward or back and left or right.
  80691. */
  80692. var DeviceOrientationCamera = /** @class */ (function (_super) {
  80693. __extends(DeviceOrientationCamera, _super);
  80694. /**
  80695. * Creates a new device orientation camera. @see DeviceOrientationCamera
  80696. * @param name The name of the camera
  80697. * @param position The start position camera
  80698. * @param scene The scene the camera belongs to
  80699. */
  80700. function DeviceOrientationCamera(name, position, scene) {
  80701. var _this = _super.call(this, name, position, scene) || this;
  80702. _this._quaternionCache = new BABYLON.Quaternion();
  80703. _this.inputs.addDeviceOrientation();
  80704. return _this;
  80705. }
  80706. /**
  80707. * Gets the current instance class name ("DeviceOrientationCamera").
  80708. * This helps avoiding instanceof at run time.
  80709. * @returns the class name
  80710. */
  80711. DeviceOrientationCamera.prototype.getClassName = function () {
  80712. return "DeviceOrientationCamera";
  80713. };
  80714. /**
  80715. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  80716. */
  80717. DeviceOrientationCamera.prototype._checkInputs = function () {
  80718. _super.prototype._checkInputs.call(this);
  80719. this._quaternionCache.copyFrom(this.rotationQuaternion);
  80720. if (this._initialQuaternion) {
  80721. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80722. }
  80723. };
  80724. /**
  80725. * Reset the camera to its default orientation on the specified axis only.
  80726. * @param axis The axis to reset
  80727. */
  80728. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  80729. var _this = this;
  80730. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  80731. //can only work if this camera has a rotation quaternion already.
  80732. if (!this.rotationQuaternion)
  80733. return;
  80734. if (!this._initialQuaternion) {
  80735. this._initialQuaternion = new BABYLON.Quaternion();
  80736. }
  80737. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  80738. ['x', 'y', 'z'].forEach(function (axisName) {
  80739. if (!axis[axisName]) {
  80740. _this._initialQuaternion[axisName] = 0;
  80741. }
  80742. else {
  80743. _this._initialQuaternion[axisName] *= -1;
  80744. }
  80745. });
  80746. this._initialQuaternion.normalize();
  80747. //force rotation update
  80748. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80749. };
  80750. return DeviceOrientationCamera;
  80751. }(BABYLON.FreeCamera));
  80752. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  80753. })(BABYLON || (BABYLON = {}));
  80754. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  80755. var BABYLON;
  80756. (function (BABYLON) {
  80757. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  80758. __extends(VRDeviceOrientationFreeCamera, _super);
  80759. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80760. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80761. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80762. var _this = _super.call(this, name, position, scene) || this;
  80763. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80764. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80765. return _this;
  80766. }
  80767. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  80768. return "VRDeviceOrientationFreeCamera";
  80769. };
  80770. return VRDeviceOrientationFreeCamera;
  80771. }(BABYLON.DeviceOrientationCamera));
  80772. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  80773. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  80774. __extends(VRDeviceOrientationGamepadCamera, _super);
  80775. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80776. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80777. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80778. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  80779. _this.inputs.addGamepad();
  80780. return _this;
  80781. }
  80782. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  80783. return "VRDeviceOrientationGamepadCamera";
  80784. };
  80785. return VRDeviceOrientationGamepadCamera;
  80786. }(VRDeviceOrientationFreeCamera));
  80787. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  80788. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  80789. __extends(VRDeviceOrientationArcRotateCamera, _super);
  80790. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  80791. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80792. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80793. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80794. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80795. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80796. _this.inputs.addVRDeviceOrientation();
  80797. return _this;
  80798. }
  80799. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  80800. return "VRDeviceOrientationArcRotateCamera";
  80801. };
  80802. return VRDeviceOrientationArcRotateCamera;
  80803. }(BABYLON.ArcRotateCamera));
  80804. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  80805. })(BABYLON || (BABYLON = {}));
  80806. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  80807. var BABYLON;
  80808. (function (BABYLON) {
  80809. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  80810. __extends(AnaglyphFreeCamera, _super);
  80811. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  80812. var _this = _super.call(this, name, position, scene) || this;
  80813. _this.interaxialDistance = interaxialDistance;
  80814. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80815. return _this;
  80816. }
  80817. AnaglyphFreeCamera.prototype.getClassName = function () {
  80818. return "AnaglyphFreeCamera";
  80819. };
  80820. return AnaglyphFreeCamera;
  80821. }(BABYLON.FreeCamera));
  80822. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  80823. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  80824. __extends(AnaglyphArcRotateCamera, _super);
  80825. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  80826. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80827. _this.interaxialDistance = interaxialDistance;
  80828. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80829. return _this;
  80830. }
  80831. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  80832. return "AnaglyphArcRotateCamera";
  80833. };
  80834. return AnaglyphArcRotateCamera;
  80835. }(BABYLON.ArcRotateCamera));
  80836. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  80837. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  80838. __extends(AnaglyphGamepadCamera, _super);
  80839. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  80840. var _this = _super.call(this, name, position, scene) || this;
  80841. _this.interaxialDistance = interaxialDistance;
  80842. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80843. return _this;
  80844. }
  80845. AnaglyphGamepadCamera.prototype.getClassName = function () {
  80846. return "AnaglyphGamepadCamera";
  80847. };
  80848. return AnaglyphGamepadCamera;
  80849. }(BABYLON.GamepadCamera));
  80850. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  80851. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  80852. __extends(AnaglyphUniversalCamera, _super);
  80853. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  80854. var _this = _super.call(this, name, position, scene) || this;
  80855. _this.interaxialDistance = interaxialDistance;
  80856. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80857. return _this;
  80858. }
  80859. AnaglyphUniversalCamera.prototype.getClassName = function () {
  80860. return "AnaglyphUniversalCamera";
  80861. };
  80862. return AnaglyphUniversalCamera;
  80863. }(BABYLON.UniversalCamera));
  80864. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  80865. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  80866. __extends(StereoscopicFreeCamera, _super);
  80867. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80868. var _this = _super.call(this, name, position, scene) || this;
  80869. _this.interaxialDistance = interaxialDistance;
  80870. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80871. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80872. return _this;
  80873. }
  80874. StereoscopicFreeCamera.prototype.getClassName = function () {
  80875. return "StereoscopicFreeCamera";
  80876. };
  80877. return StereoscopicFreeCamera;
  80878. }(BABYLON.FreeCamera));
  80879. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  80880. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  80881. __extends(StereoscopicArcRotateCamera, _super);
  80882. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  80883. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80884. _this.interaxialDistance = interaxialDistance;
  80885. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80886. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80887. return _this;
  80888. }
  80889. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  80890. return "StereoscopicArcRotateCamera";
  80891. };
  80892. return StereoscopicArcRotateCamera;
  80893. }(BABYLON.ArcRotateCamera));
  80894. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  80895. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  80896. __extends(StereoscopicGamepadCamera, _super);
  80897. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80898. var _this = _super.call(this, name, position, scene) || this;
  80899. _this.interaxialDistance = interaxialDistance;
  80900. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80901. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80902. return _this;
  80903. }
  80904. StereoscopicGamepadCamera.prototype.getClassName = function () {
  80905. return "StereoscopicGamepadCamera";
  80906. };
  80907. return StereoscopicGamepadCamera;
  80908. }(BABYLON.GamepadCamera));
  80909. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  80910. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  80911. __extends(StereoscopicUniversalCamera, _super);
  80912. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80913. var _this = _super.call(this, name, position, scene) || this;
  80914. _this.interaxialDistance = interaxialDistance;
  80915. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80916. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80917. return _this;
  80918. }
  80919. StereoscopicUniversalCamera.prototype.getClassName = function () {
  80920. return "StereoscopicUniversalCamera";
  80921. };
  80922. return StereoscopicUniversalCamera;
  80923. }(BABYLON.UniversalCamera));
  80924. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  80925. })(BABYLON || (BABYLON = {}));
  80926. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  80927. var BABYLON;
  80928. (function (BABYLON) {
  80929. var VRExperienceHelperGazer = /** @class */ (function () {
  80930. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  80931. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  80932. this.scene = scene;
  80933. this._pointerDownOnMeshAsked = false;
  80934. this._isActionableMesh = false;
  80935. this._teleportationRequestInitiated = false;
  80936. this._teleportationBackRequestInitiated = false;
  80937. this._dpadPressed = true;
  80938. this._activePointer = false;
  80939. this._id = VRExperienceHelperGazer._idCounter++;
  80940. // Gaze tracker
  80941. if (!gazeTrackerToClone) {
  80942. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  80943. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80944. this._gazeTracker.isPickable = false;
  80945. this._gazeTracker.isVisible = false;
  80946. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  80947. targetMat.specularColor = BABYLON.Color3.Black();
  80948. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80949. targetMat.backFaceCulling = false;
  80950. this._gazeTracker.material = targetMat;
  80951. }
  80952. else {
  80953. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  80954. }
  80955. }
  80956. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  80957. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  80958. };
  80959. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  80960. this._pointerDownOnMeshAsked = true;
  80961. if (this._currentMeshSelected && this._currentHit) {
  80962. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  80963. }
  80964. };
  80965. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  80966. if (this._currentMeshSelected && this._currentHit) {
  80967. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  80968. }
  80969. this._pointerDownOnMeshAsked = false;
  80970. };
  80971. VRExperienceHelperGazer.prototype._activatePointer = function () {
  80972. this._activePointer = true;
  80973. };
  80974. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  80975. this._activePointer = false;
  80976. };
  80977. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  80978. };
  80979. VRExperienceHelperGazer.prototype.dispose = function () {
  80980. this._interactionsEnabled = false;
  80981. this._teleportationEnabled = false;
  80982. };
  80983. VRExperienceHelperGazer._idCounter = 0;
  80984. return VRExperienceHelperGazer;
  80985. }());
  80986. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  80987. __extends(VRExperienceHelperControllerGazer, _super);
  80988. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  80989. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  80990. _this.webVRController = webVRController;
  80991. // Laser pointer
  80992. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  80993. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  80994. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80995. laserPointerMaterial.alpha = 0.6;
  80996. _this._laserPointer.material = laserPointerMaterial;
  80997. _this._laserPointer.rotation.x = Math.PI / 2;
  80998. _this._laserPointer.position.z = -0.5;
  80999. _this._laserPointer.isVisible = false;
  81000. if (!webVRController.mesh) {
  81001. // Create an empty mesh that is used prior to loading the high quality model
  81002. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  81003. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  81004. preloadPointerPose.rotation.x = -0.7;
  81005. preloadMesh.addChild(preloadPointerPose);
  81006. webVRController.attachToMesh(preloadMesh);
  81007. }
  81008. _this._setLaserPointerParent(webVRController.mesh);
  81009. return _this;
  81010. }
  81011. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  81012. return this.webVRController.getForwardRay(length);
  81013. };
  81014. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  81015. _super.prototype._activatePointer.call(this);
  81016. this._laserPointer.isVisible = true;
  81017. };
  81018. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  81019. _super.prototype._deactivatePointer.call(this);
  81020. this._laserPointer.isVisible = false;
  81021. };
  81022. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  81023. this._laserPointer.material.emissiveColor = color;
  81024. };
  81025. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  81026. var makeNotPick = function (root) {
  81027. root.name += " laserPointer";
  81028. root.getChildMeshes().forEach(function (c) {
  81029. makeNotPick(c);
  81030. });
  81031. };
  81032. makeNotPick(mesh);
  81033. var childMeshes = mesh.getChildMeshes();
  81034. for (var i = 0; i < childMeshes.length; i++) {
  81035. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  81036. mesh = childMeshes[i];
  81037. this.webVRController._pointingPoseNode = mesh;
  81038. break;
  81039. }
  81040. }
  81041. this._laserPointer.parent = mesh;
  81042. };
  81043. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  81044. this._laserPointer.scaling.y = distance;
  81045. this._laserPointer.position.z = -distance / 2;
  81046. };
  81047. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  81048. _super.prototype.dispose.call(this);
  81049. this._laserPointer.dispose();
  81050. };
  81051. return VRExperienceHelperControllerGazer;
  81052. }(VRExperienceHelperGazer));
  81053. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  81054. __extends(VRExperienceHelperCameraGazer, _super);
  81055. function VRExperienceHelperCameraGazer(getCamera, scene) {
  81056. var _this = _super.call(this, scene) || this;
  81057. _this.getCamera = getCamera;
  81058. return _this;
  81059. }
  81060. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  81061. var camera = this.getCamera();
  81062. if (camera) {
  81063. return camera.getForwardRay(length);
  81064. }
  81065. else {
  81066. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  81067. }
  81068. };
  81069. return VRExperienceHelperCameraGazer;
  81070. }(VRExperienceHelperGazer));
  81071. /**
  81072. * Helps to quickly add VR support to an existing scene.
  81073. * See http://doc.babylonjs.com/how_to/webvr_helper
  81074. */
  81075. var VRExperienceHelper = /** @class */ (function () {
  81076. /**
  81077. * Instantiates a VRExperienceHelper.
  81078. * Helps to quickly add VR support to an existing scene.
  81079. * @param scene The scene the VRExperienceHelper belongs to.
  81080. * @param webVROptions Options to modify the vr experience helper's behavior.
  81081. */
  81082. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  81083. if (webVROptions === void 0) { webVROptions = {}; }
  81084. var _this = this;
  81085. this.webVROptions = webVROptions;
  81086. // Can the system support WebVR, even if a headset isn't plugged in?
  81087. this._webVRsupported = false;
  81088. // If WebVR is supported, is a headset plugged in and are we ready to present?
  81089. this._webVRready = false;
  81090. // Are we waiting for the requestPresent callback to complete?
  81091. this._webVRrequesting = false;
  81092. // Are we presenting to the headset right now?
  81093. this._webVRpresenting = false;
  81094. // Are we presenting in the fullscreen fallback?
  81095. this._fullscreenVRpresenting = false;
  81096. /**
  81097. * Observable raised when entering VR.
  81098. */
  81099. this.onEnteringVRObservable = new BABYLON.Observable();
  81100. /**
  81101. * Observable raised when exiting VR.
  81102. */
  81103. this.onExitingVRObservable = new BABYLON.Observable();
  81104. /**
  81105. * Observable raised when controller mesh is loaded.
  81106. */
  81107. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81108. this._useCustomVRButton = false;
  81109. this._teleportationRequested = false;
  81110. this._teleportActive = false;
  81111. this._floorMeshesCollection = [];
  81112. this._rotationAllowed = true;
  81113. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  81114. this._rotationRightAsked = false;
  81115. this._rotationLeftAsked = false;
  81116. this._isDefaultTeleportationTarget = true;
  81117. this._teleportationFillColor = "#444444";
  81118. this._teleportationBorderColor = "#FFFFFF";
  81119. this._rotationAngle = 0;
  81120. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  81121. this._padSensibilityUp = 0.65;
  81122. this._padSensibilityDown = 0.35;
  81123. this.leftController = null;
  81124. this.rightController = null;
  81125. /**
  81126. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  81127. */
  81128. this.onNewMeshSelected = new BABYLON.Observable();
  81129. /**
  81130. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  81131. */
  81132. this.onNewMeshPicked = new BABYLON.Observable();
  81133. /**
  81134. * Observable raised before camera teleportation
  81135. */
  81136. this.onBeforeCameraTeleport = new BABYLON.Observable();
  81137. /**
  81138. * Observable raised after camera teleportation
  81139. */
  81140. this.onAfterCameraTeleport = new BABYLON.Observable();
  81141. /**
  81142. * Observable raised when current selected mesh gets unselected
  81143. */
  81144. this.onSelectedMeshUnselected = new BABYLON.Observable();
  81145. /**
  81146. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  81147. */
  81148. this.teleportationEnabled = true;
  81149. this._teleportationInitialized = false;
  81150. this._interactionsEnabled = false;
  81151. this._interactionsRequested = false;
  81152. this._displayGaze = true;
  81153. this._displayLaserPointer = true;
  81154. this._onResize = function () {
  81155. _this.moveButtonToBottomRight();
  81156. if (_this._fullscreenVRpresenting && _this._webVRready) {
  81157. _this.exitVR();
  81158. }
  81159. };
  81160. this._onFullscreenChange = function () {
  81161. if (document.fullscreen !== undefined) {
  81162. _this._fullscreenVRpresenting = document.fullscreen;
  81163. }
  81164. else if (document.mozFullScreen !== undefined) {
  81165. _this._fullscreenVRpresenting = document.mozFullScreen;
  81166. }
  81167. else if (document.webkitIsFullScreen !== undefined) {
  81168. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  81169. }
  81170. else if (document.msIsFullScreen !== undefined) {
  81171. _this._fullscreenVRpresenting = document.msIsFullScreen;
  81172. }
  81173. if (!_this._fullscreenVRpresenting && _this._canvas) {
  81174. _this.exitVR();
  81175. if (!_this._useCustomVRButton) {
  81176. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  81177. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  81178. }
  81179. }
  81180. };
  81181. this.beforeRender = function () {
  81182. if (_this.leftController && _this.leftController._activePointer) {
  81183. _this._castRayAndSelectObject(_this.leftController);
  81184. }
  81185. if (_this.rightController && _this.rightController._activePointer) {
  81186. _this._castRayAndSelectObject(_this.rightController);
  81187. }
  81188. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  81189. _this._castRayAndSelectObject(_this._cameraGazer);
  81190. }
  81191. else {
  81192. _this._cameraGazer._gazeTracker.isVisible = false;
  81193. }
  81194. };
  81195. this._onNewGamepadConnected = function (gamepad) {
  81196. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81197. if (gamepad.leftStick) {
  81198. gamepad.onleftstickchanged(function (stickValues) {
  81199. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  81200. // Listening to classic/xbox gamepad only if no VR controller is active
  81201. if ((!_this.leftController && !_this.rightController) ||
  81202. ((_this.leftController && !_this.leftController._activePointer) &&
  81203. (_this.rightController && !_this.rightController._activePointer))) {
  81204. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  81205. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  81206. }
  81207. }
  81208. });
  81209. }
  81210. if (gamepad.rightStick) {
  81211. gamepad.onrightstickchanged(function (stickValues) {
  81212. if (_this._teleportationInitialized) {
  81213. _this._checkRotate(stickValues, _this._cameraGazer);
  81214. }
  81215. });
  81216. }
  81217. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  81218. gamepad.onbuttondown(function (buttonPressed) {
  81219. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81220. _this._cameraGazer._selectionPointerDown();
  81221. }
  81222. });
  81223. gamepad.onbuttonup(function (buttonPressed) {
  81224. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81225. _this._cameraGazer._selectionPointerUp();
  81226. }
  81227. });
  81228. }
  81229. }
  81230. else {
  81231. var webVRController = gamepad;
  81232. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  81233. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  81234. _this.rightController = controller;
  81235. }
  81236. else {
  81237. _this.leftController = controller;
  81238. }
  81239. _this._tryEnableInteractionOnController(controller);
  81240. }
  81241. };
  81242. // 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
  81243. this._tryEnableInteractionOnController = function (controller) {
  81244. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  81245. _this._enableInteractionOnController(controller);
  81246. }
  81247. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  81248. _this._enableTeleportationOnController(controller);
  81249. }
  81250. };
  81251. this._onNewGamepadDisconnected = function (gamepad) {
  81252. if (gamepad instanceof BABYLON.WebVRController) {
  81253. if (gamepad.hand === "left" && _this.leftController != null) {
  81254. _this.leftController.dispose();
  81255. _this.leftController = null;
  81256. }
  81257. if (gamepad.hand === "right" && _this.rightController != null) {
  81258. _this.rightController.dispose();
  81259. _this.rightController = null;
  81260. }
  81261. }
  81262. };
  81263. this._workingVector = BABYLON.Vector3.Zero();
  81264. this._workingQuaternion = BABYLON.Quaternion.Identity();
  81265. this._workingMatrix = BABYLON.Matrix.Identity();
  81266. this._scene = scene;
  81267. this._canvas = scene.getEngine().getRenderingCanvas();
  81268. // Parse options
  81269. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  81270. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  81271. }
  81272. if (webVROptions.createDeviceOrientationCamera === undefined) {
  81273. webVROptions.createDeviceOrientationCamera = true;
  81274. }
  81275. if (webVROptions.defaultHeight === undefined) {
  81276. webVROptions.defaultHeight = 1.7;
  81277. }
  81278. if (webVROptions.useCustomVRButton) {
  81279. this._useCustomVRButton = true;
  81280. if (webVROptions.customVRButton) {
  81281. this._btnVR = webVROptions.customVRButton;
  81282. }
  81283. }
  81284. if (webVROptions.rayLength) {
  81285. this._rayLength = webVROptions.rayLength;
  81286. }
  81287. this._defaultHeight = webVROptions.defaultHeight;
  81288. if (webVROptions.positionScale) {
  81289. this._rayLength *= webVROptions.positionScale;
  81290. this._defaultHeight *= webVROptions.positionScale;
  81291. }
  81292. // Set position
  81293. if (this._scene.activeCamera) {
  81294. this._position = this._scene.activeCamera.position.clone();
  81295. }
  81296. else {
  81297. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  81298. }
  81299. // Set non-vr camera
  81300. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  81301. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  81302. // Copy data from existing camera
  81303. if (this._scene.activeCamera) {
  81304. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  81305. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  81306. // Set rotation from previous camera
  81307. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  81308. var targetCamera = this._scene.activeCamera;
  81309. if (targetCamera.rotationQuaternion) {
  81310. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  81311. }
  81312. else {
  81313. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  81314. }
  81315. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  81316. }
  81317. }
  81318. this._scene.activeCamera = this._deviceOrientationCamera;
  81319. if (this._canvas) {
  81320. this._scene.activeCamera.attachControl(this._canvas);
  81321. }
  81322. }
  81323. else {
  81324. this._existingCamera = this._scene.activeCamera;
  81325. }
  81326. // Create VR cameras
  81327. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81328. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  81329. }
  81330. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  81331. this._webVRCamera.useStandingMatrix();
  81332. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  81333. // Create default button
  81334. if (!this._useCustomVRButton) {
  81335. this._btnVR = document.createElement("BUTTON");
  81336. this._btnVR.className = "babylonVRicon";
  81337. this._btnVR.id = "babylonVRiconbtn";
  81338. this._btnVR.title = "Click to switch to VR";
  81339. 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) }";
  81340. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  81341. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  81342. // css += ".babylonVRicon.vrdisplaysupported { }";
  81343. // css += ".babylonVRicon.vrdisplayready { }";
  81344. // css += ".babylonVRicon.vrdisplayrequesting { }";
  81345. var style = document.createElement('style');
  81346. style.appendChild(document.createTextNode(css));
  81347. document.getElementsByTagName('head')[0].appendChild(style);
  81348. this.moveButtonToBottomRight();
  81349. }
  81350. // VR button click event
  81351. if (this._btnVR) {
  81352. this._btnVR.addEventListener("click", function () {
  81353. if (!_this.isInVRMode) {
  81354. _this.enterVR();
  81355. }
  81356. else {
  81357. _this.exitVR();
  81358. }
  81359. });
  81360. }
  81361. // Window events
  81362. window.addEventListener("resize", this._onResize);
  81363. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  81364. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  81365. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  81366. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  81367. // Display vr button when headset is connected
  81368. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81369. this.displayVRButton();
  81370. }
  81371. else {
  81372. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  81373. if (e.vrDisplay) {
  81374. _this.displayVRButton();
  81375. }
  81376. });
  81377. }
  81378. // Exiting VR mode using 'ESC' key on desktop
  81379. this._onKeyDown = function (event) {
  81380. if (event.keyCode === 27 && _this.isInVRMode) {
  81381. _this.exitVR();
  81382. }
  81383. };
  81384. document.addEventListener("keydown", this._onKeyDown);
  81385. // Exiting VR mode double tapping the touch screen
  81386. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  81387. if (_this.isInVRMode) {
  81388. _this.exitVR();
  81389. if (_this._fullscreenVRpresenting) {
  81390. _this._scene.getEngine().switchFullscreen(true);
  81391. }
  81392. }
  81393. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  81394. // Listen for WebVR display changes
  81395. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  81396. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  81397. this._onVRRequestPresentStart = function () {
  81398. _this._webVRrequesting = true;
  81399. _this.updateButtonVisibility();
  81400. };
  81401. this._onVRRequestPresentComplete = function (success) {
  81402. _this._webVRrequesting = false;
  81403. _this.updateButtonVisibility();
  81404. };
  81405. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  81406. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  81407. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  81408. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81409. scene.onDisposeObservable.add(function () {
  81410. _this.dispose();
  81411. });
  81412. // Gamepad connection events
  81413. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  81414. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  81415. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  81416. this.updateButtonVisibility();
  81417. //create easing functions
  81418. this._circleEase = new BABYLON.CircleEase();
  81419. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81420. }
  81421. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  81422. /** Return this.onEnteringVRObservable
  81423. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  81424. */
  81425. get: function () {
  81426. return this.onEnteringVRObservable;
  81427. },
  81428. enumerable: true,
  81429. configurable: true
  81430. });
  81431. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  81432. /** Return this.onExitingVRObservable
  81433. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  81434. */
  81435. get: function () {
  81436. return this.onExitingVRObservable;
  81437. },
  81438. enumerable: true,
  81439. configurable: true
  81440. });
  81441. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  81442. /** Return this.onControllerMeshLoadedObservable
  81443. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  81444. */
  81445. get: function () {
  81446. return this.onControllerMeshLoadedObservable;
  81447. },
  81448. enumerable: true,
  81449. configurable: true
  81450. });
  81451. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  81452. /**
  81453. * The mesh used to display where the user is going to teleport.
  81454. */
  81455. get: function () {
  81456. return this._teleportationTarget;
  81457. },
  81458. /**
  81459. * Sets the mesh to be used to display where the user is going to teleport.
  81460. */
  81461. set: function (value) {
  81462. if (value) {
  81463. value.name = "teleportationTarget";
  81464. this._isDefaultTeleportationTarget = false;
  81465. this._teleportationTarget = value;
  81466. }
  81467. },
  81468. enumerable: true,
  81469. configurable: true
  81470. });
  81471. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  81472. /**
  81473. * The mesh used to display where the user is selecting,
  81474. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  81475. * See http://doc.babylonjs.com/resources/baking_transformations
  81476. */
  81477. get: function () {
  81478. return this._cameraGazer._gazeTracker;
  81479. },
  81480. set: function (value) {
  81481. if (value) {
  81482. this._cameraGazer._gazeTracker = value;
  81483. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  81484. this._cameraGazer._gazeTracker.isPickable = false;
  81485. this._cameraGazer._gazeTracker.isVisible = false;
  81486. this._cameraGazer._gazeTracker.name = "gazeTracker";
  81487. if (this.leftController) {
  81488. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81489. }
  81490. if (this.rightController) {
  81491. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81492. }
  81493. }
  81494. },
  81495. enumerable: true,
  81496. configurable: true
  81497. });
  81498. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  81499. /**
  81500. * If the ray of the gaze should be displayed.
  81501. */
  81502. get: function () {
  81503. return this._displayGaze;
  81504. },
  81505. /**
  81506. * Sets if the ray of the gaze should be displayed.
  81507. */
  81508. set: function (value) {
  81509. this._displayGaze = value;
  81510. if (!value) {
  81511. this._cameraGazer._gazeTracker.isVisible = false;
  81512. if (this.leftController) {
  81513. this.leftController._gazeTracker.isVisible = false;
  81514. }
  81515. if (this.rightController) {
  81516. this.rightController._gazeTracker.isVisible = false;
  81517. }
  81518. }
  81519. },
  81520. enumerable: true,
  81521. configurable: true
  81522. });
  81523. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  81524. /**
  81525. * If the ray of the LaserPointer should be displayed.
  81526. */
  81527. get: function () {
  81528. return this._displayLaserPointer;
  81529. },
  81530. /**
  81531. * Sets if the ray of the LaserPointer should be displayed.
  81532. */
  81533. set: function (value) {
  81534. this._displayLaserPointer = value;
  81535. if (!value) {
  81536. if (this.rightController) {
  81537. this.rightController._deactivatePointer();
  81538. this.rightController._gazeTracker.isVisible = false;
  81539. }
  81540. if (this.leftController) {
  81541. this.leftController._deactivatePointer();
  81542. this.leftController._gazeTracker.isVisible = false;
  81543. }
  81544. }
  81545. else {
  81546. if (this.rightController) {
  81547. this.rightController._activatePointer();
  81548. }
  81549. else if (this.leftController) {
  81550. this.leftController._activatePointer();
  81551. }
  81552. }
  81553. },
  81554. enumerable: true,
  81555. configurable: true
  81556. });
  81557. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  81558. /**
  81559. * The deviceOrientationCamera used as the camera when not in VR.
  81560. */
  81561. get: function () {
  81562. return this._deviceOrientationCamera;
  81563. },
  81564. enumerable: true,
  81565. configurable: true
  81566. });
  81567. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  81568. /**
  81569. * Based on the current WebVR support, returns the current VR camera used.
  81570. */
  81571. get: function () {
  81572. if (this._webVRready) {
  81573. return this._webVRCamera;
  81574. }
  81575. else {
  81576. return this._scene.activeCamera;
  81577. }
  81578. },
  81579. enumerable: true,
  81580. configurable: true
  81581. });
  81582. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  81583. /**
  81584. * The webVRCamera which is used when in VR.
  81585. */
  81586. get: function () {
  81587. return this._webVRCamera;
  81588. },
  81589. enumerable: true,
  81590. configurable: true
  81591. });
  81592. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  81593. /**
  81594. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  81595. */
  81596. get: function () {
  81597. return this._vrDeviceOrientationCamera;
  81598. },
  81599. enumerable: true,
  81600. configurable: true
  81601. });
  81602. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  81603. get: function () {
  81604. var result = this._cameraGazer._teleportationRequestInitiated
  81605. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  81606. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  81607. return result;
  81608. },
  81609. enumerable: true,
  81610. configurable: true
  81611. });
  81612. // Raised when one of the controller has loaded successfully its associated default mesh
  81613. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  81614. if (this.leftController && this.leftController.webVRController == webVRController) {
  81615. if (webVRController.mesh) {
  81616. this.leftController._setLaserPointerParent(webVRController.mesh);
  81617. }
  81618. }
  81619. if (this.rightController && this.rightController.webVRController == webVRController) {
  81620. if (webVRController.mesh) {
  81621. this.rightController._setLaserPointerParent(webVRController.mesh);
  81622. }
  81623. }
  81624. try {
  81625. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  81626. }
  81627. catch (err) {
  81628. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  81629. }
  81630. };
  81631. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  81632. /**
  81633. * Gets a value indicating if we are currently in VR mode.
  81634. */
  81635. get: function () {
  81636. return this._webVRpresenting || this._fullscreenVRpresenting;
  81637. },
  81638. enumerable: true,
  81639. configurable: true
  81640. });
  81641. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  81642. var vrDisplay = this._scene.getEngine().getVRDevice();
  81643. if (vrDisplay) {
  81644. var wasPresenting = this._webVRpresenting;
  81645. // A VR display is connected
  81646. this._webVRpresenting = vrDisplay.isPresenting;
  81647. if (wasPresenting && !this._webVRpresenting)
  81648. this.exitVR();
  81649. }
  81650. else {
  81651. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  81652. }
  81653. this.updateButtonVisibility();
  81654. };
  81655. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  81656. this._webVRsupported = eventArgs.vrSupported;
  81657. this._webVRready = !!eventArgs.vrDisplay;
  81658. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  81659. this.updateButtonVisibility();
  81660. };
  81661. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  81662. if (this._canvas && !this._useCustomVRButton) {
  81663. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  81664. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  81665. }
  81666. };
  81667. VRExperienceHelper.prototype.displayVRButton = function () {
  81668. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  81669. document.body.appendChild(this._btnVR);
  81670. this._btnVRDisplayed = true;
  81671. }
  81672. };
  81673. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  81674. if (!this._btnVR || this._useCustomVRButton) {
  81675. return;
  81676. }
  81677. this._btnVR.className = "babylonVRicon";
  81678. if (this.isInVRMode) {
  81679. this._btnVR.className += " vrdisplaypresenting";
  81680. }
  81681. else {
  81682. if (this._webVRready)
  81683. this._btnVR.className += " vrdisplayready";
  81684. if (this._webVRsupported)
  81685. this._btnVR.className += " vrdisplaysupported";
  81686. if (this._webVRrequesting)
  81687. this._btnVR.className += " vrdisplayrequesting";
  81688. }
  81689. };
  81690. /**
  81691. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  81692. * Otherwise, will use the fullscreen API.
  81693. */
  81694. VRExperienceHelper.prototype.enterVR = function () {
  81695. if (this.onEnteringVRObservable) {
  81696. try {
  81697. this.onEnteringVRObservable.notifyObservers(this);
  81698. }
  81699. catch (err) {
  81700. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  81701. }
  81702. }
  81703. if (this._scene.activeCamera) {
  81704. this._position = this._scene.activeCamera.position.clone();
  81705. // make sure that we return to the last active camera
  81706. this._existingCamera = this._scene.activeCamera;
  81707. }
  81708. if (this._webVRrequesting)
  81709. return;
  81710. // If WebVR is supported and a headset is connected
  81711. if (this._webVRready) {
  81712. if (!this._webVRpresenting) {
  81713. this._webVRCamera.position = this._position;
  81714. this._scene.activeCamera = this._webVRCamera;
  81715. }
  81716. }
  81717. else if (this._vrDeviceOrientationCamera) {
  81718. this._vrDeviceOrientationCamera.position = this._position;
  81719. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  81720. this._scene.getEngine().switchFullscreen(true);
  81721. this.updateButtonVisibility();
  81722. }
  81723. if (this._scene.activeCamera && this._canvas) {
  81724. this._scene.activeCamera.attachControl(this._canvas);
  81725. }
  81726. if (this._interactionsEnabled) {
  81727. this._scene.registerBeforeRender(this.beforeRender);
  81728. }
  81729. };
  81730. /**
  81731. * Attempt to exit VR, or fullscreen.
  81732. */
  81733. VRExperienceHelper.prototype.exitVR = function () {
  81734. if (this.onExitingVRObservable) {
  81735. try {
  81736. this.onExitingVRObservable.notifyObservers(this);
  81737. }
  81738. catch (err) {
  81739. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  81740. }
  81741. }
  81742. if (this._webVRpresenting) {
  81743. this._scene.getEngine().disableVR();
  81744. }
  81745. if (this._scene.activeCamera) {
  81746. this._position = this._scene.activeCamera.position.clone();
  81747. }
  81748. if (this._deviceOrientationCamera) {
  81749. this._deviceOrientationCamera.position = this._position;
  81750. this._scene.activeCamera = this._deviceOrientationCamera;
  81751. if (this._canvas) {
  81752. this._scene.activeCamera.attachControl(this._canvas);
  81753. }
  81754. }
  81755. else if (this._existingCamera) {
  81756. this._existingCamera.position = this._position;
  81757. this._scene.activeCamera = this._existingCamera;
  81758. }
  81759. this.updateButtonVisibility();
  81760. if (this._interactionsEnabled) {
  81761. this._scene.unregisterBeforeRender(this.beforeRender);
  81762. }
  81763. };
  81764. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  81765. /**
  81766. * The position of the vr experience helper.
  81767. */
  81768. get: function () {
  81769. return this._position;
  81770. },
  81771. /**
  81772. * Sets the position of the vr experience helper.
  81773. */
  81774. set: function (value) {
  81775. this._position = value;
  81776. if (this._scene.activeCamera) {
  81777. this._scene.activeCamera.position = value;
  81778. }
  81779. },
  81780. enumerable: true,
  81781. configurable: true
  81782. });
  81783. /**
  81784. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  81785. */
  81786. VRExperienceHelper.prototype.enableInteractions = function () {
  81787. var _this = this;
  81788. if (!this._interactionsEnabled) {
  81789. this._interactionsRequested = true;
  81790. if (this.leftController) {
  81791. this._enableInteractionOnController(this.leftController);
  81792. }
  81793. if (this.rightController) {
  81794. this._enableInteractionOnController(this.rightController);
  81795. }
  81796. this.raySelectionPredicate = function (mesh) {
  81797. return mesh.isVisible;
  81798. };
  81799. this.meshSelectionPredicate = function (mesh) {
  81800. return true;
  81801. };
  81802. this._raySelectionPredicate = function (mesh) {
  81803. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  81804. && mesh.name.indexOf("teleportationTarget") === -1
  81805. && mesh.name.indexOf("torusTeleportation") === -1
  81806. && mesh.name.indexOf("laserPointer") === -1)) {
  81807. return _this.raySelectionPredicate(mesh);
  81808. }
  81809. return false;
  81810. };
  81811. this._interactionsEnabled = true;
  81812. }
  81813. };
  81814. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  81815. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  81816. if (this._floorMeshesCollection[i].id === mesh.id) {
  81817. return true;
  81818. }
  81819. }
  81820. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  81821. return true;
  81822. }
  81823. return false;
  81824. };
  81825. /**
  81826. * Adds a floor mesh to be used for teleportation.
  81827. * @param floorMesh the mesh to be used for teleportation.
  81828. */
  81829. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  81830. if (!this._floorMeshesCollection) {
  81831. return;
  81832. }
  81833. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  81834. return;
  81835. }
  81836. this._floorMeshesCollection.push(floorMesh);
  81837. };
  81838. /**
  81839. * Removes a floor mesh from being used for teleportation.
  81840. * @param floorMesh the mesh to be removed.
  81841. */
  81842. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  81843. if (!this._floorMeshesCollection) {
  81844. return;
  81845. }
  81846. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  81847. if (meshIndex !== -1) {
  81848. this._floorMeshesCollection.splice(meshIndex, 1);
  81849. }
  81850. };
  81851. /**
  81852. * Enables interactions and teleportation using the VR controllers and gaze.
  81853. * @param vrTeleportationOptions options to modify teleportation behavior.
  81854. */
  81855. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  81856. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  81857. if (!this._teleportationInitialized) {
  81858. this._teleportationRequested = true;
  81859. this.enableInteractions();
  81860. if (vrTeleportationOptions.floorMeshName) {
  81861. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  81862. }
  81863. if (vrTeleportationOptions.floorMeshes) {
  81864. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  81865. }
  81866. if (this.leftController != null) {
  81867. this._enableTeleportationOnController(this.leftController);
  81868. }
  81869. if (this.rightController != null) {
  81870. this._enableTeleportationOnController(this.rightController);
  81871. }
  81872. // Creates an image processing post process for the vignette not relying
  81873. // on the main scene configuration for image processing to reduce setup and spaces
  81874. // (gamma/linear) conflicts.
  81875. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  81876. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81877. imageProcessingConfiguration.vignetteEnabled = true;
  81878. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  81879. this._webVRCamera.detachPostProcess(this._postProcessMove);
  81880. this._teleportationInitialized = true;
  81881. if (this._isDefaultTeleportationTarget) {
  81882. this._createTeleportationCircles();
  81883. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  81884. }
  81885. }
  81886. };
  81887. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  81888. var _this = this;
  81889. var controllerMesh = controller.webVRController.mesh;
  81890. if (controllerMesh) {
  81891. controller._interactionsEnabled = true;
  81892. controller._activatePointer();
  81893. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  81894. // Enabling / disabling laserPointer
  81895. if (_this._displayLaserPointer && stateObject.value === 1) {
  81896. if (controller._activePointer) {
  81897. controller._deactivatePointer();
  81898. }
  81899. else {
  81900. controller._activatePointer();
  81901. }
  81902. if (_this.displayGaze) {
  81903. controller._gazeTracker.isVisible = controller._activePointer;
  81904. }
  81905. }
  81906. });
  81907. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  81908. if (!controller._pointerDownOnMeshAsked) {
  81909. if (stateObject.value > _this._padSensibilityUp) {
  81910. controller._selectionPointerDown();
  81911. }
  81912. }
  81913. else if (stateObject.value < _this._padSensibilityDown) {
  81914. controller._selectionPointerUp();
  81915. }
  81916. });
  81917. }
  81918. };
  81919. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  81920. // Dont teleport if another gaze already requested teleportation
  81921. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  81922. return;
  81923. }
  81924. if (!gazer._teleportationRequestInitiated) {
  81925. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  81926. gazer._activatePointer();
  81927. gazer._teleportationRequestInitiated = true;
  81928. }
  81929. }
  81930. else {
  81931. // Listening to the proper controller values changes to confirm teleportation
  81932. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  81933. if (this._teleportActive) {
  81934. this._teleportCamera(this._haloCenter);
  81935. }
  81936. gazer._teleportationRequestInitiated = false;
  81937. }
  81938. }
  81939. };
  81940. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  81941. // Only rotate when user is not currently selecting a teleportation location
  81942. if (gazer._teleportationRequestInitiated) {
  81943. return;
  81944. }
  81945. if (!this._rotationLeftAsked) {
  81946. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  81947. this._rotationLeftAsked = true;
  81948. if (this._rotationAllowed) {
  81949. this._rotateCamera(false);
  81950. }
  81951. }
  81952. }
  81953. else {
  81954. if (stateObject.x > -this._padSensibilityDown) {
  81955. this._rotationLeftAsked = false;
  81956. }
  81957. }
  81958. if (!this._rotationRightAsked) {
  81959. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  81960. this._rotationRightAsked = true;
  81961. if (this._rotationAllowed) {
  81962. this._rotateCamera(true);
  81963. }
  81964. }
  81965. }
  81966. else {
  81967. if (stateObject.x < this._padSensibilityDown) {
  81968. this._rotationRightAsked = false;
  81969. }
  81970. }
  81971. };
  81972. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  81973. // Only teleport backwards when user is not currently selecting a teleportation location
  81974. if (gazer._teleportationRequestInitiated) {
  81975. return;
  81976. }
  81977. // Teleport backwards
  81978. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  81979. if (!gazer._teleportationBackRequestInitiated) {
  81980. if (!this.currentVRCamera) {
  81981. return;
  81982. }
  81983. // Get rotation and position of the current camera
  81984. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  81985. var position = this.currentVRCamera.position;
  81986. // If the camera has device position, use that instead
  81987. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  81988. rotation = this.currentVRCamera.deviceRotationQuaternion;
  81989. position = this.currentVRCamera.devicePosition;
  81990. }
  81991. // Get matrix with only the y rotation of the device rotation
  81992. rotation.toEulerAnglesToRef(this._workingVector);
  81993. this._workingVector.z = 0;
  81994. this._workingVector.x = 0;
  81995. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  81996. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  81997. // Rotate backwards ray by device rotation to cast at the ground behind the user
  81998. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  81999. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  82000. var ray = new BABYLON.Ray(position, this._workingVector);
  82001. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  82002. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  82003. this._teleportCamera(hit.pickedPoint);
  82004. }
  82005. gazer._teleportationBackRequestInitiated = true;
  82006. }
  82007. }
  82008. else {
  82009. gazer._teleportationBackRequestInitiated = false;
  82010. }
  82011. };
  82012. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  82013. var _this = this;
  82014. var controllerMesh = controller.webVRController.mesh;
  82015. if (controllerMesh) {
  82016. if (!controller._interactionsEnabled) {
  82017. this._enableInteractionOnController(controller);
  82018. }
  82019. controller._interactionsEnabled = true;
  82020. controller._teleportationEnabled = true;
  82021. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82022. controller._dpadPressed = false;
  82023. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  82024. controller._dpadPressed = stateObject.pressed;
  82025. if (!controller._dpadPressed) {
  82026. _this._rotationLeftAsked = false;
  82027. _this._rotationRightAsked = false;
  82028. controller._teleportationBackRequestInitiated = false;
  82029. }
  82030. });
  82031. }
  82032. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  82033. if (_this.teleportationEnabled) {
  82034. _this._checkTeleportBackwards(stateObject, controller);
  82035. _this._checkTeleportWithRay(stateObject, controller);
  82036. }
  82037. _this._checkRotate(stateObject, controller);
  82038. });
  82039. }
  82040. };
  82041. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  82042. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  82043. this._teleportationTarget.isPickable = false;
  82044. var length = 512;
  82045. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  82046. dynamicTexture.hasAlpha = true;
  82047. var context = dynamicTexture.getContext();
  82048. var centerX = length / 2;
  82049. var centerY = length / 2;
  82050. var radius = 200;
  82051. context.beginPath();
  82052. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  82053. context.fillStyle = this._teleportationFillColor;
  82054. context.fill();
  82055. context.lineWidth = 10;
  82056. context.strokeStyle = this._teleportationBorderColor;
  82057. context.stroke();
  82058. context.closePath();
  82059. dynamicTexture.update();
  82060. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  82061. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  82062. this._teleportationTarget.material = teleportationCircleMaterial;
  82063. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  82064. torus.isPickable = false;
  82065. torus.parent = this._teleportationTarget;
  82066. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82067. var keys = [];
  82068. keys.push({
  82069. frame: 0,
  82070. value: 0
  82071. });
  82072. keys.push({
  82073. frame: 30,
  82074. value: 0.4
  82075. });
  82076. keys.push({
  82077. frame: 60,
  82078. value: 0
  82079. });
  82080. animationInnerCircle.setKeys(keys);
  82081. var easingFunction = new BABYLON.SineEase();
  82082. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82083. animationInnerCircle.setEasingFunction(easingFunction);
  82084. torus.animations = [];
  82085. torus.animations.push(animationInnerCircle);
  82086. this._scene.beginAnimation(torus, 0, 60, true);
  82087. this._hideTeleportationTarget();
  82088. };
  82089. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  82090. this._teleportActive = true;
  82091. if (this._teleportationInitialized) {
  82092. this._teleportationTarget.isVisible = true;
  82093. if (this._isDefaultTeleportationTarget) {
  82094. this._teleportationTarget.getChildren()[0].isVisible = true;
  82095. }
  82096. }
  82097. };
  82098. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  82099. this._teleportActive = false;
  82100. if (this._teleportationInitialized) {
  82101. this._teleportationTarget.isVisible = false;
  82102. if (this._isDefaultTeleportationTarget) {
  82103. this._teleportationTarget.getChildren()[0].isVisible = false;
  82104. }
  82105. }
  82106. };
  82107. VRExperienceHelper.prototype._rotateCamera = function (right) {
  82108. var _this = this;
  82109. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82110. return;
  82111. }
  82112. if (right) {
  82113. this._rotationAngle++;
  82114. }
  82115. else {
  82116. this._rotationAngle--;
  82117. }
  82118. this.currentVRCamera.animations = [];
  82119. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  82120. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82121. var animationRotationKeys = [];
  82122. animationRotationKeys.push({
  82123. frame: 0,
  82124. value: this.currentVRCamera.rotationQuaternion
  82125. });
  82126. animationRotationKeys.push({
  82127. frame: 6,
  82128. value: target
  82129. });
  82130. animationRotation.setKeys(animationRotationKeys);
  82131. animationRotation.setEasingFunction(this._circleEase);
  82132. this.currentVRCamera.animations.push(animationRotation);
  82133. this._postProcessMove.animations = [];
  82134. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82135. var vignetteWeightKeys = [];
  82136. vignetteWeightKeys.push({
  82137. frame: 0,
  82138. value: 0
  82139. });
  82140. vignetteWeightKeys.push({
  82141. frame: 3,
  82142. value: 4
  82143. });
  82144. vignetteWeightKeys.push({
  82145. frame: 6,
  82146. value: 0
  82147. });
  82148. animationPP.setKeys(vignetteWeightKeys);
  82149. animationPP.setEasingFunction(this._circleEase);
  82150. this._postProcessMove.animations.push(animationPP);
  82151. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82152. var vignetteStretchKeys = [];
  82153. vignetteStretchKeys.push({
  82154. frame: 0,
  82155. value: 0
  82156. });
  82157. vignetteStretchKeys.push({
  82158. frame: 3,
  82159. value: 10
  82160. });
  82161. vignetteStretchKeys.push({
  82162. frame: 6,
  82163. value: 0
  82164. });
  82165. animationPP2.setKeys(vignetteStretchKeys);
  82166. animationPP2.setEasingFunction(this._circleEase);
  82167. this._postProcessMove.animations.push(animationPP2);
  82168. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82169. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82170. this._postProcessMove.samples = 4;
  82171. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82172. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  82173. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82174. });
  82175. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  82176. };
  82177. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  82178. if (hit.pickedPoint) {
  82179. if (gazer._teleportationRequestInitiated) {
  82180. this._displayTeleportationTarget();
  82181. this._haloCenter.copyFrom(hit.pickedPoint);
  82182. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  82183. }
  82184. var pickNormal = hit.getNormal(true, false);
  82185. if (pickNormal) {
  82186. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82187. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82188. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  82189. }
  82190. this._teleportationTarget.position.y += 0.1;
  82191. }
  82192. };
  82193. VRExperienceHelper.prototype._teleportCamera = function (location) {
  82194. var _this = this;
  82195. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82196. return;
  82197. }
  82198. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  82199. // offset of the headset from the anchor.
  82200. if (this.webVRCamera.leftCamera) {
  82201. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  82202. this._workingVector.subtractInPlace(this.webVRCamera.position);
  82203. location.subtractToRef(this._workingVector, this._workingVector);
  82204. }
  82205. else {
  82206. this._workingVector.copyFrom(location);
  82207. }
  82208. // Add height to account for user's height offset
  82209. if (this.isInVRMode) {
  82210. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  82211. }
  82212. else {
  82213. this._workingVector.y += this._defaultHeight;
  82214. }
  82215. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  82216. // Create animation from the camera's position to the new location
  82217. this.currentVRCamera.animations = [];
  82218. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82219. var animationCameraTeleportationKeys = [{
  82220. frame: 0,
  82221. value: this.currentVRCamera.position
  82222. },
  82223. {
  82224. frame: 11,
  82225. value: this._workingVector
  82226. }
  82227. ];
  82228. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  82229. animationCameraTeleportation.setEasingFunction(this._circleEase);
  82230. this.currentVRCamera.animations.push(animationCameraTeleportation);
  82231. this._postProcessMove.animations = [];
  82232. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82233. var vignetteWeightKeys = [];
  82234. vignetteWeightKeys.push({
  82235. frame: 0,
  82236. value: 0
  82237. });
  82238. vignetteWeightKeys.push({
  82239. frame: 5,
  82240. value: 8
  82241. });
  82242. vignetteWeightKeys.push({
  82243. frame: 11,
  82244. value: 0
  82245. });
  82246. animationPP.setKeys(vignetteWeightKeys);
  82247. this._postProcessMove.animations.push(animationPP);
  82248. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82249. var vignetteStretchKeys = [];
  82250. vignetteStretchKeys.push({
  82251. frame: 0,
  82252. value: 0
  82253. });
  82254. vignetteStretchKeys.push({
  82255. frame: 5,
  82256. value: 10
  82257. });
  82258. vignetteStretchKeys.push({
  82259. frame: 11,
  82260. value: 0
  82261. });
  82262. animationPP2.setKeys(vignetteStretchKeys);
  82263. this._postProcessMove.animations.push(animationPP2);
  82264. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82265. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82266. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82267. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  82268. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82269. });
  82270. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  82271. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  82272. });
  82273. this._hideTeleportationTarget();
  82274. };
  82275. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  82276. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82277. return;
  82278. }
  82279. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  82280. // Moving the gazeTracker on the mesh face targetted
  82281. if (hit && hit.pickedPoint) {
  82282. if (this._displayGaze) {
  82283. var multiplier = 1;
  82284. gazer._gazeTracker.isVisible = true;
  82285. if (gazer._isActionableMesh) {
  82286. multiplier = 3;
  82287. }
  82288. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  82289. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  82290. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  82291. var pickNormal = hit.getNormal();
  82292. // To avoid z-fighting
  82293. var deltaFighting = 0.002;
  82294. if (pickNormal) {
  82295. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82296. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82297. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  82298. }
  82299. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  82300. if (gazer._gazeTracker.position.x < 0) {
  82301. gazer._gazeTracker.position.x += deltaFighting;
  82302. }
  82303. else {
  82304. gazer._gazeTracker.position.x -= deltaFighting;
  82305. }
  82306. if (gazer._gazeTracker.position.y < 0) {
  82307. gazer._gazeTracker.position.y += deltaFighting;
  82308. }
  82309. else {
  82310. gazer._gazeTracker.position.y -= deltaFighting;
  82311. }
  82312. if (gazer._gazeTracker.position.z < 0) {
  82313. gazer._gazeTracker.position.z += deltaFighting;
  82314. }
  82315. else {
  82316. gazer._gazeTracker.position.z -= deltaFighting;
  82317. }
  82318. }
  82319. // Changing the size of the laser pointer based on the distance from the targetted point
  82320. gazer._updatePointerDistance(hit.distance);
  82321. }
  82322. else {
  82323. gazer._gazeTracker.isVisible = false;
  82324. }
  82325. if (hit && hit.pickedMesh) {
  82326. gazer._currentHit = hit;
  82327. if (gazer._pointerDownOnMeshAsked) {
  82328. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  82329. }
  82330. // The object selected is the floor, we're in a teleportation scenario
  82331. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  82332. // Moving the teleportation area to this targetted point
  82333. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  82334. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  82335. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82336. }
  82337. gazer._currentMeshSelected = null;
  82338. if (gazer._teleportationRequestInitiated) {
  82339. this._moveTeleportationSelectorTo(hit, gazer);
  82340. }
  82341. return;
  82342. }
  82343. // If not, we're in a selection scenario
  82344. //this._teleportationAllowed = false;
  82345. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  82346. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  82347. this.onNewMeshPicked.notifyObservers(hit);
  82348. gazer._currentMeshSelected = hit.pickedMesh;
  82349. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  82350. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  82351. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  82352. gazer._isActionableMesh = true;
  82353. }
  82354. else {
  82355. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82356. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82357. gazer._isActionableMesh = false;
  82358. }
  82359. try {
  82360. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  82361. }
  82362. catch (err) {
  82363. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  82364. }
  82365. }
  82366. else {
  82367. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82368. gazer._currentMeshSelected = null;
  82369. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82370. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82371. }
  82372. }
  82373. }
  82374. else {
  82375. gazer._currentHit = null;
  82376. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82377. gazer._currentMeshSelected = null;
  82378. //this._teleportationAllowed = false;
  82379. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82380. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82381. }
  82382. };
  82383. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  82384. if (mesh) {
  82385. this.onSelectedMeshUnselected.notifyObservers(mesh);
  82386. }
  82387. };
  82388. /**
  82389. * Sets the color of the laser ray from the vr controllers.
  82390. * @param color new color for the ray.
  82391. */
  82392. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  82393. if (this.leftController) {
  82394. this.leftController._setLaserPointerColor(color);
  82395. }
  82396. if (this.rightController) {
  82397. this.rightController._setLaserPointerColor(color);
  82398. }
  82399. };
  82400. /**
  82401. * Sets the color of the ray from the vr headsets gaze.
  82402. * @param color new color for the ray.
  82403. */
  82404. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  82405. if (!this._cameraGazer._gazeTracker.material) {
  82406. return;
  82407. }
  82408. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  82409. if (this.leftController) {
  82410. this.leftController._gazeTracker.material.emissiveColor = color;
  82411. }
  82412. if (this.rightController) {
  82413. this.rightController._gazeTracker.material.emissiveColor = color;
  82414. }
  82415. };
  82416. /**
  82417. * Exits VR and disposes of the vr experience helper
  82418. */
  82419. VRExperienceHelper.prototype.dispose = function () {
  82420. if (this.isInVRMode) {
  82421. this.exitVR();
  82422. }
  82423. if (this._postProcessMove) {
  82424. this._postProcessMove.dispose();
  82425. }
  82426. if (this._webVRCamera) {
  82427. this._webVRCamera.dispose();
  82428. }
  82429. if (this._vrDeviceOrientationCamera) {
  82430. this._vrDeviceOrientationCamera.dispose();
  82431. }
  82432. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  82433. document.body.removeChild(this._btnVR);
  82434. }
  82435. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  82436. this._deviceOrientationCamera.dispose();
  82437. }
  82438. if (this._cameraGazer) {
  82439. this._cameraGazer.dispose();
  82440. }
  82441. if (this.leftController) {
  82442. this.leftController.dispose();
  82443. }
  82444. if (this.rightController) {
  82445. this.rightController.dispose();
  82446. }
  82447. if (this._teleportationTarget) {
  82448. this._teleportationTarget.dispose();
  82449. }
  82450. this._floorMeshesCollection = [];
  82451. document.removeEventListener("keydown", this._onKeyDown);
  82452. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82453. window.removeEventListener("resize", this._onResize);
  82454. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  82455. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  82456. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  82457. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  82458. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  82459. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  82460. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  82461. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82462. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  82463. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  82464. this._scene.unregisterBeforeRender(this.beforeRender);
  82465. };
  82466. /**
  82467. * Gets the name of the VRExperienceHelper class
  82468. * @returns "VRExperienceHelper"
  82469. */
  82470. VRExperienceHelper.prototype.getClassName = function () {
  82471. return "VRExperienceHelper";
  82472. };
  82473. return VRExperienceHelper;
  82474. }());
  82475. BABYLON.VRExperienceHelper = VRExperienceHelper;
  82476. })(BABYLON || (BABYLON = {}));
  82477. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  82478. // Mainly based on these 2 articles :
  82479. // 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
  82480. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  82481. var BABYLON;
  82482. (function (BABYLON) {
  82483. var JoystickAxis;
  82484. (function (JoystickAxis) {
  82485. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  82486. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  82487. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  82488. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  82489. var VirtualJoystick = /** @class */ (function () {
  82490. function VirtualJoystick(leftJoystick) {
  82491. var _this = this;
  82492. if (leftJoystick) {
  82493. this._leftJoystick = true;
  82494. }
  82495. else {
  82496. this._leftJoystick = false;
  82497. }
  82498. VirtualJoystick._globalJoystickIndex++;
  82499. // By default left & right arrow keys are moving the X
  82500. // and up & down keys are moving the Y
  82501. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82502. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82503. this.reverseLeftRight = false;
  82504. this.reverseUpDown = false;
  82505. // collections of pointers
  82506. this._touches = new BABYLON.StringDictionary();
  82507. this.deltaPosition = BABYLON.Vector3.Zero();
  82508. this._joystickSensibility = 25;
  82509. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82510. this._onResize = function (evt) {
  82511. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82512. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82513. if (VirtualJoystick.vjCanvas) {
  82514. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  82515. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  82516. }
  82517. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  82518. };
  82519. // injecting a canvas element on top of the canvas 3D game
  82520. if (!VirtualJoystick.vjCanvas) {
  82521. window.addEventListener("resize", this._onResize, false);
  82522. VirtualJoystick.vjCanvas = document.createElement("canvas");
  82523. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82524. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82525. VirtualJoystick.vjCanvas.width = window.innerWidth;
  82526. VirtualJoystick.vjCanvas.height = window.innerHeight;
  82527. VirtualJoystick.vjCanvas.style.width = "100%";
  82528. VirtualJoystick.vjCanvas.style.height = "100%";
  82529. VirtualJoystick.vjCanvas.style.position = "absolute";
  82530. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  82531. VirtualJoystick.vjCanvas.style.top = "0px";
  82532. VirtualJoystick.vjCanvas.style.left = "0px";
  82533. VirtualJoystick.vjCanvas.style.zIndex = "5";
  82534. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  82535. // Support for jQuery PEP polyfill
  82536. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  82537. var context = VirtualJoystick.vjCanvas.getContext('2d');
  82538. if (!context) {
  82539. throw new Error("Unable to create canvas for virtual joystick");
  82540. }
  82541. VirtualJoystick.vjCanvasContext = context;
  82542. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  82543. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82544. document.body.appendChild(VirtualJoystick.vjCanvas);
  82545. }
  82546. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  82547. this.pressed = false;
  82548. // default joystick color
  82549. this._joystickColor = "cyan";
  82550. this._joystickPointerID = -1;
  82551. // current joystick position
  82552. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  82553. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  82554. // origin joystick position
  82555. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  82556. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  82557. this._onPointerDownHandlerRef = function (evt) {
  82558. _this._onPointerDown(evt);
  82559. };
  82560. this._onPointerMoveHandlerRef = function (evt) {
  82561. _this._onPointerMove(evt);
  82562. };
  82563. this._onPointerUpHandlerRef = function (evt) {
  82564. _this._onPointerUp(evt);
  82565. };
  82566. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  82567. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  82568. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  82569. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  82570. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  82571. evt.preventDefault(); // Disables system menu
  82572. }, false);
  82573. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82574. }
  82575. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  82576. this._joystickSensibility = newJoystickSensibility;
  82577. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82578. };
  82579. VirtualJoystick.prototype._onPointerDown = function (e) {
  82580. var positionOnScreenCondition;
  82581. e.preventDefault();
  82582. if (this._leftJoystick === true) {
  82583. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  82584. }
  82585. else {
  82586. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  82587. }
  82588. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  82589. // First contact will be dedicated to the virtual joystick
  82590. this._joystickPointerID = e.pointerId;
  82591. this._joystickPointerStartPos.x = e.clientX;
  82592. this._joystickPointerStartPos.y = e.clientY;
  82593. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  82594. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  82595. this._deltaJoystickVector.x = 0;
  82596. this._deltaJoystickVector.y = 0;
  82597. this.pressed = true;
  82598. this._touches.add(e.pointerId.toString(), e);
  82599. }
  82600. else {
  82601. // You can only trigger the action buttons with a joystick declared
  82602. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  82603. this._action();
  82604. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  82605. }
  82606. }
  82607. };
  82608. VirtualJoystick.prototype._onPointerMove = function (e) {
  82609. // If the current pointer is the one associated to the joystick (first touch contact)
  82610. if (this._joystickPointerID == e.pointerId) {
  82611. this._joystickPointerPos.x = e.clientX;
  82612. this._joystickPointerPos.y = e.clientY;
  82613. this._deltaJoystickVector = this._joystickPointerPos.clone();
  82614. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  82615. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  82616. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  82617. switch (this._axisTargetedByLeftAndRight) {
  82618. case JoystickAxis.X:
  82619. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  82620. break;
  82621. case JoystickAxis.Y:
  82622. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  82623. break;
  82624. case JoystickAxis.Z:
  82625. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  82626. break;
  82627. }
  82628. var directionUpDown = this.reverseUpDown ? 1 : -1;
  82629. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  82630. switch (this._axisTargetedByUpAndDown) {
  82631. case JoystickAxis.X:
  82632. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  82633. break;
  82634. case JoystickAxis.Y:
  82635. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  82636. break;
  82637. case JoystickAxis.Z:
  82638. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  82639. break;
  82640. }
  82641. }
  82642. else {
  82643. var data = this._touches.get(e.pointerId.toString());
  82644. if (data) {
  82645. data.x = e.clientX;
  82646. data.y = e.clientY;
  82647. }
  82648. }
  82649. };
  82650. VirtualJoystick.prototype._onPointerUp = function (e) {
  82651. if (this._joystickPointerID == e.pointerId) {
  82652. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  82653. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  82654. this._joystickPointerID = -1;
  82655. this.pressed = false;
  82656. }
  82657. else {
  82658. var touch = this._touches.get(e.pointerId.toString());
  82659. if (touch) {
  82660. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82661. }
  82662. }
  82663. this._deltaJoystickVector.x = 0;
  82664. this._deltaJoystickVector.y = 0;
  82665. this._touches.remove(e.pointerId.toString());
  82666. };
  82667. /**
  82668. * Change the color of the virtual joystick
  82669. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  82670. */
  82671. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  82672. this._joystickColor = newColor;
  82673. };
  82674. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  82675. this._action = action;
  82676. };
  82677. // Define which axis you'd like to control for left & right
  82678. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  82679. switch (axis) {
  82680. case JoystickAxis.X:
  82681. case JoystickAxis.Y:
  82682. case JoystickAxis.Z:
  82683. this._axisTargetedByLeftAndRight = axis;
  82684. break;
  82685. default:
  82686. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82687. break;
  82688. }
  82689. };
  82690. // Define which axis you'd like to control for up & down
  82691. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  82692. switch (axis) {
  82693. case JoystickAxis.X:
  82694. case JoystickAxis.Y:
  82695. case JoystickAxis.Z:
  82696. this._axisTargetedByUpAndDown = axis;
  82697. break;
  82698. default:
  82699. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82700. break;
  82701. }
  82702. };
  82703. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  82704. var _this = this;
  82705. if (this.pressed) {
  82706. this._touches.forEach(function (key, touch) {
  82707. if (touch.pointerId === _this._joystickPointerID) {
  82708. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  82709. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  82710. VirtualJoystick.vjCanvasContext.beginPath();
  82711. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82712. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82713. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  82714. VirtualJoystick.vjCanvasContext.stroke();
  82715. VirtualJoystick.vjCanvasContext.closePath();
  82716. VirtualJoystick.vjCanvasContext.beginPath();
  82717. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82718. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82719. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  82720. VirtualJoystick.vjCanvasContext.stroke();
  82721. VirtualJoystick.vjCanvasContext.closePath();
  82722. VirtualJoystick.vjCanvasContext.beginPath();
  82723. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82724. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  82725. VirtualJoystick.vjCanvasContext.stroke();
  82726. VirtualJoystick.vjCanvasContext.closePath();
  82727. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  82728. }
  82729. else {
  82730. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82731. VirtualJoystick.vjCanvasContext.beginPath();
  82732. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  82733. VirtualJoystick.vjCanvasContext.beginPath();
  82734. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  82735. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82736. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  82737. VirtualJoystick.vjCanvasContext.stroke();
  82738. VirtualJoystick.vjCanvasContext.closePath();
  82739. touch.prevX = touch.x;
  82740. touch.prevY = touch.y;
  82741. }
  82742. ;
  82743. });
  82744. }
  82745. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82746. };
  82747. VirtualJoystick.prototype.releaseCanvas = function () {
  82748. if (VirtualJoystick.vjCanvas) {
  82749. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  82750. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  82751. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  82752. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  82753. window.removeEventListener("resize", this._onResize);
  82754. document.body.removeChild(VirtualJoystick.vjCanvas);
  82755. VirtualJoystick.vjCanvas = null;
  82756. }
  82757. };
  82758. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  82759. VirtualJoystick._globalJoystickIndex = 0;
  82760. return VirtualJoystick;
  82761. }());
  82762. BABYLON.VirtualJoystick = VirtualJoystick;
  82763. })(BABYLON || (BABYLON = {}));
  82764. //# sourceMappingURL=babylon.virtualJoystick.js.map
  82765. var BABYLON;
  82766. (function (BABYLON) {
  82767. // We're mainly based on the logic defined into the FreeCamera code
  82768. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  82769. __extends(VirtualJoysticksCamera, _super);
  82770. function VirtualJoysticksCamera(name, position, scene) {
  82771. var _this = _super.call(this, name, position, scene) || this;
  82772. _this.inputs.addVirtualJoystick();
  82773. return _this;
  82774. }
  82775. VirtualJoysticksCamera.prototype.getClassName = function () {
  82776. return "VirtualJoysticksCamera";
  82777. };
  82778. return VirtualJoysticksCamera;
  82779. }(BABYLON.FreeCamera));
  82780. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  82781. })(BABYLON || (BABYLON = {}));
  82782. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  82783. var BABYLON;
  82784. (function (BABYLON) {
  82785. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  82786. function FreeCameraVirtualJoystickInput() {
  82787. }
  82788. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  82789. return this._leftjoystick;
  82790. };
  82791. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  82792. return this._rightjoystick;
  82793. };
  82794. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  82795. if (this._leftjoystick) {
  82796. var camera = this.camera;
  82797. var speed = camera._computeLocalCameraSpeed() * 50;
  82798. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  82799. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  82800. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  82801. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  82802. if (!this._leftjoystick.pressed) {
  82803. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  82804. }
  82805. if (!this._rightjoystick.pressed) {
  82806. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  82807. }
  82808. }
  82809. };
  82810. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  82811. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  82812. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  82813. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  82814. this._leftjoystick.setJoystickSensibility(0.15);
  82815. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  82816. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  82817. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  82818. this._rightjoystick.reverseUpDown = true;
  82819. this._rightjoystick.setJoystickSensibility(0.05);
  82820. this._rightjoystick.setJoystickColor("yellow");
  82821. };
  82822. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  82823. this._leftjoystick.releaseCanvas();
  82824. this._rightjoystick.releaseCanvas();
  82825. };
  82826. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  82827. return "FreeCameraVirtualJoystickInput";
  82828. };
  82829. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  82830. return "virtualJoystick";
  82831. };
  82832. return FreeCameraVirtualJoystickInput;
  82833. }());
  82834. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  82835. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  82836. })(BABYLON || (BABYLON = {}));
  82837. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  82838. var BABYLON;
  82839. (function (BABYLON) {
  82840. var SimplificationSettings = /** @class */ (function () {
  82841. function SimplificationSettings(quality, distance, optimizeMesh) {
  82842. this.quality = quality;
  82843. this.distance = distance;
  82844. this.optimizeMesh = optimizeMesh;
  82845. }
  82846. return SimplificationSettings;
  82847. }());
  82848. BABYLON.SimplificationSettings = SimplificationSettings;
  82849. var SimplificationQueue = /** @class */ (function () {
  82850. function SimplificationQueue() {
  82851. this.running = false;
  82852. this._simplificationArray = [];
  82853. }
  82854. SimplificationQueue.prototype.addTask = function (task) {
  82855. this._simplificationArray.push(task);
  82856. };
  82857. SimplificationQueue.prototype.executeNext = function () {
  82858. var task = this._simplificationArray.pop();
  82859. if (task) {
  82860. this.running = true;
  82861. this.runSimplification(task);
  82862. }
  82863. else {
  82864. this.running = false;
  82865. }
  82866. };
  82867. SimplificationQueue.prototype.runSimplification = function (task) {
  82868. var _this = this;
  82869. if (task.parallelProcessing) {
  82870. //parallel simplifier
  82871. task.settings.forEach(function (setting) {
  82872. var simplifier = _this.getSimplifier(task);
  82873. simplifier.simplify(setting, function (newMesh) {
  82874. task.mesh.addLODLevel(setting.distance, newMesh);
  82875. newMesh.isVisible = true;
  82876. //check if it is the last
  82877. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  82878. //all done, run the success callback.
  82879. task.successCallback();
  82880. }
  82881. _this.executeNext();
  82882. });
  82883. });
  82884. }
  82885. else {
  82886. //single simplifier.
  82887. var simplifier = this.getSimplifier(task);
  82888. var runDecimation = function (setting, callback) {
  82889. simplifier.simplify(setting, function (newMesh) {
  82890. task.mesh.addLODLevel(setting.distance, newMesh);
  82891. newMesh.isVisible = true;
  82892. //run the next quality level
  82893. callback();
  82894. });
  82895. };
  82896. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  82897. runDecimation(task.settings[loop.index], function () {
  82898. loop.executeNext();
  82899. });
  82900. }, function () {
  82901. //execution ended, run the success callback.
  82902. if (task.successCallback) {
  82903. task.successCallback();
  82904. }
  82905. _this.executeNext();
  82906. });
  82907. }
  82908. };
  82909. SimplificationQueue.prototype.getSimplifier = function (task) {
  82910. switch (task.simplificationType) {
  82911. case SimplificationType.QUADRATIC:
  82912. default:
  82913. return new QuadraticErrorSimplification(task.mesh);
  82914. }
  82915. };
  82916. return SimplificationQueue;
  82917. }());
  82918. BABYLON.SimplificationQueue = SimplificationQueue;
  82919. /**
  82920. * The implemented types of simplification.
  82921. * At the moment only Quadratic Error Decimation is implemented.
  82922. */
  82923. var SimplificationType;
  82924. (function (SimplificationType) {
  82925. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  82926. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  82927. var DecimationTriangle = /** @class */ (function () {
  82928. function DecimationTriangle(vertices) {
  82929. this.vertices = vertices;
  82930. this.error = new Array(4);
  82931. this.deleted = false;
  82932. this.isDirty = false;
  82933. this.deletePending = false;
  82934. this.borderFactor = 0;
  82935. }
  82936. return DecimationTriangle;
  82937. }());
  82938. BABYLON.DecimationTriangle = DecimationTriangle;
  82939. var DecimationVertex = /** @class */ (function () {
  82940. function DecimationVertex(position, id) {
  82941. this.position = position;
  82942. this.id = id;
  82943. this.isBorder = true;
  82944. this.q = new QuadraticMatrix();
  82945. this.triangleCount = 0;
  82946. this.triangleStart = 0;
  82947. this.originalOffsets = [];
  82948. }
  82949. DecimationVertex.prototype.updatePosition = function (newPosition) {
  82950. this.position.copyFrom(newPosition);
  82951. };
  82952. return DecimationVertex;
  82953. }());
  82954. BABYLON.DecimationVertex = DecimationVertex;
  82955. var QuadraticMatrix = /** @class */ (function () {
  82956. function QuadraticMatrix(data) {
  82957. this.data = new Array(10);
  82958. for (var i = 0; i < 10; ++i) {
  82959. if (data && data[i]) {
  82960. this.data[i] = data[i];
  82961. }
  82962. else {
  82963. this.data[i] = 0;
  82964. }
  82965. }
  82966. }
  82967. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  82968. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  82969. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  82970. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  82971. return det;
  82972. };
  82973. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  82974. for (var i = 0; i < 10; ++i) {
  82975. this.data[i] += matrix.data[i];
  82976. }
  82977. };
  82978. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  82979. for (var i = 0; i < 10; ++i) {
  82980. this.data[i] += data[i];
  82981. }
  82982. };
  82983. QuadraticMatrix.prototype.add = function (matrix) {
  82984. var m = new QuadraticMatrix();
  82985. for (var i = 0; i < 10; ++i) {
  82986. m.data[i] = this.data[i] + matrix.data[i];
  82987. }
  82988. return m;
  82989. };
  82990. QuadraticMatrix.FromData = function (a, b, c, d) {
  82991. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  82992. };
  82993. //returning an array to avoid garbage collection
  82994. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  82995. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82996. };
  82997. return QuadraticMatrix;
  82998. }());
  82999. BABYLON.QuadraticMatrix = QuadraticMatrix;
  83000. var Reference = /** @class */ (function () {
  83001. function Reference(vertexId, triangleId) {
  83002. this.vertexId = vertexId;
  83003. this.triangleId = triangleId;
  83004. }
  83005. return Reference;
  83006. }());
  83007. BABYLON.Reference = Reference;
  83008. /**
  83009. * An implementation of the Quadratic Error simplification algorithm.
  83010. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  83011. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  83012. * @author RaananW
  83013. */
  83014. var QuadraticErrorSimplification = /** @class */ (function () {
  83015. function QuadraticErrorSimplification(_mesh) {
  83016. this._mesh = _mesh;
  83017. this.syncIterations = 5000;
  83018. this.aggressiveness = 7;
  83019. this.decimationIterations = 100;
  83020. this.boundingBoxEpsilon = BABYLON.Epsilon;
  83021. }
  83022. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  83023. var _this = this;
  83024. this.initDecimatedMesh();
  83025. //iterating through the submeshes array, one after the other.
  83026. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  83027. _this.initWithMesh(loop.index, function () {
  83028. _this.runDecimation(settings, loop.index, function () {
  83029. loop.executeNext();
  83030. });
  83031. }, settings.optimizeMesh);
  83032. }, function () {
  83033. setTimeout(function () {
  83034. successCallback(_this._reconstructedMesh);
  83035. }, 0);
  83036. });
  83037. };
  83038. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  83039. var _this = this;
  83040. var targetCount = ~~(this.triangles.length * settings.quality);
  83041. var deletedTriangles = 0;
  83042. var triangleCount = this.triangles.length;
  83043. var iterationFunction = function (iteration, callback) {
  83044. setTimeout(function () {
  83045. if (iteration % 5 === 0) {
  83046. _this.updateMesh(iteration === 0);
  83047. }
  83048. for (var i = 0; i < _this.triangles.length; ++i) {
  83049. _this.triangles[i].isDirty = false;
  83050. }
  83051. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  83052. var trianglesIterator = function (i) {
  83053. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  83054. var t = _this.triangles[tIdx];
  83055. if (!t)
  83056. return;
  83057. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  83058. return;
  83059. }
  83060. for (var j = 0; j < 3; ++j) {
  83061. if (t.error[j] < threshold) {
  83062. var deleted0 = [];
  83063. var deleted1 = [];
  83064. var v0 = t.vertices[j];
  83065. var v1 = t.vertices[(j + 1) % 3];
  83066. if (v0.isBorder || v1.isBorder)
  83067. continue;
  83068. var p = BABYLON.Vector3.Zero();
  83069. var n = BABYLON.Vector3.Zero();
  83070. var uv = BABYLON.Vector2.Zero();
  83071. var color = new BABYLON.Color4(0, 0, 0, 1);
  83072. _this.calculateError(v0, v1, p, n, uv, color);
  83073. var delTr = new Array();
  83074. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  83075. continue;
  83076. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  83077. continue;
  83078. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  83079. continue;
  83080. var uniqueArray = new Array();
  83081. delTr.forEach(function (deletedT) {
  83082. if (uniqueArray.indexOf(deletedT) === -1) {
  83083. deletedT.deletePending = true;
  83084. uniqueArray.push(deletedT);
  83085. }
  83086. });
  83087. if (uniqueArray.length % 2 !== 0) {
  83088. continue;
  83089. }
  83090. v0.q = v1.q.add(v0.q);
  83091. v0.updatePosition(p);
  83092. var tStart = _this.references.length;
  83093. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  83094. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  83095. var tCount = _this.references.length - tStart;
  83096. if (tCount <= v0.triangleCount) {
  83097. if (tCount) {
  83098. for (var c = 0; c < tCount; c++) {
  83099. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  83100. }
  83101. }
  83102. }
  83103. else {
  83104. v0.triangleStart = tStart;
  83105. }
  83106. v0.triangleCount = tCount;
  83107. break;
  83108. }
  83109. }
  83110. };
  83111. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  83112. }, 0);
  83113. };
  83114. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  83115. if (triangleCount - deletedTriangles <= targetCount)
  83116. loop.breakLoop();
  83117. else {
  83118. iterationFunction(loop.index, function () {
  83119. loop.executeNext();
  83120. });
  83121. }
  83122. }, function () {
  83123. setTimeout(function () {
  83124. //reconstruct this part of the mesh
  83125. _this.reconstructMesh(submeshIndex);
  83126. successCallback();
  83127. }, 0);
  83128. });
  83129. };
  83130. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  83131. var _this = this;
  83132. this.vertices = [];
  83133. this.triangles = [];
  83134. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83135. var indices = this._mesh.getIndices();
  83136. var submesh = this._mesh.subMeshes[submeshIndex];
  83137. var findInVertices = function (positionToSearch) {
  83138. if (optimizeMesh) {
  83139. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  83140. if (_this.vertices[ii].position.equals(positionToSearch)) {
  83141. return _this.vertices[ii];
  83142. }
  83143. }
  83144. }
  83145. return null;
  83146. };
  83147. var vertexReferences = [];
  83148. var vertexInit = function (i) {
  83149. if (!positionData) {
  83150. return;
  83151. }
  83152. var offset = i + submesh.verticesStart;
  83153. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  83154. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  83155. vertex.originalOffsets.push(offset);
  83156. if (vertex.id === _this.vertices.length) {
  83157. _this.vertices.push(vertex);
  83158. }
  83159. vertexReferences.push(vertex.id);
  83160. };
  83161. //var totalVertices = mesh.getTotalVertices();
  83162. var totalVertices = submesh.verticesCount;
  83163. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  83164. var indicesInit = function (i) {
  83165. if (!indices) {
  83166. return;
  83167. }
  83168. var offset = (submesh.indexStart / 3) + i;
  83169. var pos = (offset * 3);
  83170. var i0 = indices[pos + 0];
  83171. var i1 = indices[pos + 1];
  83172. var i2 = indices[pos + 2];
  83173. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  83174. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  83175. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  83176. var triangle = new DecimationTriangle([v0, v1, v2]);
  83177. triangle.originalOffset = pos;
  83178. _this.triangles.push(triangle);
  83179. };
  83180. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  83181. _this.init(callback);
  83182. });
  83183. });
  83184. };
  83185. QuadraticErrorSimplification.prototype.init = function (callback) {
  83186. var _this = this;
  83187. var triangleInit1 = function (i) {
  83188. var t = _this.triangles[i];
  83189. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  83190. for (var j = 0; j < 3; j++) {
  83191. 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))));
  83192. }
  83193. };
  83194. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  83195. var triangleInit2 = function (i) {
  83196. var t = _this.triangles[i];
  83197. for (var j = 0; j < 3; ++j) {
  83198. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  83199. }
  83200. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83201. };
  83202. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  83203. callback();
  83204. });
  83205. });
  83206. };
  83207. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  83208. var newTriangles = [];
  83209. var i;
  83210. for (i = 0; i < this.vertices.length; ++i) {
  83211. this.vertices[i].triangleCount = 0;
  83212. }
  83213. var t;
  83214. var j;
  83215. for (i = 0; i < this.triangles.length; ++i) {
  83216. if (!this.triangles[i].deleted) {
  83217. t = this.triangles[i];
  83218. for (j = 0; j < 3; ++j) {
  83219. t.vertices[j].triangleCount = 1;
  83220. }
  83221. newTriangles.push(t);
  83222. }
  83223. }
  83224. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  83225. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  83226. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  83227. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  83228. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  83229. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83230. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  83231. var vertexCount = 0;
  83232. for (i = 0; i < this.vertices.length; ++i) {
  83233. var vertex = this.vertices[i];
  83234. vertex.id = vertexCount;
  83235. if (vertex.triangleCount) {
  83236. vertex.originalOffsets.forEach(function (originalOffset) {
  83237. if (!normalData) {
  83238. return;
  83239. }
  83240. newPositionData.push(vertex.position.x);
  83241. newPositionData.push(vertex.position.y);
  83242. newPositionData.push(vertex.position.z);
  83243. newNormalData.push(normalData[originalOffset * 3]);
  83244. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  83245. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  83246. if (uvs && uvs.length) {
  83247. newUVsData.push(uvs[(originalOffset * 2)]);
  83248. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  83249. }
  83250. else if (colorsData && colorsData.length) {
  83251. newColorsData.push(colorsData[(originalOffset * 4)]);
  83252. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  83253. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  83254. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  83255. }
  83256. ++vertexCount;
  83257. });
  83258. }
  83259. }
  83260. var startingIndex = this._reconstructedMesh.getTotalIndices();
  83261. var startingVertex = this._reconstructedMesh.getTotalVertices();
  83262. var submeshesArray = this._reconstructedMesh.subMeshes;
  83263. this._reconstructedMesh.subMeshes = [];
  83264. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  83265. var originalIndices = this._mesh.getIndices();
  83266. for (i = 0; i < newTriangles.length; ++i) {
  83267. t = newTriangles[i]; //now get the new referencing point for each vertex
  83268. [0, 1, 2].forEach(function (idx) {
  83269. var id = originalIndices[t.originalOffset + idx];
  83270. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  83271. if (offset < 0)
  83272. offset = 0;
  83273. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  83274. });
  83275. }
  83276. //overwriting the old vertex buffers and indices.
  83277. this._reconstructedMesh.setIndices(newIndicesArray);
  83278. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  83279. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  83280. if (newUVsData.length > 0)
  83281. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  83282. if (newColorsData.length > 0)
  83283. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  83284. //create submesh
  83285. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  83286. if (submeshIndex > 0) {
  83287. this._reconstructedMesh.subMeshes = [];
  83288. submeshesArray.forEach(function (submesh) {
  83289. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  83290. });
  83291. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  83292. }
  83293. };
  83294. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  83295. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  83296. this._reconstructedMesh.material = this._mesh.material;
  83297. this._reconstructedMesh.parent = this._mesh.parent;
  83298. this._reconstructedMesh.isVisible = false;
  83299. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  83300. };
  83301. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  83302. for (var i = 0; i < vertex1.triangleCount; ++i) {
  83303. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  83304. if (t.deleted)
  83305. continue;
  83306. var s = this.references[vertex1.triangleStart + i].vertexId;
  83307. var v1 = t.vertices[(s + 1) % 3];
  83308. var v2 = t.vertices[(s + 2) % 3];
  83309. if ((v1 === vertex2 || v2 === vertex2)) {
  83310. deletedArray[i] = true;
  83311. delTr.push(t);
  83312. continue;
  83313. }
  83314. var d1 = v1.position.subtract(point);
  83315. d1 = d1.normalize();
  83316. var d2 = v2.position.subtract(point);
  83317. d2 = d2.normalize();
  83318. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  83319. return true;
  83320. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  83321. deletedArray[i] = false;
  83322. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  83323. return true;
  83324. }
  83325. return false;
  83326. };
  83327. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  83328. var newDeleted = deletedTriangles;
  83329. for (var i = 0; i < vertex.triangleCount; ++i) {
  83330. var ref = this.references[vertex.triangleStart + i];
  83331. var t = this.triangles[ref.triangleId];
  83332. if (t.deleted)
  83333. continue;
  83334. if (deletedArray[i] && t.deletePending) {
  83335. t.deleted = true;
  83336. newDeleted++;
  83337. continue;
  83338. }
  83339. t.vertices[ref.vertexId] = origVertex;
  83340. t.isDirty = true;
  83341. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  83342. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  83343. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  83344. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83345. this.references.push(ref);
  83346. }
  83347. return newDeleted;
  83348. };
  83349. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  83350. for (var i = 0; i < this.vertices.length; ++i) {
  83351. var vCount = [];
  83352. var vId = [];
  83353. var v = this.vertices[i];
  83354. var j;
  83355. for (j = 0; j < v.triangleCount; ++j) {
  83356. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  83357. for (var ii = 0; ii < 3; ii++) {
  83358. var ofs = 0;
  83359. var vv = triangle.vertices[ii];
  83360. while (ofs < vCount.length) {
  83361. if (vId[ofs] === vv.id)
  83362. break;
  83363. ++ofs;
  83364. }
  83365. if (ofs === vCount.length) {
  83366. vCount.push(1);
  83367. vId.push(vv.id);
  83368. }
  83369. else {
  83370. vCount[ofs]++;
  83371. }
  83372. }
  83373. }
  83374. for (j = 0; j < vCount.length; ++j) {
  83375. if (vCount[j] === 1) {
  83376. this.vertices[vId[j]].isBorder = true;
  83377. }
  83378. else {
  83379. this.vertices[vId[j]].isBorder = false;
  83380. }
  83381. }
  83382. }
  83383. };
  83384. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  83385. if (identifyBorders === void 0) { identifyBorders = false; }
  83386. var i;
  83387. if (!identifyBorders) {
  83388. var newTrianglesVector = [];
  83389. for (i = 0; i < this.triangles.length; ++i) {
  83390. if (!this.triangles[i].deleted) {
  83391. newTrianglesVector.push(this.triangles[i]);
  83392. }
  83393. }
  83394. this.triangles = newTrianglesVector;
  83395. }
  83396. for (i = 0; i < this.vertices.length; ++i) {
  83397. this.vertices[i].triangleCount = 0;
  83398. this.vertices[i].triangleStart = 0;
  83399. }
  83400. var t;
  83401. var j;
  83402. var v;
  83403. for (i = 0; i < this.triangles.length; ++i) {
  83404. t = this.triangles[i];
  83405. for (j = 0; j < 3; ++j) {
  83406. v = t.vertices[j];
  83407. v.triangleCount++;
  83408. }
  83409. }
  83410. var tStart = 0;
  83411. for (i = 0; i < this.vertices.length; ++i) {
  83412. this.vertices[i].triangleStart = tStart;
  83413. tStart += this.vertices[i].triangleCount;
  83414. this.vertices[i].triangleCount = 0;
  83415. }
  83416. var newReferences = new Array(this.triangles.length * 3);
  83417. for (i = 0; i < this.triangles.length; ++i) {
  83418. t = this.triangles[i];
  83419. for (j = 0; j < 3; ++j) {
  83420. v = t.vertices[j];
  83421. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  83422. v.triangleCount++;
  83423. }
  83424. }
  83425. this.references = newReferences;
  83426. if (identifyBorders) {
  83427. this.identifyBorder();
  83428. }
  83429. };
  83430. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  83431. var x = point.x;
  83432. var y = point.y;
  83433. var z = point.z;
  83434. 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
  83435. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  83436. };
  83437. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  83438. var q = vertex1.q.add(vertex2.q);
  83439. var border = vertex1.isBorder && vertex2.isBorder;
  83440. var error = 0;
  83441. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  83442. if (qDet !== 0 && !border) {
  83443. if (!pointResult) {
  83444. pointResult = BABYLON.Vector3.Zero();
  83445. }
  83446. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  83447. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  83448. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  83449. error = this.vertexError(q, pointResult);
  83450. }
  83451. else {
  83452. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  83453. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  83454. var error1 = this.vertexError(q, vertex1.position);
  83455. var error2 = this.vertexError(q, vertex2.position);
  83456. var error3 = this.vertexError(q, p3);
  83457. error = Math.min(error1, error2, error3);
  83458. if (error === error1) {
  83459. if (pointResult) {
  83460. pointResult.copyFrom(vertex1.position);
  83461. }
  83462. }
  83463. else if (error === error2) {
  83464. if (pointResult) {
  83465. pointResult.copyFrom(vertex2.position);
  83466. }
  83467. }
  83468. else {
  83469. if (pointResult) {
  83470. pointResult.copyFrom(p3);
  83471. }
  83472. }
  83473. }
  83474. return error;
  83475. };
  83476. return QuadraticErrorSimplification;
  83477. }());
  83478. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  83479. })(BABYLON || (BABYLON = {}));
  83480. //# sourceMappingURL=babylon.meshSimplification.js.map
  83481. var BABYLON;
  83482. (function (BABYLON) {
  83483. var MeshLODLevel = /** @class */ (function () {
  83484. function MeshLODLevel(distance, mesh) {
  83485. this.distance = distance;
  83486. this.mesh = mesh;
  83487. }
  83488. return MeshLODLevel;
  83489. }());
  83490. BABYLON.MeshLODLevel = MeshLODLevel;
  83491. })(BABYLON || (BABYLON = {}));
  83492. //# sourceMappingURL=babylon.meshLODLevel.js.map
  83493. var BABYLON;
  83494. (function (BABYLON) {
  83495. /**
  83496. * Defines the root class used to create scene optimization to use with SceneOptimizer
  83497. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83498. */
  83499. var SceneOptimization = /** @class */ (function () {
  83500. /**
  83501. * Creates the SceneOptimization object
  83502. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83503. * @param desc defines the description associated with the optimization
  83504. */
  83505. function SceneOptimization(
  83506. /**
  83507. * Defines the priority of this optimization (0 by default which means first in the list)
  83508. */
  83509. priority) {
  83510. if (priority === void 0) { priority = 0; }
  83511. this.priority = priority;
  83512. }
  83513. /**
  83514. * Gets a string describing the action executed by the current optimization
  83515. * @returns description string
  83516. */
  83517. SceneOptimization.prototype.getDescription = function () {
  83518. return "";
  83519. };
  83520. /**
  83521. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83522. * @param scene defines the current scene where to apply this optimization
  83523. * @param optimizer defines the current optimizer
  83524. * @returns true if everything that can be done was applied
  83525. */
  83526. SceneOptimization.prototype.apply = function (scene, optimizer) {
  83527. return true;
  83528. };
  83529. ;
  83530. return SceneOptimization;
  83531. }());
  83532. BABYLON.SceneOptimization = SceneOptimization;
  83533. /**
  83534. * Defines an optimization used to reduce the size of render target textures
  83535. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83536. */
  83537. var TextureOptimization = /** @class */ (function (_super) {
  83538. __extends(TextureOptimization, _super);
  83539. /**
  83540. * Creates the TextureOptimization object
  83541. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83542. * @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
  83543. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83544. */
  83545. function TextureOptimization(
  83546. /**
  83547. * Defines the priority of this optimization (0 by default which means first in the list)
  83548. */
  83549. priority,
  83550. /**
  83551. * 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
  83552. */
  83553. maximumSize,
  83554. /**
  83555. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83556. */
  83557. step) {
  83558. if (priority === void 0) { priority = 0; }
  83559. if (maximumSize === void 0) { maximumSize = 1024; }
  83560. if (step === void 0) { step = 0.5; }
  83561. var _this = _super.call(this, priority) || this;
  83562. _this.priority = priority;
  83563. _this.maximumSize = maximumSize;
  83564. _this.step = step;
  83565. return _this;
  83566. }
  83567. /**
  83568. * Gets a string describing the action executed by the current optimization
  83569. * @returns description string
  83570. */
  83571. TextureOptimization.prototype.getDescription = function () {
  83572. return "Reducing render target texture size to " + this.maximumSize;
  83573. };
  83574. /**
  83575. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83576. * @param scene defines the current scene where to apply this optimization
  83577. * @param optimizer defines the current optimizer
  83578. * @returns true if everything that can be done was applied
  83579. */
  83580. TextureOptimization.prototype.apply = function (scene, optimizer) {
  83581. var allDone = true;
  83582. for (var index = 0; index < scene.textures.length; index++) {
  83583. var texture = scene.textures[index];
  83584. if (!texture.canRescale || texture.getContext) {
  83585. continue;
  83586. }
  83587. var currentSize = texture.getSize();
  83588. var maxDimension = Math.max(currentSize.width, currentSize.height);
  83589. if (maxDimension > this.maximumSize) {
  83590. texture.scale(this.step);
  83591. allDone = false;
  83592. }
  83593. }
  83594. return allDone;
  83595. };
  83596. return TextureOptimization;
  83597. }(SceneOptimization));
  83598. BABYLON.TextureOptimization = TextureOptimization;
  83599. /**
  83600. * Defines an optimization used to increase or decrease the rendering resolution
  83601. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83602. */
  83603. var HardwareScalingOptimization = /** @class */ (function (_super) {
  83604. __extends(HardwareScalingOptimization, _super);
  83605. /**
  83606. * Creates the HardwareScalingOptimization object
  83607. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83608. * @param maximumScale defines the maximum scale to use (2 by default)
  83609. * @param step defines the step to use between two passes (0.5 by default)
  83610. */
  83611. function HardwareScalingOptimization(
  83612. /**
  83613. * Defines the priority of this optimization (0 by default which means first in the list)
  83614. */
  83615. priority,
  83616. /**
  83617. * Defines the maximum scale to use (2 by default)
  83618. */
  83619. maximumScale,
  83620. /**
  83621. * Defines the step to use between two passes (0.5 by default)
  83622. */
  83623. step) {
  83624. if (priority === void 0) { priority = 0; }
  83625. if (maximumScale === void 0) { maximumScale = 2; }
  83626. if (step === void 0) { step = 0.25; }
  83627. var _this = _super.call(this, priority) || this;
  83628. _this.priority = priority;
  83629. _this.maximumScale = maximumScale;
  83630. _this.step = step;
  83631. _this._currentScale = -1;
  83632. _this._directionOffset = 1;
  83633. return _this;
  83634. }
  83635. /**
  83636. * Gets a string describing the action executed by the current optimization
  83637. * @return description string
  83638. */
  83639. HardwareScalingOptimization.prototype.getDescription = function () {
  83640. return "Setting hardware scaling level to " + this._currentScale;
  83641. };
  83642. /**
  83643. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83644. * @param scene defines the current scene where to apply this optimization
  83645. * @param optimizer defines the current optimizer
  83646. * @returns true if everything that can be done was applied
  83647. */
  83648. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  83649. if (this._currentScale === -1) {
  83650. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  83651. if (this._currentScale > this.maximumScale) {
  83652. this._directionOffset = -1;
  83653. }
  83654. }
  83655. this._currentScale += this._directionOffset * this.step;
  83656. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  83657. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  83658. };
  83659. ;
  83660. return HardwareScalingOptimization;
  83661. }(SceneOptimization));
  83662. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  83663. /**
  83664. * Defines an optimization used to remove shadows
  83665. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83666. */
  83667. var ShadowsOptimization = /** @class */ (function (_super) {
  83668. __extends(ShadowsOptimization, _super);
  83669. function ShadowsOptimization() {
  83670. return _super !== null && _super.apply(this, arguments) || this;
  83671. }
  83672. /**
  83673. * Gets a string describing the action executed by the current optimization
  83674. * @return description string
  83675. */
  83676. ShadowsOptimization.prototype.getDescription = function () {
  83677. return "Turning shadows on/off";
  83678. };
  83679. /**
  83680. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83681. * @param scene defines the current scene where to apply this optimization
  83682. * @param optimizer defines the current optimizer
  83683. * @returns true if everything that can be done was applied
  83684. */
  83685. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  83686. scene.shadowsEnabled = optimizer.isInImprovementMode;
  83687. return true;
  83688. };
  83689. ;
  83690. return ShadowsOptimization;
  83691. }(SceneOptimization));
  83692. BABYLON.ShadowsOptimization = ShadowsOptimization;
  83693. /**
  83694. * Defines an optimization used to turn post-processes off
  83695. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83696. */
  83697. var PostProcessesOptimization = /** @class */ (function (_super) {
  83698. __extends(PostProcessesOptimization, _super);
  83699. function PostProcessesOptimization() {
  83700. return _super !== null && _super.apply(this, arguments) || this;
  83701. }
  83702. /**
  83703. * Gets a string describing the action executed by the current optimization
  83704. * @return description string
  83705. */
  83706. PostProcessesOptimization.prototype.getDescription = function () {
  83707. return "Turning post-processes on/off";
  83708. };
  83709. /**
  83710. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83711. * @param scene defines the current scene where to apply this optimization
  83712. * @param optimizer defines the current optimizer
  83713. * @returns true if everything that can be done was applied
  83714. */
  83715. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  83716. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  83717. return true;
  83718. };
  83719. ;
  83720. return PostProcessesOptimization;
  83721. }(SceneOptimization));
  83722. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  83723. /**
  83724. * Defines an optimization used to turn lens flares off
  83725. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83726. */
  83727. var LensFlaresOptimization = /** @class */ (function (_super) {
  83728. __extends(LensFlaresOptimization, _super);
  83729. function LensFlaresOptimization() {
  83730. return _super !== null && _super.apply(this, arguments) || this;
  83731. }
  83732. /**
  83733. * Gets a string describing the action executed by the current optimization
  83734. * @return description string
  83735. */
  83736. LensFlaresOptimization.prototype.getDescription = function () {
  83737. return "Turning lens flares on/off";
  83738. };
  83739. /**
  83740. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83741. * @param scene defines the current scene where to apply this optimization
  83742. * @param optimizer defines the current optimizer
  83743. * @returns true if everything that can be done was applied
  83744. */
  83745. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  83746. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  83747. return true;
  83748. };
  83749. ;
  83750. return LensFlaresOptimization;
  83751. }(SceneOptimization));
  83752. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  83753. /**
  83754. * Defines an optimization based on user defined callback.
  83755. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83756. */
  83757. var CustomOptimization = /** @class */ (function (_super) {
  83758. __extends(CustomOptimization, _super);
  83759. function CustomOptimization() {
  83760. return _super !== null && _super.apply(this, arguments) || this;
  83761. }
  83762. /**
  83763. * Gets a string describing the action executed by the current optimization
  83764. * @returns description string
  83765. */
  83766. CustomOptimization.prototype.getDescription = function () {
  83767. if (this.onGetDescription) {
  83768. return this.onGetDescription();
  83769. }
  83770. return "Running user defined callback";
  83771. };
  83772. /**
  83773. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83774. * @param scene defines the current scene where to apply this optimization
  83775. * @param optimizer defines the current optimizer
  83776. * @returns true if everything that can be done was applied
  83777. */
  83778. CustomOptimization.prototype.apply = function (scene, optimizer) {
  83779. if (this.onApply) {
  83780. return this.onApply(scene, optimizer);
  83781. }
  83782. return true;
  83783. };
  83784. ;
  83785. return CustomOptimization;
  83786. }(SceneOptimization));
  83787. BABYLON.CustomOptimization = CustomOptimization;
  83788. /**
  83789. * Defines an optimization used to turn particles off
  83790. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83791. */
  83792. var ParticlesOptimization = /** @class */ (function (_super) {
  83793. __extends(ParticlesOptimization, _super);
  83794. function ParticlesOptimization() {
  83795. return _super !== null && _super.apply(this, arguments) || this;
  83796. }
  83797. /**
  83798. * Gets a string describing the action executed by the current optimization
  83799. * @return description string
  83800. */
  83801. ParticlesOptimization.prototype.getDescription = function () {
  83802. return "Turning particles on/off";
  83803. };
  83804. /**
  83805. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83806. * @param scene defines the current scene where to apply this optimization
  83807. * @param optimizer defines the current optimizer
  83808. * @returns true if everything that can be done was applied
  83809. */
  83810. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  83811. scene.particlesEnabled = optimizer.isInImprovementMode;
  83812. return true;
  83813. };
  83814. ;
  83815. return ParticlesOptimization;
  83816. }(SceneOptimization));
  83817. BABYLON.ParticlesOptimization = ParticlesOptimization;
  83818. /**
  83819. * Defines an optimization used to turn render targets off
  83820. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83821. */
  83822. var RenderTargetsOptimization = /** @class */ (function (_super) {
  83823. __extends(RenderTargetsOptimization, _super);
  83824. function RenderTargetsOptimization() {
  83825. return _super !== null && _super.apply(this, arguments) || this;
  83826. }
  83827. /**
  83828. * Gets a string describing the action executed by the current optimization
  83829. * @return description string
  83830. */
  83831. RenderTargetsOptimization.prototype.getDescription = function () {
  83832. return "Turning render targets off";
  83833. };
  83834. /**
  83835. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83836. * @param scene defines the current scene where to apply this optimization
  83837. * @param optimizer defines the current optimizer
  83838. * @returns true if everything that can be done was applied
  83839. */
  83840. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  83841. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  83842. return true;
  83843. };
  83844. ;
  83845. return RenderTargetsOptimization;
  83846. }(SceneOptimization));
  83847. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  83848. /**
  83849. * Defines an optimization used to merge meshes with compatible materials
  83850. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83851. */
  83852. var MergeMeshesOptimization = /** @class */ (function (_super) {
  83853. __extends(MergeMeshesOptimization, _super);
  83854. function MergeMeshesOptimization() {
  83855. var _this = _super !== null && _super.apply(this, arguments) || this;
  83856. _this._canBeMerged = function (abstractMesh) {
  83857. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  83858. return false;
  83859. }
  83860. var mesh = abstractMesh;
  83861. if (!mesh.isVisible || !mesh.isEnabled()) {
  83862. return false;
  83863. }
  83864. if (mesh.instances.length > 0) {
  83865. return false;
  83866. }
  83867. if (mesh.skeleton || mesh.hasLODLevels) {
  83868. return false;
  83869. }
  83870. if (mesh.parent) {
  83871. return false;
  83872. }
  83873. return true;
  83874. };
  83875. return _this;
  83876. }
  83877. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  83878. /**
  83879. * Gets or sets a boolean which defines if optimization octree has to be updated
  83880. */
  83881. get: function () {
  83882. return MergeMeshesOptimization._UpdateSelectionTree;
  83883. },
  83884. /**
  83885. * Gets or sets a boolean which defines if optimization octree has to be updated
  83886. */
  83887. set: function (value) {
  83888. MergeMeshesOptimization._UpdateSelectionTree = value;
  83889. },
  83890. enumerable: true,
  83891. configurable: true
  83892. });
  83893. /**
  83894. * Gets a string describing the action executed by the current optimization
  83895. * @return description string
  83896. */
  83897. MergeMeshesOptimization.prototype.getDescription = function () {
  83898. return "Merging similar meshes together";
  83899. };
  83900. /**
  83901. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83902. * @param scene defines the current scene where to apply this optimization
  83903. * @param optimizer defines the current optimizer
  83904. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  83905. * @returns true if everything that can be done was applied
  83906. */
  83907. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  83908. var globalPool = scene.meshes.slice(0);
  83909. var globalLength = globalPool.length;
  83910. for (var index = 0; index < globalLength; index++) {
  83911. var currentPool = new Array();
  83912. var current = globalPool[index];
  83913. // Checks
  83914. if (!this._canBeMerged(current)) {
  83915. continue;
  83916. }
  83917. currentPool.push(current);
  83918. // Find compatible meshes
  83919. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  83920. var otherMesh = globalPool[subIndex];
  83921. if (!this._canBeMerged(otherMesh)) {
  83922. continue;
  83923. }
  83924. if (otherMesh.material !== current.material) {
  83925. continue;
  83926. }
  83927. if (otherMesh.checkCollisions !== current.checkCollisions) {
  83928. continue;
  83929. }
  83930. currentPool.push(otherMesh);
  83931. globalLength--;
  83932. globalPool.splice(subIndex, 1);
  83933. subIndex--;
  83934. }
  83935. if (currentPool.length < 2) {
  83936. continue;
  83937. }
  83938. // Merge meshes
  83939. BABYLON.Mesh.MergeMeshes(currentPool);
  83940. }
  83941. if (updateSelectionTree != undefined) {
  83942. if (updateSelectionTree) {
  83943. scene.createOrUpdateSelectionOctree();
  83944. }
  83945. }
  83946. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  83947. scene.createOrUpdateSelectionOctree();
  83948. }
  83949. return true;
  83950. };
  83951. ;
  83952. MergeMeshesOptimization._UpdateSelectionTree = false;
  83953. return MergeMeshesOptimization;
  83954. }(SceneOptimization));
  83955. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  83956. /**
  83957. * Defines a list of options used by SceneOptimizer
  83958. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83959. */
  83960. var SceneOptimizerOptions = /** @class */ (function () {
  83961. /**
  83962. * Creates a new list of options used by SceneOptimizer
  83963. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  83964. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  83965. */
  83966. function SceneOptimizerOptions(
  83967. /**
  83968. * Defines the target frame rate to reach (60 by default)
  83969. */
  83970. targetFrameRate,
  83971. /**
  83972. * Defines the interval between two checkes (2000ms by default)
  83973. */
  83974. trackerDuration) {
  83975. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  83976. if (trackerDuration === void 0) { trackerDuration = 2000; }
  83977. this.targetFrameRate = targetFrameRate;
  83978. this.trackerDuration = trackerDuration;
  83979. /**
  83980. * Gets the list of optimizations to apply
  83981. */
  83982. this.optimizations = new Array();
  83983. }
  83984. /**
  83985. * Add a new optimization
  83986. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  83987. * @returns the current SceneOptimizerOptions
  83988. */
  83989. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  83990. this.optimizations.push(optimization);
  83991. return this;
  83992. };
  83993. /**
  83994. * Add a new custom optimization
  83995. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  83996. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  83997. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83998. * @returns the current SceneOptimizerOptions
  83999. */
  84000. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  84001. if (priority === void 0) { priority = 0; }
  84002. var optimization = new CustomOptimization(priority);
  84003. optimization.onApply = onApply;
  84004. optimization.onGetDescription = onGetDescription;
  84005. this.optimizations.push(optimization);
  84006. return this;
  84007. };
  84008. /**
  84009. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  84010. * @param targetFrameRate defines the target frame rate (60 by default)
  84011. * @returns a SceneOptimizerOptions object
  84012. */
  84013. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  84014. var result = new SceneOptimizerOptions(targetFrameRate);
  84015. var priority = 0;
  84016. result.addOptimization(new MergeMeshesOptimization(priority));
  84017. result.addOptimization(new ShadowsOptimization(priority));
  84018. result.addOptimization(new LensFlaresOptimization(priority));
  84019. // Next priority
  84020. priority++;
  84021. result.addOptimization(new PostProcessesOptimization(priority));
  84022. result.addOptimization(new ParticlesOptimization(priority));
  84023. // Next priority
  84024. priority++;
  84025. result.addOptimization(new TextureOptimization(priority, 1024));
  84026. return result;
  84027. };
  84028. /**
  84029. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  84030. * @param targetFrameRate defines the target frame rate (60 by default)
  84031. * @returns a SceneOptimizerOptions object
  84032. */
  84033. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  84034. var result = new SceneOptimizerOptions(targetFrameRate);
  84035. var priority = 0;
  84036. result.addOptimization(new MergeMeshesOptimization(priority));
  84037. result.addOptimization(new ShadowsOptimization(priority));
  84038. result.addOptimization(new LensFlaresOptimization(priority));
  84039. // Next priority
  84040. priority++;
  84041. result.addOptimization(new PostProcessesOptimization(priority));
  84042. result.addOptimization(new ParticlesOptimization(priority));
  84043. // Next priority
  84044. priority++;
  84045. result.addOptimization(new TextureOptimization(priority, 512));
  84046. // Next priority
  84047. priority++;
  84048. result.addOptimization(new RenderTargetsOptimization(priority));
  84049. // Next priority
  84050. priority++;
  84051. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  84052. return result;
  84053. };
  84054. /**
  84055. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  84056. * @param targetFrameRate defines the target frame rate (60 by default)
  84057. * @returns a SceneOptimizerOptions object
  84058. */
  84059. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  84060. var result = new SceneOptimizerOptions(targetFrameRate);
  84061. var priority = 0;
  84062. result.addOptimization(new MergeMeshesOptimization(priority));
  84063. result.addOptimization(new ShadowsOptimization(priority));
  84064. result.addOptimization(new LensFlaresOptimization(priority));
  84065. // Next priority
  84066. priority++;
  84067. result.addOptimization(new PostProcessesOptimization(priority));
  84068. result.addOptimization(new ParticlesOptimization(priority));
  84069. // Next priority
  84070. priority++;
  84071. result.addOptimization(new TextureOptimization(priority, 256));
  84072. // Next priority
  84073. priority++;
  84074. result.addOptimization(new RenderTargetsOptimization(priority));
  84075. // Next priority
  84076. priority++;
  84077. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  84078. return result;
  84079. };
  84080. return SceneOptimizerOptions;
  84081. }());
  84082. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  84083. /**
  84084. * Class used to run optimizations in order to reach a target frame rate
  84085. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84086. */
  84087. var SceneOptimizer = /** @class */ (function () {
  84088. /**
  84089. * Creates a new SceneOptimizer
  84090. * @param scene defines the scene to work on
  84091. * @param options defines the options to use with the SceneOptimizer
  84092. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  84093. * @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)
  84094. */
  84095. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  84096. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  84097. if (improvementMode === void 0) { improvementMode = false; }
  84098. var _this = this;
  84099. this._isRunning = false;
  84100. this._currentPriorityLevel = 0;
  84101. this._targetFrameRate = 60;
  84102. this._trackerDuration = 2000;
  84103. this._currentFrameRate = 0;
  84104. this._improvementMode = false;
  84105. /**
  84106. * Defines an observable called when the optimizer reaches the target frame rate
  84107. */
  84108. this.onSuccessObservable = new BABYLON.Observable();
  84109. /**
  84110. * Defines an observable called when the optimizer enables an optimization
  84111. */
  84112. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  84113. /**
  84114. * Defines an observable called when the optimizer is not able to reach the target frame rate
  84115. */
  84116. this.onFailureObservable = new BABYLON.Observable();
  84117. if (!options) {
  84118. this._options = new SceneOptimizerOptions();
  84119. }
  84120. else {
  84121. this._options = options;
  84122. }
  84123. if (this._options.targetFrameRate) {
  84124. this._targetFrameRate = this._options.targetFrameRate;
  84125. }
  84126. if (this._options.trackerDuration) {
  84127. this._trackerDuration = this._options.trackerDuration;
  84128. }
  84129. if (autoGeneratePriorities) {
  84130. var priority = 0;
  84131. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  84132. var optim = _a[_i];
  84133. optim.priority = priority++;
  84134. }
  84135. }
  84136. this._improvementMode = improvementMode;
  84137. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84138. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  84139. _this._sceneDisposeObserver = null;
  84140. _this.dispose();
  84141. });
  84142. }
  84143. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  84144. /**
  84145. * Gets a boolean indicating if the optimizer is in improvement mode
  84146. */
  84147. get: function () {
  84148. return this._improvementMode;
  84149. },
  84150. enumerable: true,
  84151. configurable: true
  84152. });
  84153. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  84154. /**
  84155. * Gets the current priority level (0 at start)
  84156. */
  84157. get: function () {
  84158. return this._currentPriorityLevel;
  84159. },
  84160. enumerable: true,
  84161. configurable: true
  84162. });
  84163. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  84164. /**
  84165. * Gets the current frame rate checked by the SceneOptimizer
  84166. */
  84167. get: function () {
  84168. return this._currentFrameRate;
  84169. },
  84170. enumerable: true,
  84171. configurable: true
  84172. });
  84173. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  84174. /**
  84175. * Gets or sets the current target frame rate (60 by default)
  84176. */
  84177. get: function () {
  84178. return this._targetFrameRate;
  84179. },
  84180. /**
  84181. * Gets or sets the current target frame rate (60 by default)
  84182. */
  84183. set: function (value) {
  84184. this._targetFrameRate = value;
  84185. },
  84186. enumerable: true,
  84187. configurable: true
  84188. });
  84189. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  84190. /**
  84191. * Gets or sets the current interval between two checks (every 2000ms by default)
  84192. */
  84193. get: function () {
  84194. return this._trackerDuration;
  84195. },
  84196. /**
  84197. * Gets or sets the current interval between two checks (every 2000ms by default)
  84198. */
  84199. set: function (value) {
  84200. this._trackerDuration = value;
  84201. },
  84202. enumerable: true,
  84203. configurable: true
  84204. });
  84205. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  84206. /**
  84207. * Gets the list of active optimizations
  84208. */
  84209. get: function () {
  84210. return this._options.optimizations;
  84211. },
  84212. enumerable: true,
  84213. configurable: true
  84214. });
  84215. /**
  84216. * Stops the current optimizer
  84217. */
  84218. SceneOptimizer.prototype.stop = function () {
  84219. this._isRunning = false;
  84220. };
  84221. /**
  84222. * Reset the optimizer to initial step (current priority level = 0)
  84223. */
  84224. SceneOptimizer.prototype.reset = function () {
  84225. this._currentPriorityLevel = 0;
  84226. };
  84227. /**
  84228. * Start the optimizer. By default it will try to reach a specific framerate
  84229. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  84230. */
  84231. SceneOptimizer.prototype.start = function () {
  84232. var _this = this;
  84233. if (this._isRunning) {
  84234. return;
  84235. }
  84236. this._isRunning = true;
  84237. // Let's wait for the scene to be ready before running our check
  84238. this._scene.executeWhenReady(function () {
  84239. setTimeout(function () {
  84240. _this._checkCurrentState();
  84241. }, _this._trackerDuration);
  84242. });
  84243. };
  84244. SceneOptimizer.prototype._checkCurrentState = function () {
  84245. var _this = this;
  84246. if (!this._isRunning) {
  84247. return;
  84248. }
  84249. var scene = this._scene;
  84250. var options = this._options;
  84251. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  84252. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  84253. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  84254. this._isRunning = false;
  84255. this.onSuccessObservable.notifyObservers(this);
  84256. return;
  84257. }
  84258. // Apply current level of optimizations
  84259. var allDone = true;
  84260. var noOptimizationApplied = true;
  84261. for (var index = 0; index < options.optimizations.length; index++) {
  84262. var optimization = options.optimizations[index];
  84263. if (optimization.priority === this._currentPriorityLevel) {
  84264. noOptimizationApplied = false;
  84265. allDone = allDone && optimization.apply(scene, this);
  84266. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  84267. }
  84268. }
  84269. // If no optimization was applied, this is a failure :(
  84270. if (noOptimizationApplied) {
  84271. this._isRunning = false;
  84272. this.onFailureObservable.notifyObservers(this);
  84273. return;
  84274. }
  84275. // If all optimizations were done, move to next level
  84276. if (allDone) {
  84277. this._currentPriorityLevel++;
  84278. }
  84279. // Let's the system running for a specific amount of time before checking FPS
  84280. scene.executeWhenReady(function () {
  84281. setTimeout(function () {
  84282. _this._checkCurrentState();
  84283. }, _this._trackerDuration);
  84284. });
  84285. };
  84286. /**
  84287. * Release all resources
  84288. */
  84289. SceneOptimizer.prototype.dispose = function () {
  84290. this.stop();
  84291. this.onSuccessObservable.clear();
  84292. this.onFailureObservable.clear();
  84293. this.onNewOptimizationAppliedObservable.clear();
  84294. if (this._sceneDisposeObserver) {
  84295. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  84296. }
  84297. };
  84298. /**
  84299. * Helper function to create a SceneOptimizer with one single line of code
  84300. * @param scene defines the scene to work on
  84301. * @param options defines the options to use with the SceneOptimizer
  84302. * @param onSuccess defines a callback to call on success
  84303. * @param onFailure defines a callback to call on failure
  84304. * @returns the new SceneOptimizer object
  84305. */
  84306. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  84307. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  84308. if (onSuccess) {
  84309. optimizer.onSuccessObservable.add(function () {
  84310. onSuccess();
  84311. });
  84312. }
  84313. if (onFailure) {
  84314. optimizer.onFailureObservable.add(function () {
  84315. onFailure();
  84316. });
  84317. }
  84318. optimizer.start();
  84319. return optimizer;
  84320. };
  84321. return SceneOptimizer;
  84322. }());
  84323. BABYLON.SceneOptimizer = SceneOptimizer;
  84324. })(BABYLON || (BABYLON = {}));
  84325. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  84326. var BABYLON;
  84327. (function (BABYLON) {
  84328. var OutlineRenderer = /** @class */ (function () {
  84329. function OutlineRenderer(scene) {
  84330. this.zOffset = 1;
  84331. this._scene = scene;
  84332. }
  84333. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  84334. var _this = this;
  84335. if (useOverlay === void 0) { useOverlay = false; }
  84336. var scene = this._scene;
  84337. var engine = this._scene.getEngine();
  84338. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84339. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  84340. return;
  84341. }
  84342. var mesh = subMesh.getRenderingMesh();
  84343. var material = subMesh.getMaterial();
  84344. if (!material || !scene.activeCamera) {
  84345. return;
  84346. }
  84347. engine.enableEffect(this._effect);
  84348. // Logarithmic depth
  84349. if (material.useLogarithmicDepth) {
  84350. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  84351. }
  84352. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  84353. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  84354. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84355. // Bones
  84356. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84357. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84358. }
  84359. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  84360. // Alpha test
  84361. if (material && material.needAlphaTesting()) {
  84362. var alphaTexture = material.getAlphaTestTexture();
  84363. if (alphaTexture) {
  84364. this._effect.setTexture("diffuseSampler", alphaTexture);
  84365. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84366. }
  84367. }
  84368. engine.setZOffset(-this.zOffset);
  84369. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  84370. engine.setZOffset(0);
  84371. };
  84372. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  84373. var defines = [];
  84374. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84375. var mesh = subMesh.getMesh();
  84376. var material = subMesh.getMaterial();
  84377. if (material) {
  84378. // Alpha test
  84379. if (material.needAlphaTesting()) {
  84380. defines.push("#define ALPHATEST");
  84381. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84382. attribs.push(BABYLON.VertexBuffer.UVKind);
  84383. defines.push("#define UV1");
  84384. }
  84385. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84386. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84387. defines.push("#define UV2");
  84388. }
  84389. }
  84390. //Logarithmic depth
  84391. if (material.useLogarithmicDepth) {
  84392. defines.push("#define LOGARITHMICDEPTH");
  84393. }
  84394. }
  84395. // Bones
  84396. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84397. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84398. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84399. if (mesh.numBoneInfluencers > 4) {
  84400. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84401. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84402. }
  84403. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84404. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84405. }
  84406. else {
  84407. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84408. }
  84409. // Instances
  84410. if (useInstances) {
  84411. defines.push("#define INSTANCES");
  84412. attribs.push("world0");
  84413. attribs.push("world1");
  84414. attribs.push("world2");
  84415. attribs.push("world3");
  84416. }
  84417. // Get correct effect
  84418. var join = defines.join("\n");
  84419. if (this._cachedDefines !== join) {
  84420. this._cachedDefines = join;
  84421. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  84422. }
  84423. return this._effect.isReady();
  84424. };
  84425. return OutlineRenderer;
  84426. }());
  84427. BABYLON.OutlineRenderer = OutlineRenderer;
  84428. })(BABYLON || (BABYLON = {}));
  84429. //# sourceMappingURL=babylon.outlineRenderer.js.map
  84430. var BABYLON;
  84431. (function (BABYLON) {
  84432. var FaceAdjacencies = /** @class */ (function () {
  84433. function FaceAdjacencies() {
  84434. this.edges = new Array();
  84435. this.edgesConnectedCount = 0;
  84436. }
  84437. return FaceAdjacencies;
  84438. }());
  84439. var EdgesRenderer = /** @class */ (function () {
  84440. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  84441. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  84442. if (epsilon === void 0) { epsilon = 0.95; }
  84443. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  84444. this.edgesWidthScalerForOrthographic = 1000.0;
  84445. this.edgesWidthScalerForPerspective = 50.0;
  84446. this._linesPositions = new Array();
  84447. this._linesNormals = new Array();
  84448. this._linesIndices = new Array();
  84449. this._buffers = {};
  84450. this._checkVerticesInsteadOfIndices = false;
  84451. this._source = source;
  84452. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  84453. this._epsilon = epsilon;
  84454. this._prepareRessources();
  84455. this._generateEdgesLines();
  84456. }
  84457. EdgesRenderer.prototype._prepareRessources = function () {
  84458. if (this._lineShader) {
  84459. return;
  84460. }
  84461. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  84462. attributes: ["position", "normal"],
  84463. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  84464. });
  84465. this._lineShader.disableDepthWrite = true;
  84466. this._lineShader.backFaceCulling = false;
  84467. };
  84468. EdgesRenderer.prototype._rebuild = function () {
  84469. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84470. if (buffer) {
  84471. buffer._rebuild();
  84472. }
  84473. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84474. if (buffer) {
  84475. buffer._rebuild();
  84476. }
  84477. var scene = this._source.getScene();
  84478. var engine = scene.getEngine();
  84479. this._ib = engine.createIndexBuffer(this._linesIndices);
  84480. };
  84481. EdgesRenderer.prototype.dispose = function () {
  84482. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84483. if (buffer) {
  84484. buffer.dispose();
  84485. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  84486. }
  84487. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84488. if (buffer) {
  84489. buffer.dispose();
  84490. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  84491. }
  84492. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  84493. this._lineShader.dispose();
  84494. };
  84495. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  84496. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  84497. return 0;
  84498. }
  84499. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  84500. return 1;
  84501. }
  84502. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  84503. return 2;
  84504. }
  84505. return -1;
  84506. };
  84507. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  84508. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  84509. return 0;
  84510. }
  84511. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  84512. return 1;
  84513. }
  84514. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  84515. return 2;
  84516. }
  84517. return -1;
  84518. };
  84519. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  84520. var needToCreateLine;
  84521. if (edge === undefined) {
  84522. needToCreateLine = true;
  84523. }
  84524. else {
  84525. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  84526. needToCreateLine = dotProduct < this._epsilon;
  84527. }
  84528. if (needToCreateLine) {
  84529. var offset = this._linesPositions.length / 3;
  84530. var normal = p0.subtract(p1);
  84531. normal.normalize();
  84532. // Positions
  84533. this._linesPositions.push(p0.x);
  84534. this._linesPositions.push(p0.y);
  84535. this._linesPositions.push(p0.z);
  84536. this._linesPositions.push(p0.x);
  84537. this._linesPositions.push(p0.y);
  84538. this._linesPositions.push(p0.z);
  84539. this._linesPositions.push(p1.x);
  84540. this._linesPositions.push(p1.y);
  84541. this._linesPositions.push(p1.z);
  84542. this._linesPositions.push(p1.x);
  84543. this._linesPositions.push(p1.y);
  84544. this._linesPositions.push(p1.z);
  84545. // Normals
  84546. this._linesNormals.push(p1.x);
  84547. this._linesNormals.push(p1.y);
  84548. this._linesNormals.push(p1.z);
  84549. this._linesNormals.push(-1);
  84550. this._linesNormals.push(p1.x);
  84551. this._linesNormals.push(p1.y);
  84552. this._linesNormals.push(p1.z);
  84553. this._linesNormals.push(1);
  84554. this._linesNormals.push(p0.x);
  84555. this._linesNormals.push(p0.y);
  84556. this._linesNormals.push(p0.z);
  84557. this._linesNormals.push(-1);
  84558. this._linesNormals.push(p0.x);
  84559. this._linesNormals.push(p0.y);
  84560. this._linesNormals.push(p0.z);
  84561. this._linesNormals.push(1);
  84562. // Indices
  84563. this._linesIndices.push(offset);
  84564. this._linesIndices.push(offset + 1);
  84565. this._linesIndices.push(offset + 2);
  84566. this._linesIndices.push(offset);
  84567. this._linesIndices.push(offset + 2);
  84568. this._linesIndices.push(offset + 3);
  84569. }
  84570. };
  84571. EdgesRenderer.prototype._generateEdgesLines = function () {
  84572. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84573. var indices = this._source.getIndices();
  84574. if (!indices || !positions) {
  84575. return;
  84576. }
  84577. // First let's find adjacencies
  84578. var adjacencies = new Array();
  84579. var faceNormals = new Array();
  84580. var index;
  84581. var faceAdjacencies;
  84582. // Prepare faces
  84583. for (index = 0; index < indices.length; index += 3) {
  84584. faceAdjacencies = new FaceAdjacencies();
  84585. var p0Index = indices[index];
  84586. var p1Index = indices[index + 1];
  84587. var p2Index = indices[index + 2];
  84588. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  84589. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  84590. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  84591. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  84592. faceNormal.normalize();
  84593. faceNormals.push(faceNormal);
  84594. adjacencies.push(faceAdjacencies);
  84595. }
  84596. // Scan
  84597. for (index = 0; index < adjacencies.length; index++) {
  84598. faceAdjacencies = adjacencies[index];
  84599. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  84600. var otherFaceAdjacencies = adjacencies[otherIndex];
  84601. if (faceAdjacencies.edgesConnectedCount === 3) {
  84602. break;
  84603. }
  84604. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  84605. continue;
  84606. }
  84607. var otherP0 = indices[otherIndex * 3];
  84608. var otherP1 = indices[otherIndex * 3 + 1];
  84609. var otherP2 = indices[otherIndex * 3 + 2];
  84610. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  84611. var otherEdgeIndex = 0;
  84612. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  84613. continue;
  84614. }
  84615. switch (edgeIndex) {
  84616. case 0:
  84617. if (this._checkVerticesInsteadOfIndices) {
  84618. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84619. }
  84620. else {
  84621. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  84622. }
  84623. break;
  84624. case 1:
  84625. if (this._checkVerticesInsteadOfIndices) {
  84626. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84627. }
  84628. else {
  84629. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  84630. }
  84631. break;
  84632. case 2:
  84633. if (this._checkVerticesInsteadOfIndices) {
  84634. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84635. }
  84636. else {
  84637. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  84638. }
  84639. break;
  84640. }
  84641. if (otherEdgeIndex === -1) {
  84642. continue;
  84643. }
  84644. faceAdjacencies.edges[edgeIndex] = otherIndex;
  84645. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  84646. faceAdjacencies.edgesConnectedCount++;
  84647. otherFaceAdjacencies.edgesConnectedCount++;
  84648. if (faceAdjacencies.edgesConnectedCount === 3) {
  84649. break;
  84650. }
  84651. }
  84652. }
  84653. }
  84654. // Create lines
  84655. for (index = 0; index < adjacencies.length; index++) {
  84656. // 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
  84657. var current = adjacencies[index];
  84658. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  84659. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  84660. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  84661. }
  84662. // Merge into a single mesh
  84663. var engine = this._source.getScene().getEngine();
  84664. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  84665. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  84666. this._ib = engine.createIndexBuffer(this._linesIndices);
  84667. this._indicesCount = this._linesIndices.length;
  84668. };
  84669. EdgesRenderer.prototype.render = function () {
  84670. var scene = this._source.getScene();
  84671. if (!this._lineShader.isReady() || !scene.activeCamera) {
  84672. return;
  84673. }
  84674. var engine = scene.getEngine();
  84675. this._lineShader._preBind();
  84676. // VBOs
  84677. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  84678. scene.resetCachedMaterial();
  84679. this._lineShader.setColor4("color", this._source.edgesColor);
  84680. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  84681. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  84682. }
  84683. else {
  84684. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  84685. }
  84686. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  84687. this._lineShader.bind(this._source.getWorldMatrix());
  84688. // Draw order
  84689. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  84690. this._lineShader.unbind();
  84691. engine.setDepthWrite(true);
  84692. };
  84693. return EdgesRenderer;
  84694. }());
  84695. BABYLON.EdgesRenderer = EdgesRenderer;
  84696. })(BABYLON || (BABYLON = {}));
  84697. //# sourceMappingURL=babylon.edgesRenderer.js.map
  84698. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84699. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84700. s = arguments[i];
  84701. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84702. t[p] = s[p];
  84703. }
  84704. return t;
  84705. };
  84706. var BABYLON;
  84707. (function (BABYLON) {
  84708. /**
  84709. * The effect layer Helps adding post process effect blended with the main pass.
  84710. *
  84711. * This can be for instance use to generate glow or higlight effects on the scene.
  84712. *
  84713. * The effect layer class can not be used directly and is intented to inherited from to be
  84714. * customized per effects.
  84715. */
  84716. var EffectLayer = /** @class */ (function () {
  84717. /**
  84718. * Instantiates a new effect Layer and references it in the scene.
  84719. * @param name The name of the layer
  84720. * @param scene The scene to use the layer in
  84721. */
  84722. function EffectLayer(
  84723. /** The Friendly of the effect in the scene */
  84724. name, scene) {
  84725. this.name = name;
  84726. this._vertexBuffers = {};
  84727. this._maxSize = 0;
  84728. this._mainTextureDesiredSize = { width: 0, height: 0 };
  84729. this._shouldRender = true;
  84730. this._postProcesses = [];
  84731. this._textures = [];
  84732. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  84733. /**
  84734. * The clear color of the texture used to generate the glow map.
  84735. */
  84736. this.neutralColor = new BABYLON.Color4();
  84737. /**
  84738. * Specifies wether the highlight layer is enabled or not.
  84739. */
  84740. this.isEnabled = true;
  84741. /**
  84742. * An event triggered when the effect layer has been disposed.
  84743. */
  84744. this.onDisposeObservable = new BABYLON.Observable();
  84745. /**
  84746. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  84747. */
  84748. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  84749. /**
  84750. * An event triggered when the generated texture is being merged in the scene.
  84751. */
  84752. this.onBeforeComposeObservable = new BABYLON.Observable();
  84753. /**
  84754. * An event triggered when the generated texture has been merged in the scene.
  84755. */
  84756. this.onAfterComposeObservable = new BABYLON.Observable();
  84757. /**
  84758. * An event triggered when the efffect layer changes its size.
  84759. */
  84760. this.onSizeChangedObservable = new BABYLON.Observable();
  84761. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84762. this._engine = scene.getEngine();
  84763. this._maxSize = this._engine.getCaps().maxTextureSize;
  84764. this._scene.effectLayers.push(this);
  84765. // Generate Buffers
  84766. this._generateIndexBuffer();
  84767. this._genrateVertexBuffer();
  84768. }
  84769. Object.defineProperty(EffectLayer.prototype, "camera", {
  84770. /**
  84771. * Gets the camera attached to the layer.
  84772. */
  84773. get: function () {
  84774. return this._effectLayerOptions.camera;
  84775. },
  84776. enumerable: true,
  84777. configurable: true
  84778. });
  84779. /**
  84780. * Initializes the effect layer with the required options.
  84781. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  84782. */
  84783. EffectLayer.prototype._init = function (options) {
  84784. // Adapt options
  84785. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84786. this._setMainTextureSize();
  84787. this._createMainTexture();
  84788. this._createTextureAndPostProcesses();
  84789. this._mergeEffect = this._createMergeEffect();
  84790. };
  84791. /**
  84792. * Generates the index buffer of the full screen quad blending to the main canvas.
  84793. */
  84794. EffectLayer.prototype._generateIndexBuffer = function () {
  84795. // Indices
  84796. var indices = [];
  84797. indices.push(0);
  84798. indices.push(1);
  84799. indices.push(2);
  84800. indices.push(0);
  84801. indices.push(2);
  84802. indices.push(3);
  84803. this._indexBuffer = this._engine.createIndexBuffer(indices);
  84804. };
  84805. /**
  84806. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  84807. */
  84808. EffectLayer.prototype._genrateVertexBuffer = function () {
  84809. // VBO
  84810. var vertices = [];
  84811. vertices.push(1, 1);
  84812. vertices.push(-1, 1);
  84813. vertices.push(-1, -1);
  84814. vertices.push(1, -1);
  84815. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84816. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84817. };
  84818. /**
  84819. * Sets the main texture desired size which is the closest power of two
  84820. * of the engine canvas size.
  84821. */
  84822. EffectLayer.prototype._setMainTextureSize = function () {
  84823. if (this._effectLayerOptions.mainTextureFixedSize) {
  84824. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  84825. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  84826. }
  84827. else {
  84828. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  84829. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  84830. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  84831. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  84832. }
  84833. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  84834. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  84835. };
  84836. /**
  84837. * Creates the main texture for the effect layer.
  84838. */
  84839. EffectLayer.prototype._createMainTexture = function () {
  84840. var _this = this;
  84841. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  84842. width: this._mainTextureDesiredSize.width,
  84843. height: this._mainTextureDesiredSize.height
  84844. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84845. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  84846. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84847. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84848. this._mainTexture.anisotropicFilteringLevel = 1;
  84849. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84850. this._mainTexture.renderParticles = false;
  84851. this._mainTexture.renderList = null;
  84852. this._mainTexture.ignoreCameraViewport = true;
  84853. // Custom render function
  84854. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84855. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  84856. var index;
  84857. var engine = _this._scene.getEngine();
  84858. if (depthOnlySubMeshes.length) {
  84859. engine.setColorWrite(false);
  84860. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84861. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  84862. }
  84863. engine.setColorWrite(true);
  84864. }
  84865. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84866. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  84867. }
  84868. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84869. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  84870. }
  84871. for (index = 0; index < transparentSubMeshes.length; index++) {
  84872. _this._renderSubMesh(transparentSubMeshes.data[index]);
  84873. }
  84874. };
  84875. this._mainTexture.onClearObservable.add(function (engine) {
  84876. engine.clear(_this.neutralColor, true, true, true);
  84877. });
  84878. };
  84879. /**
  84880. * Checks for the readiness of the element composing the layer.
  84881. * @param subMesh the mesh to check for
  84882. * @param useInstances specify wether or not to use instances to render the mesh
  84883. * @param emissiveTexture the associated emissive texture used to generate the glow
  84884. * @return true if ready otherwise, false
  84885. */
  84886. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  84887. var material = subMesh.getMaterial();
  84888. if (!material) {
  84889. return false;
  84890. }
  84891. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  84892. return false;
  84893. }
  84894. var defines = [];
  84895. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84896. var mesh = subMesh.getMesh();
  84897. var uv1 = false;
  84898. var uv2 = false;
  84899. // Alpha test
  84900. if (material && material.needAlphaTesting()) {
  84901. var alphaTexture = material.getAlphaTestTexture();
  84902. if (alphaTexture) {
  84903. defines.push("#define ALPHATEST");
  84904. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84905. alphaTexture.coordinatesIndex === 1) {
  84906. defines.push("#define DIFFUSEUV2");
  84907. uv2 = true;
  84908. }
  84909. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84910. defines.push("#define DIFFUSEUV1");
  84911. uv1 = true;
  84912. }
  84913. }
  84914. }
  84915. // Emissive
  84916. if (emissiveTexture) {
  84917. defines.push("#define EMISSIVE");
  84918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84919. emissiveTexture.coordinatesIndex === 1) {
  84920. defines.push("#define EMISSIVEUV2");
  84921. uv2 = true;
  84922. }
  84923. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84924. defines.push("#define EMISSIVEUV1");
  84925. uv1 = true;
  84926. }
  84927. }
  84928. if (uv1) {
  84929. attribs.push(BABYLON.VertexBuffer.UVKind);
  84930. defines.push("#define UV1");
  84931. }
  84932. if (uv2) {
  84933. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84934. defines.push("#define UV2");
  84935. }
  84936. // Bones
  84937. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84938. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84939. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84940. if (mesh.numBoneInfluencers > 4) {
  84941. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84942. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84943. }
  84944. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84945. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  84946. }
  84947. else {
  84948. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84949. }
  84950. // Instances
  84951. if (useInstances) {
  84952. defines.push("#define INSTANCES");
  84953. attribs.push("world0");
  84954. attribs.push("world1");
  84955. attribs.push("world2");
  84956. attribs.push("world3");
  84957. }
  84958. // Get correct effect
  84959. var join = defines.join("\n");
  84960. if (this._cachedDefines !== join) {
  84961. this._cachedDefines = join;
  84962. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  84963. }
  84964. return this._effectLayerMapGenerationEffect.isReady();
  84965. };
  84966. /**
  84967. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  84968. */
  84969. EffectLayer.prototype.render = function () {
  84970. var currentEffect = this._mergeEffect;
  84971. // Check
  84972. if (!currentEffect.isReady())
  84973. return;
  84974. for (var i = 0; i < this._postProcesses.length; i++) {
  84975. if (!this._postProcesses[i].isReady()) {
  84976. return;
  84977. }
  84978. }
  84979. var engine = this._scene.getEngine();
  84980. this.onBeforeComposeObservable.notifyObservers(this);
  84981. // Render
  84982. engine.enableEffect(currentEffect);
  84983. engine.setState(false);
  84984. // VBOs
  84985. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84986. // Cache
  84987. var previousAlphaMode = engine.getAlphaMode();
  84988. // Go Blend.
  84989. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  84990. // Blends the map on the main canvas.
  84991. this._internalRender(currentEffect);
  84992. // Restore Alpha
  84993. engine.setAlphaMode(previousAlphaMode);
  84994. this.onAfterComposeObservable.notifyObservers(this);
  84995. // Handle size changes.
  84996. var size = this._mainTexture.getSize();
  84997. this._setMainTextureSize();
  84998. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  84999. // Recreate RTT and post processes on size change.
  85000. this.onSizeChangedObservable.notifyObservers(this);
  85001. this._disposeTextureAndPostProcesses();
  85002. this._createMainTexture();
  85003. this._createTextureAndPostProcesses();
  85004. }
  85005. };
  85006. /**
  85007. * Determine if a given mesh will be used in the current effect.
  85008. * @param mesh mesh to test
  85009. * @returns true if the mesh will be used
  85010. */
  85011. EffectLayer.prototype.hasMesh = function (mesh) {
  85012. return true;
  85013. };
  85014. /**
  85015. * Returns true if the layer contains information to display, otherwise false.
  85016. * @returns true if the glow layer should be rendered
  85017. */
  85018. EffectLayer.prototype.shouldRender = function () {
  85019. return this.isEnabled && this._shouldRender;
  85020. };
  85021. /**
  85022. * Returns true if the mesh should render, otherwise false.
  85023. * @param mesh The mesh to render
  85024. * @returns true if it should render otherwise false
  85025. */
  85026. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  85027. return true;
  85028. };
  85029. /**
  85030. * Returns true if the mesh should render, otherwise false.
  85031. * @param mesh The mesh to render
  85032. * @returns true if it should render otherwise false
  85033. */
  85034. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  85035. return true;
  85036. };
  85037. /**
  85038. * Renders the submesh passed in parameter to the generation map.
  85039. */
  85040. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  85041. var _this = this;
  85042. if (!this.shouldRender()) {
  85043. return;
  85044. }
  85045. var material = subMesh.getMaterial();
  85046. var mesh = subMesh.getRenderingMesh();
  85047. var scene = this._scene;
  85048. var engine = scene.getEngine();
  85049. if (!material) {
  85050. return;
  85051. }
  85052. // Do not block in blend mode.
  85053. if (material.needAlphaBlendingForMesh(mesh)) {
  85054. return;
  85055. }
  85056. // Culling
  85057. engine.setState(material.backFaceCulling);
  85058. // Managing instances
  85059. var batch = mesh._getInstancesRenderList(subMesh._id);
  85060. if (batch.mustReturn) {
  85061. return;
  85062. }
  85063. // Early Exit per mesh
  85064. if (!this._shouldRenderMesh(mesh)) {
  85065. return;
  85066. }
  85067. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85068. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  85069. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  85070. engine.enableEffect(this._effectLayerMapGenerationEffect);
  85071. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  85072. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  85073. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  85074. // Alpha test
  85075. if (material && material.needAlphaTesting()) {
  85076. var alphaTexture = material.getAlphaTestTexture();
  85077. if (alphaTexture) {
  85078. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  85079. var textureMatrix = alphaTexture.getTextureMatrix();
  85080. if (textureMatrix) {
  85081. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  85082. }
  85083. }
  85084. }
  85085. // Glow emissive only
  85086. if (this._emissiveTextureAndColor.texture) {
  85087. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  85088. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  85089. }
  85090. // Bones
  85091. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85092. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85093. }
  85094. // Draw
  85095. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  85096. }
  85097. else {
  85098. // Need to reset refresh rate of the shadowMap
  85099. this._mainTexture.resetRefreshCounter();
  85100. }
  85101. };
  85102. /**
  85103. * Rebuild the required buffers.
  85104. * @ignore Internal use only.
  85105. */
  85106. EffectLayer.prototype._rebuild = function () {
  85107. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85108. if (vb) {
  85109. vb._rebuild();
  85110. }
  85111. this._generateIndexBuffer();
  85112. };
  85113. /**
  85114. * Dispose only the render target textures and post process.
  85115. */
  85116. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  85117. this._mainTexture.dispose();
  85118. for (var i = 0; i < this._postProcesses.length; i++) {
  85119. if (this._postProcesses[i]) {
  85120. this._postProcesses[i].dispose();
  85121. }
  85122. }
  85123. this._postProcesses = [];
  85124. for (var i = 0; i < this._textures.length; i++) {
  85125. if (this._textures[i]) {
  85126. this._textures[i].dispose();
  85127. }
  85128. }
  85129. this._textures = [];
  85130. };
  85131. /**
  85132. * Dispose the highlight layer and free resources.
  85133. */
  85134. EffectLayer.prototype.dispose = function () {
  85135. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85136. if (vertexBuffer) {
  85137. vertexBuffer.dispose();
  85138. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85139. }
  85140. if (this._indexBuffer) {
  85141. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85142. this._indexBuffer = null;
  85143. }
  85144. // Clean textures and post processes
  85145. this._disposeTextureAndPostProcesses();
  85146. // Remove from scene
  85147. var index = this._scene.effectLayers.indexOf(this, 0);
  85148. if (index > -1) {
  85149. this._scene.effectLayers.splice(index, 1);
  85150. }
  85151. // Callback
  85152. this.onDisposeObservable.notifyObservers(this);
  85153. this.onDisposeObservable.clear();
  85154. this.onBeforeRenderMainTextureObservable.clear();
  85155. this.onBeforeComposeObservable.clear();
  85156. this.onAfterComposeObservable.clear();
  85157. this.onSizeChangedObservable.clear();
  85158. };
  85159. return EffectLayer;
  85160. }());
  85161. BABYLON.EffectLayer = EffectLayer;
  85162. })(BABYLON || (BABYLON = {}));
  85163. //# sourceMappingURL=babylon.effectLayer.js.map
  85164. var BABYLON;
  85165. (function (BABYLON) {
  85166. /**
  85167. * Special Glow Blur post process only blurring the alpha channel
  85168. * It enforces keeping the most luminous color in the color channel.
  85169. */
  85170. var GlowBlurPostProcess = /** @class */ (function (_super) {
  85171. __extends(GlowBlurPostProcess, _super);
  85172. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  85173. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85174. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  85175. _this.direction = direction;
  85176. _this.kernel = kernel;
  85177. _this.onApplyObservable.add(function (effect) {
  85178. effect.setFloat2("screenSize", _this.width, _this.height);
  85179. effect.setVector2("direction", _this.direction);
  85180. effect.setFloat("blurWidth", _this.kernel);
  85181. });
  85182. return _this;
  85183. }
  85184. return GlowBlurPostProcess;
  85185. }(BABYLON.PostProcess));
  85186. /**
  85187. * The highlight layer Helps adding a glow effect around a mesh.
  85188. *
  85189. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85190. * glowy meshes to your scene.
  85191. *
  85192. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  85193. */
  85194. var HighlightLayer = /** @class */ (function (_super) {
  85195. __extends(HighlightLayer, _super);
  85196. /**
  85197. * Instantiates a new highlight Layer and references it to the scene..
  85198. * @param name The name of the layer
  85199. * @param scene The scene to use the layer in
  85200. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  85201. */
  85202. function HighlightLayer(name, scene, options) {
  85203. var _this = _super.call(this, name, scene) || this;
  85204. _this.name = name;
  85205. /**
  85206. * Specifies whether or not the inner glow is ACTIVE in the layer.
  85207. */
  85208. _this.innerGlow = true;
  85209. /**
  85210. * Specifies whether or not the outer glow is ACTIVE in the layer.
  85211. */
  85212. _this.outerGlow = true;
  85213. /**
  85214. * An event triggered when the highlight layer is being blurred.
  85215. */
  85216. _this.onBeforeBlurObservable = new BABYLON.Observable();
  85217. /**
  85218. * An event triggered when the highlight layer has been blurred.
  85219. */
  85220. _this.onAfterBlurObservable = new BABYLON.Observable();
  85221. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  85222. _this._meshes = {};
  85223. _this._excludedMeshes = {};
  85224. _this.neutralColor = HighlightLayer.NeutralColor;
  85225. // Warn on stencil
  85226. if (!_this._engine.isStencilEnable) {
  85227. 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 }");
  85228. }
  85229. // Adapt options
  85230. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85231. // Initialize the layer
  85232. _this._init({
  85233. alphaBlendingMode: _this._options.alphaBlendingMode,
  85234. camera: _this._options.camera,
  85235. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85236. mainTextureRatio: _this._options.mainTextureRatio
  85237. });
  85238. // Do not render as long as no meshes have been added
  85239. _this._shouldRender = false;
  85240. return _this;
  85241. }
  85242. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  85243. /**
  85244. * Gets the horizontal size of the blur.
  85245. */
  85246. get: function () {
  85247. return this._horizontalBlurPostprocess.kernel;
  85248. },
  85249. /**
  85250. * Specifies the horizontal size of the blur.
  85251. */
  85252. set: function (value) {
  85253. this._horizontalBlurPostprocess.kernel = value;
  85254. },
  85255. enumerable: true,
  85256. configurable: true
  85257. });
  85258. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  85259. /**
  85260. * Gets the vertical size of the blur.
  85261. */
  85262. get: function () {
  85263. return this._verticalBlurPostprocess.kernel;
  85264. },
  85265. /**
  85266. * Specifies the vertical size of the blur.
  85267. */
  85268. set: function (value) {
  85269. this._verticalBlurPostprocess.kernel = value;
  85270. },
  85271. enumerable: true,
  85272. configurable: true
  85273. });
  85274. /**
  85275. * Get the effect name of the layer.
  85276. * @return The effect name
  85277. */
  85278. HighlightLayer.prototype.getEffectName = function () {
  85279. return HighlightLayer.EffectName;
  85280. };
  85281. /**
  85282. * Create the merge effect. This is the shader use to blit the information back
  85283. * to the main canvas at the end of the scene rendering.
  85284. */
  85285. HighlightLayer.prototype._createMergeEffect = function () {
  85286. // Effect
  85287. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  85288. };
  85289. /**
  85290. * Creates the render target textures and post processes used in the highlight layer.
  85291. */
  85292. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  85293. var _this = this;
  85294. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  85295. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  85296. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85297. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85298. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  85299. width: blurTextureWidth,
  85300. height: blurTextureHeight
  85301. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85302. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85303. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85304. this._blurTexture.anisotropicFilteringLevel = 16;
  85305. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85306. this._blurTexture.renderParticles = false;
  85307. this._blurTexture.ignoreCameraViewport = true;
  85308. this._textures = [this._blurTexture];
  85309. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  85310. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85311. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  85312. effect.setTexture("textureSampler", _this._mainTexture);
  85313. });
  85314. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85315. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85316. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85317. });
  85318. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85319. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  85320. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85321. });
  85322. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85323. }
  85324. else {
  85325. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  85326. width: blurTextureWidth,
  85327. height: blurTextureHeight
  85328. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85329. this._horizontalBlurPostprocess.width = blurTextureWidth;
  85330. this._horizontalBlurPostprocess.height = blurTextureHeight;
  85331. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85332. effect.setTexture("textureSampler", _this._mainTexture);
  85333. });
  85334. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  85335. width: blurTextureWidth,
  85336. height: blurTextureHeight
  85337. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85338. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85339. }
  85340. this._mainTexture.onAfterUnbindObservable.add(function () {
  85341. _this.onBeforeBlurObservable.notifyObservers(_this);
  85342. var internalTexture = _this._blurTexture.getInternalTexture();
  85343. if (internalTexture) {
  85344. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  85345. }
  85346. _this.onAfterBlurObservable.notifyObservers(_this);
  85347. });
  85348. // Prevent autoClear.
  85349. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85350. };
  85351. /**
  85352. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85353. */
  85354. HighlightLayer.prototype.needStencil = function () {
  85355. return true;
  85356. };
  85357. /**
  85358. * Checks for the readiness of the element composing the layer.
  85359. * @param subMesh the mesh to check for
  85360. * @param useInstances specify wether or not to use instances to render the mesh
  85361. * @param emissiveTexture the associated emissive texture used to generate the glow
  85362. * @return true if ready otherwise, false
  85363. */
  85364. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  85365. var material = subMesh.getMaterial();
  85366. var mesh = subMesh.getRenderingMesh();
  85367. if (!material || !mesh || !this._meshes) {
  85368. return false;
  85369. }
  85370. var emissiveTexture = null;
  85371. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85372. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85373. emissiveTexture = material.emissiveTexture;
  85374. }
  85375. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85376. };
  85377. /**
  85378. * Implementation specific of rendering the generating effect on the main canvas.
  85379. * @param effect The effect used to render through
  85380. */
  85381. HighlightLayer.prototype._internalRender = function (effect) {
  85382. // Texture
  85383. effect.setTexture("textureSampler", this._blurTexture);
  85384. // Cache
  85385. var engine = this._engine;
  85386. var previousStencilBuffer = engine.getStencilBuffer();
  85387. var previousStencilFunction = engine.getStencilFunction();
  85388. var previousStencilMask = engine.getStencilMask();
  85389. var previousStencilOperationPass = engine.getStencilOperationPass();
  85390. var previousStencilOperationFail = engine.getStencilOperationFail();
  85391. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  85392. var previousStencilReference = engine.getStencilFunctionReference();
  85393. // Stencil operations
  85394. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  85395. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  85396. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  85397. // Draw order
  85398. engine.setStencilMask(0x00);
  85399. engine.setStencilBuffer(true);
  85400. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  85401. // 2 passes inner outer
  85402. if (this.outerGlow) {
  85403. effect.setFloat("offset", 0);
  85404. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  85405. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85406. }
  85407. if (this.innerGlow) {
  85408. effect.setFloat("offset", 1);
  85409. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  85410. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85411. }
  85412. // Restore Cache
  85413. engine.setStencilFunction(previousStencilFunction);
  85414. engine.setStencilMask(previousStencilMask);
  85415. engine.setStencilBuffer(previousStencilBuffer);
  85416. engine.setStencilOperationPass(previousStencilOperationPass);
  85417. engine.setStencilOperationFail(previousStencilOperationFail);
  85418. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  85419. engine.setStencilFunctionReference(previousStencilReference);
  85420. };
  85421. /**
  85422. * Returns true if the layer contains information to display, otherwise false.
  85423. */
  85424. HighlightLayer.prototype.shouldRender = function () {
  85425. if (_super.prototype.shouldRender.call(this)) {
  85426. return this._meshes ? true : false;
  85427. }
  85428. return false;
  85429. };
  85430. /**
  85431. * Returns true if the mesh should render, otherwise false.
  85432. * @param mesh The mesh to render
  85433. * @returns true if it should render otherwise false
  85434. */
  85435. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  85436. // Excluded Mesh
  85437. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  85438. return false;
  85439. }
  85440. ;
  85441. return true;
  85442. };
  85443. /**
  85444. * Sets the required values for both the emissive texture and and the main color.
  85445. */
  85446. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85447. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85448. if (highlightLayerMesh) {
  85449. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  85450. }
  85451. else {
  85452. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85453. }
  85454. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85455. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85456. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  85457. }
  85458. else {
  85459. this._emissiveTextureAndColor.texture = null;
  85460. }
  85461. };
  85462. /**
  85463. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  85464. * @param mesh The mesh to exclude from the highlight layer
  85465. */
  85466. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  85467. if (!this._excludedMeshes) {
  85468. return;
  85469. }
  85470. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85471. if (!meshExcluded) {
  85472. this._excludedMeshes[mesh.uniqueId] = {
  85473. mesh: mesh,
  85474. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  85475. mesh.getEngine().setStencilBuffer(false);
  85476. }),
  85477. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  85478. mesh.getEngine().setStencilBuffer(true);
  85479. }),
  85480. };
  85481. }
  85482. };
  85483. /**
  85484. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  85485. * @param mesh The mesh to highlight
  85486. */
  85487. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  85488. if (!this._excludedMeshes) {
  85489. return;
  85490. }
  85491. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85492. if (meshExcluded) {
  85493. if (meshExcluded.beforeRender) {
  85494. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  85495. }
  85496. if (meshExcluded.afterRender) {
  85497. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  85498. }
  85499. }
  85500. this._excludedMeshes[mesh.uniqueId] = null;
  85501. };
  85502. /**
  85503. * Determine if a given mesh will be highlighted by the current HighlightLayer
  85504. * @param mesh mesh to test
  85505. * @returns true if the mesh will be highlighted by the current HighlightLayer
  85506. */
  85507. HighlightLayer.prototype.hasMesh = function (mesh) {
  85508. if (!this._meshes) {
  85509. return false;
  85510. }
  85511. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  85512. };
  85513. /**
  85514. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  85515. * @param mesh The mesh to highlight
  85516. * @param color The color of the highlight
  85517. * @param glowEmissiveOnly Extract the glow from the emissive texture
  85518. */
  85519. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  85520. var _this = this;
  85521. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  85522. if (!this._meshes) {
  85523. return;
  85524. }
  85525. var meshHighlight = this._meshes[mesh.uniqueId];
  85526. if (meshHighlight) {
  85527. meshHighlight.color = color;
  85528. }
  85529. else {
  85530. this._meshes[mesh.uniqueId] = {
  85531. mesh: mesh,
  85532. color: color,
  85533. // Lambda required for capture due to Observable this context
  85534. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  85535. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  85536. _this._defaultStencilReference(mesh);
  85537. }
  85538. else {
  85539. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  85540. }
  85541. }),
  85542. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  85543. glowEmissiveOnly: glowEmissiveOnly
  85544. };
  85545. }
  85546. this._shouldRender = true;
  85547. };
  85548. /**
  85549. * Remove a mesh from the highlight layer in order to make it stop glowing.
  85550. * @param mesh The mesh to highlight
  85551. */
  85552. HighlightLayer.prototype.removeMesh = function (mesh) {
  85553. if (!this._meshes) {
  85554. return;
  85555. }
  85556. var meshHighlight = this._meshes[mesh.uniqueId];
  85557. if (meshHighlight) {
  85558. if (meshHighlight.observerHighlight) {
  85559. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85560. }
  85561. if (meshHighlight.observerDefault) {
  85562. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85563. }
  85564. delete this._meshes[mesh.uniqueId];
  85565. }
  85566. this._shouldRender = false;
  85567. for (var meshHighlightToCheck in this._meshes) {
  85568. if (this._meshes[meshHighlightToCheck]) {
  85569. this._shouldRender = true;
  85570. break;
  85571. }
  85572. }
  85573. };
  85574. /**
  85575. * Force the stencil to the normal expected value for none glowing parts
  85576. */
  85577. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  85578. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  85579. };
  85580. /**
  85581. * Free any resources and references associated to a mesh.
  85582. * Internal use
  85583. * @param mesh The mesh to free.
  85584. */
  85585. HighlightLayer.prototype._disposeMesh = function (mesh) {
  85586. this.removeMesh(mesh);
  85587. this.removeExcludedMesh(mesh);
  85588. };
  85589. /**
  85590. * Dispose the highlight layer and free resources.
  85591. */
  85592. HighlightLayer.prototype.dispose = function () {
  85593. if (this._meshes) {
  85594. // Clean mesh references
  85595. for (var id in this._meshes) {
  85596. var meshHighlight = this._meshes[id];
  85597. if (meshHighlight && meshHighlight.mesh) {
  85598. if (meshHighlight.observerHighlight) {
  85599. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85600. }
  85601. if (meshHighlight.observerDefault) {
  85602. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85603. }
  85604. }
  85605. }
  85606. this._meshes = null;
  85607. }
  85608. if (this._excludedMeshes) {
  85609. for (var id in this._excludedMeshes) {
  85610. var meshHighlight = this._excludedMeshes[id];
  85611. if (meshHighlight) {
  85612. if (meshHighlight.beforeRender) {
  85613. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  85614. }
  85615. if (meshHighlight.afterRender) {
  85616. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  85617. }
  85618. }
  85619. }
  85620. this._excludedMeshes = null;
  85621. }
  85622. _super.prototype.dispose.call(this);
  85623. };
  85624. /**
  85625. * Effect Name of the highlight layer.
  85626. */
  85627. HighlightLayer.EffectName = "HighlightLayer";
  85628. /**
  85629. * The neutral color used during the preparation of the glow effect.
  85630. * This is black by default as the blend operation is a blend operation.
  85631. */
  85632. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  85633. /**
  85634. * Stencil value used for glowing meshes.
  85635. */
  85636. HighlightLayer.GlowingMeshStencilReference = 0x02;
  85637. /**
  85638. * Stencil value used for the other meshes in the scene.
  85639. */
  85640. HighlightLayer.NormalMeshStencilReference = 0x01;
  85641. return HighlightLayer;
  85642. }(BABYLON.EffectLayer));
  85643. BABYLON.HighlightLayer = HighlightLayer;
  85644. })(BABYLON || (BABYLON = {}));
  85645. //# sourceMappingURL=babylon.highlightLayer.js.map
  85646. var BABYLON;
  85647. (function (BABYLON) {
  85648. /**
  85649. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  85650. *
  85651. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85652. * glowy meshes to your scene.
  85653. *
  85654. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  85655. */
  85656. var GlowLayer = /** @class */ (function (_super) {
  85657. __extends(GlowLayer, _super);
  85658. /**
  85659. * Instantiates a new glow Layer and references it to the scene.
  85660. * @param name The name of the layer
  85661. * @param scene The scene to use the layer in
  85662. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  85663. */
  85664. function GlowLayer(name, scene, options) {
  85665. var _this = _super.call(this, name, scene) || this;
  85666. _this.name = name;
  85667. _this._intensity = 1.0;
  85668. _this._includedOnlyMeshes = [];
  85669. _this._excludedMeshes = [];
  85670. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  85671. // Adapt options
  85672. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  85673. // Initialize the layer
  85674. _this._init({
  85675. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  85676. camera: _this._options.camera,
  85677. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85678. mainTextureRatio: _this._options.mainTextureRatio
  85679. });
  85680. return _this;
  85681. }
  85682. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  85683. /**
  85684. * Gets the kernel size of the blur.
  85685. */
  85686. get: function () {
  85687. return this._horizontalBlurPostprocess1.kernel;
  85688. },
  85689. /**
  85690. * Sets the kernel size of the blur.
  85691. */
  85692. set: function (value) {
  85693. this._horizontalBlurPostprocess1.kernel = value;
  85694. this._verticalBlurPostprocess1.kernel = value;
  85695. this._horizontalBlurPostprocess2.kernel = value;
  85696. this._verticalBlurPostprocess2.kernel = value;
  85697. },
  85698. enumerable: true,
  85699. configurable: true
  85700. });
  85701. Object.defineProperty(GlowLayer.prototype, "intensity", {
  85702. /**
  85703. * Gets the glow intensity.
  85704. */
  85705. get: function () {
  85706. return this._intensity;
  85707. },
  85708. /**
  85709. * Sets the glow intensity.
  85710. */
  85711. set: function (value) {
  85712. this._intensity = value;
  85713. },
  85714. enumerable: true,
  85715. configurable: true
  85716. });
  85717. /**
  85718. * Get the effect name of the layer.
  85719. * @return The effect name
  85720. */
  85721. GlowLayer.prototype.getEffectName = function () {
  85722. return GlowLayer.EffectName;
  85723. };
  85724. /**
  85725. * Create the merge effect. This is the shader use to blit the information back
  85726. * to the main canvas at the end of the scene rendering.
  85727. */
  85728. GlowLayer.prototype._createMergeEffect = function () {
  85729. // Effect
  85730. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  85731. };
  85732. /**
  85733. * Creates the render target textures and post processes used in the glow layer.
  85734. */
  85735. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  85736. var _this = this;
  85737. var blurTextureWidth = this._mainTextureDesiredSize.width;
  85738. var blurTextureHeight = this._mainTextureDesiredSize.height;
  85739. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85740. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85741. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  85742. width: blurTextureWidth,
  85743. height: blurTextureHeight
  85744. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85745. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85746. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85747. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85748. this._blurTexture1.renderParticles = false;
  85749. this._blurTexture1.ignoreCameraViewport = true;
  85750. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  85751. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  85752. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  85753. width: blurTextureWidth2,
  85754. height: blurTextureHeight2
  85755. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85756. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85757. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85758. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85759. this._blurTexture2.renderParticles = false;
  85760. this._blurTexture2.ignoreCameraViewport = true;
  85761. this._textures = [this._blurTexture1, this._blurTexture2];
  85762. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85763. width: blurTextureWidth,
  85764. height: blurTextureHeight
  85765. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85766. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  85767. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  85768. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  85769. effect.setTexture("textureSampler", _this._mainTexture);
  85770. });
  85771. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85772. width: blurTextureWidth,
  85773. height: blurTextureHeight
  85774. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85775. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85776. width: blurTextureWidth2,
  85777. height: blurTextureHeight2
  85778. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85779. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  85780. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  85781. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  85782. effect.setTexture("textureSampler", _this._blurTexture1);
  85783. });
  85784. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85785. width: blurTextureWidth2,
  85786. height: blurTextureHeight2
  85787. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85788. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85789. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  85790. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85791. this._mainTexture.samples = this._options.mainTextureSamples;
  85792. this._mainTexture.onAfterUnbindObservable.add(function () {
  85793. var internalTexture = _this._blurTexture1.getInternalTexture();
  85794. if (internalTexture) {
  85795. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  85796. internalTexture = _this._blurTexture2.getInternalTexture();
  85797. if (internalTexture) {
  85798. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  85799. }
  85800. }
  85801. });
  85802. // Prevent autoClear.
  85803. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85804. };
  85805. /**
  85806. * Checks for the readiness of the element composing the layer.
  85807. * @param subMesh the mesh to check for
  85808. * @param useInstances specify wether or not to use instances to render the mesh
  85809. * @param emissiveTexture the associated emissive texture used to generate the glow
  85810. * @return true if ready otherwise, false
  85811. */
  85812. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  85813. var material = subMesh.getMaterial();
  85814. var mesh = subMesh.getRenderingMesh();
  85815. if (!material || !mesh) {
  85816. return false;
  85817. }
  85818. var emissiveTexture = material.emissiveTexture;
  85819. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85820. };
  85821. /**
  85822. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85823. */
  85824. GlowLayer.prototype.needStencil = function () {
  85825. return false;
  85826. };
  85827. /**
  85828. * Implementation specific of rendering the generating effect on the main canvas.
  85829. * @param effect The effect used to render through
  85830. */
  85831. GlowLayer.prototype._internalRender = function (effect) {
  85832. // Texture
  85833. effect.setTexture("textureSampler", this._blurTexture1);
  85834. effect.setTexture("textureSampler2", this._blurTexture2);
  85835. effect.setFloat("offset", this._intensity);
  85836. // Cache
  85837. var engine = this._engine;
  85838. var previousStencilBuffer = engine.getStencilBuffer();
  85839. // Draw order
  85840. engine.setStencilBuffer(false);
  85841. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85842. // Draw order
  85843. engine.setStencilBuffer(previousStencilBuffer);
  85844. };
  85845. /**
  85846. * Sets the required values for both the emissive texture and and the main color.
  85847. */
  85848. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85849. var textureLevel = 1.0;
  85850. if (this.customEmissiveTextureSelector) {
  85851. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  85852. }
  85853. else {
  85854. if (material) {
  85855. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85856. if (this._emissiveTextureAndColor.texture) {
  85857. textureLevel = this._emissiveTextureAndColor.texture.level;
  85858. }
  85859. }
  85860. else {
  85861. this._emissiveTextureAndColor.texture = null;
  85862. }
  85863. }
  85864. if (this.customEmissiveColorSelector) {
  85865. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  85866. }
  85867. else {
  85868. if (material.emissiveColor) {
  85869. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  85870. }
  85871. else {
  85872. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85873. }
  85874. }
  85875. };
  85876. /**
  85877. * Returns true if the mesh should render, otherwise false.
  85878. * @param mesh The mesh to render
  85879. * @returns true if it should render otherwise false
  85880. */
  85881. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  85882. return this.hasMesh(mesh);
  85883. };
  85884. /**
  85885. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  85886. * @param mesh The mesh to exclude from the glow layer
  85887. */
  85888. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  85889. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  85890. this._excludedMeshes.push(mesh.uniqueId);
  85891. }
  85892. };
  85893. /**
  85894. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  85895. * @param mesh The mesh to remove
  85896. */
  85897. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  85898. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  85899. if (index !== -1) {
  85900. this._excludedMeshes.splice(index, 1);
  85901. }
  85902. };
  85903. /**
  85904. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  85905. * @param mesh The mesh to include in the glow layer
  85906. */
  85907. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  85908. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  85909. this._includedOnlyMeshes.push(mesh.uniqueId);
  85910. }
  85911. };
  85912. /**
  85913. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  85914. * @param mesh The mesh to remove
  85915. */
  85916. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  85917. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  85918. if (index !== -1) {
  85919. this._includedOnlyMeshes.splice(index, 1);
  85920. }
  85921. };
  85922. /**
  85923. * Determine if a given mesh will be used in the glow layer
  85924. * @param mesh The mesh to test
  85925. * @returns true if the mesh will be highlighted by the current glow layer
  85926. */
  85927. GlowLayer.prototype.hasMesh = function (mesh) {
  85928. // Included Mesh
  85929. if (this._includedOnlyMeshes.length) {
  85930. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  85931. }
  85932. ;
  85933. // Excluded Mesh
  85934. if (this._excludedMeshes.length) {
  85935. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  85936. }
  85937. ;
  85938. return true;
  85939. };
  85940. /**
  85941. * Free any resources and references associated to a mesh.
  85942. * Internal use
  85943. * @param mesh The mesh to free.
  85944. */
  85945. GlowLayer.prototype._disposeMesh = function (mesh) {
  85946. this.removeIncludedOnlyMesh(mesh);
  85947. this.removeExcludedMesh(mesh);
  85948. };
  85949. /**
  85950. * Effect Name of the layer.
  85951. */
  85952. GlowLayer.EffectName = "GlowLayer";
  85953. /**
  85954. * The default blur kernel size used for the glow.
  85955. */
  85956. GlowLayer.DefaultBlurKernelSize = 32;
  85957. /**
  85958. * The default texture size ratio used for the glow.
  85959. */
  85960. GlowLayer.DefaultTextureRatio = 0.5;
  85961. return GlowLayer;
  85962. }(BABYLON.EffectLayer));
  85963. BABYLON.GlowLayer = GlowLayer;
  85964. })(BABYLON || (BABYLON = {}));
  85965. //# sourceMappingURL=babylon.glowLayer.js.map
  85966. var BABYLON;
  85967. (function (BABYLON) {
  85968. /**
  85969. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  85970. */
  85971. var AssetTaskState;
  85972. (function (AssetTaskState) {
  85973. /**
  85974. * Initialization
  85975. */
  85976. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  85977. /**
  85978. * Running
  85979. */
  85980. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  85981. /**
  85982. * Done
  85983. */
  85984. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  85985. /**
  85986. * Error
  85987. */
  85988. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  85989. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  85990. /**
  85991. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  85992. */
  85993. var AbstractAssetTask = /** @class */ (function () {
  85994. /**
  85995. * Creates a new {BABYLON.AssetsManager}
  85996. * @param name defines the name of the task
  85997. */
  85998. function AbstractAssetTask(
  85999. /**
  86000. * Task name
  86001. */ name) {
  86002. this.name = name;
  86003. this._isCompleted = false;
  86004. this._taskState = AssetTaskState.INIT;
  86005. }
  86006. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  86007. /**
  86008. * Get if the task is completed
  86009. */
  86010. get: function () {
  86011. return this._isCompleted;
  86012. },
  86013. enumerable: true,
  86014. configurable: true
  86015. });
  86016. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  86017. /**
  86018. * Gets the current state of the task
  86019. */
  86020. get: function () {
  86021. return this._taskState;
  86022. },
  86023. enumerable: true,
  86024. configurable: true
  86025. });
  86026. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  86027. /**
  86028. * Gets the current error object (if task is in error)
  86029. */
  86030. get: function () {
  86031. return this._errorObject;
  86032. },
  86033. enumerable: true,
  86034. configurable: true
  86035. });
  86036. /**
  86037. * Internal only
  86038. * @ignore
  86039. */
  86040. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  86041. if (this._errorObject) {
  86042. return;
  86043. }
  86044. this._errorObject = {
  86045. message: message,
  86046. exception: exception
  86047. };
  86048. };
  86049. /**
  86050. * Execute the current task
  86051. * @param scene defines the scene where you want your assets to be loaded
  86052. * @param onSuccess is a callback called when the task is successfully executed
  86053. * @param onError is a callback called if an error occurs
  86054. */
  86055. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86056. var _this = this;
  86057. this._taskState = AssetTaskState.RUNNING;
  86058. this.runTask(scene, function () {
  86059. _this.onDoneCallback(onSuccess, onError);
  86060. }, function (msg, exception) {
  86061. _this.onErrorCallback(onError, msg, exception);
  86062. });
  86063. };
  86064. /**
  86065. * Execute the current task
  86066. * @param scene defines the scene where you want your assets to be loaded
  86067. * @param onSuccess is a callback called when the task is successfully executed
  86068. * @param onError is a callback called if an error occurs
  86069. */
  86070. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86071. throw new Error("runTask is not implemented");
  86072. };
  86073. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  86074. this._taskState = AssetTaskState.ERROR;
  86075. this._errorObject = {
  86076. message: message,
  86077. exception: exception
  86078. };
  86079. if (this.onError) {
  86080. this.onError(this, message, exception);
  86081. }
  86082. onError();
  86083. };
  86084. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  86085. try {
  86086. this._taskState = AssetTaskState.DONE;
  86087. this._isCompleted = true;
  86088. if (this.onSuccess) {
  86089. this.onSuccess(this);
  86090. }
  86091. onSuccess();
  86092. }
  86093. catch (e) {
  86094. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  86095. }
  86096. };
  86097. return AbstractAssetTask;
  86098. }());
  86099. BABYLON.AbstractAssetTask = AbstractAssetTask;
  86100. /**
  86101. * Class used to share progress information about assets loading
  86102. */
  86103. var AssetsProgressEvent = /** @class */ (function () {
  86104. /**
  86105. * Creates a {BABYLON.AssetsProgressEvent}
  86106. * @param remainingCount defines the number of remaining tasks to process
  86107. * @param totalCount defines the total number of tasks
  86108. * @param task defines the task that was just processed
  86109. */
  86110. function AssetsProgressEvent(remainingCount, totalCount, task) {
  86111. this.remainingCount = remainingCount;
  86112. this.totalCount = totalCount;
  86113. this.task = task;
  86114. }
  86115. return AssetsProgressEvent;
  86116. }());
  86117. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  86118. /**
  86119. * Define a task used by {BABYLON.AssetsManager} to load meshes
  86120. */
  86121. var MeshAssetTask = /** @class */ (function (_super) {
  86122. __extends(MeshAssetTask, _super);
  86123. /**
  86124. * Creates a new {BABYLON.MeshAssetTask}
  86125. * @param name defines the name of the task
  86126. * @param meshesNames defines the list of mesh's names you want to load
  86127. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  86128. * @param sceneFilename defines the filename of the scene to load from
  86129. */
  86130. function MeshAssetTask(
  86131. /**
  86132. * Defines the name of the task
  86133. */
  86134. name,
  86135. /**
  86136. * Defines the list of mesh's names you want to load
  86137. */
  86138. meshesNames,
  86139. /**
  86140. * Defines the root url to use as a base to load your meshes and associated resources
  86141. */
  86142. rootUrl,
  86143. /**
  86144. * Defines the filename of the scene to load from
  86145. */
  86146. sceneFilename) {
  86147. var _this = _super.call(this, name) || this;
  86148. _this.name = name;
  86149. _this.meshesNames = meshesNames;
  86150. _this.rootUrl = rootUrl;
  86151. _this.sceneFilename = sceneFilename;
  86152. return _this;
  86153. }
  86154. /**
  86155. * Execute the current task
  86156. * @param scene defines the scene where you want your assets to be loaded
  86157. * @param onSuccess is a callback called when the task is successfully executed
  86158. * @param onError is a callback called if an error occurs
  86159. */
  86160. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86161. var _this = this;
  86162. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  86163. _this.loadedMeshes = meshes;
  86164. _this.loadedParticleSystems = particleSystems;
  86165. _this.loadedSkeletons = skeletons;
  86166. onSuccess();
  86167. }, null, function (scene, message, exception) {
  86168. onError(message, exception);
  86169. });
  86170. };
  86171. return MeshAssetTask;
  86172. }(AbstractAssetTask));
  86173. BABYLON.MeshAssetTask = MeshAssetTask;
  86174. /**
  86175. * Define a task used by {BABYLON.AssetsManager} to load text content
  86176. */
  86177. var TextFileAssetTask = /** @class */ (function (_super) {
  86178. __extends(TextFileAssetTask, _super);
  86179. /**
  86180. * Creates a new TextFileAssetTask object
  86181. * @param name defines the name of the task
  86182. * @param url defines the location of the file to load
  86183. */
  86184. function TextFileAssetTask(
  86185. /**
  86186. * Defines the name of the task
  86187. */
  86188. name,
  86189. /**
  86190. * Defines the location of the file to load
  86191. */
  86192. url) {
  86193. var _this = _super.call(this, name) || this;
  86194. _this.name = name;
  86195. _this.url = url;
  86196. return _this;
  86197. }
  86198. /**
  86199. * Execute the current task
  86200. * @param scene defines the scene where you want your assets to be loaded
  86201. * @param onSuccess is a callback called when the task is successfully executed
  86202. * @param onError is a callback called if an error occurs
  86203. */
  86204. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86205. var _this = this;
  86206. scene._loadFile(this.url, function (data) {
  86207. _this.text = data;
  86208. onSuccess();
  86209. }, undefined, false, false, function (request, exception) {
  86210. if (request) {
  86211. onError(request.status + " " + request.statusText, exception);
  86212. }
  86213. });
  86214. };
  86215. return TextFileAssetTask;
  86216. }(AbstractAssetTask));
  86217. BABYLON.TextFileAssetTask = TextFileAssetTask;
  86218. /**
  86219. * Define a task used by {BABYLON.AssetsManager} to load binary data
  86220. */
  86221. var BinaryFileAssetTask = /** @class */ (function (_super) {
  86222. __extends(BinaryFileAssetTask, _super);
  86223. /**
  86224. * Creates a new BinaryFileAssetTask object
  86225. * @param name defines the name of the new task
  86226. * @param url defines the location of the file to load
  86227. */
  86228. function BinaryFileAssetTask(
  86229. /**
  86230. * Defines the name of the task
  86231. */
  86232. name,
  86233. /**
  86234. * Defines the location of the file to load
  86235. */
  86236. url) {
  86237. var _this = _super.call(this, name) || this;
  86238. _this.name = name;
  86239. _this.url = url;
  86240. return _this;
  86241. }
  86242. /**
  86243. * Execute the current task
  86244. * @param scene defines the scene where you want your assets to be loaded
  86245. * @param onSuccess is a callback called when the task is successfully executed
  86246. * @param onError is a callback called if an error occurs
  86247. */
  86248. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86249. var _this = this;
  86250. scene._loadFile(this.url, function (data) {
  86251. _this.data = data;
  86252. onSuccess();
  86253. }, undefined, true, true, function (request, exception) {
  86254. if (request) {
  86255. onError(request.status + " " + request.statusText, exception);
  86256. }
  86257. });
  86258. };
  86259. return BinaryFileAssetTask;
  86260. }(AbstractAssetTask));
  86261. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  86262. /**
  86263. * Define a task used by {BABYLON.AssetsManager} to load images
  86264. */
  86265. var ImageAssetTask = /** @class */ (function (_super) {
  86266. __extends(ImageAssetTask, _super);
  86267. /**
  86268. * Creates a new ImageAssetTask
  86269. * @param name defines the name of the task
  86270. * @param url defines the location of the image to load
  86271. */
  86272. function ImageAssetTask(
  86273. /**
  86274. * Defines the name of the task
  86275. */
  86276. name,
  86277. /**
  86278. * Defines the location of the image to load
  86279. */
  86280. url) {
  86281. var _this = _super.call(this, name) || this;
  86282. _this.name = name;
  86283. _this.url = url;
  86284. return _this;
  86285. }
  86286. /**
  86287. * Execute the current task
  86288. * @param scene defines the scene where you want your assets to be loaded
  86289. * @param onSuccess is a callback called when the task is successfully executed
  86290. * @param onError is a callback called if an error occurs
  86291. */
  86292. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86293. var _this = this;
  86294. var img = new Image();
  86295. BABYLON.Tools.SetCorsBehavior(this.url, img);
  86296. img.onload = function () {
  86297. _this.image = img;
  86298. onSuccess();
  86299. };
  86300. img.onerror = function (err) {
  86301. onError("Error loading image", err);
  86302. };
  86303. img.src = this.url;
  86304. };
  86305. return ImageAssetTask;
  86306. }(AbstractAssetTask));
  86307. BABYLON.ImageAssetTask = ImageAssetTask;
  86308. /**
  86309. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  86310. */
  86311. var TextureAssetTask = /** @class */ (function (_super) {
  86312. __extends(TextureAssetTask, _super);
  86313. /**
  86314. * Creates a new TextureAssetTask object
  86315. * @param name defines the name of the task
  86316. * @param url defines the location of the file to load
  86317. * @param noMipmap defines if mipmap should not be generated (default is false)
  86318. * @param invertY defines if texture must be inverted on Y axis (default is false)
  86319. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86320. */
  86321. function TextureAssetTask(
  86322. /**
  86323. * Defines the name of the task
  86324. */
  86325. name,
  86326. /**
  86327. * Defines the location of the file to load
  86328. */
  86329. url,
  86330. /**
  86331. * Defines if mipmap should not be generated (default is false)
  86332. */
  86333. noMipmap,
  86334. /**
  86335. * Defines if texture must be inverted on Y axis (default is false)
  86336. */
  86337. invertY,
  86338. /**
  86339. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86340. */
  86341. samplingMode) {
  86342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86343. var _this = _super.call(this, name) || this;
  86344. _this.name = name;
  86345. _this.url = url;
  86346. _this.noMipmap = noMipmap;
  86347. _this.invertY = invertY;
  86348. _this.samplingMode = samplingMode;
  86349. return _this;
  86350. }
  86351. /**
  86352. * Execute the current task
  86353. * @param scene defines the scene where you want your assets to be loaded
  86354. * @param onSuccess is a callback called when the task is successfully executed
  86355. * @param onError is a callback called if an error occurs
  86356. */
  86357. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86358. var onload = function () {
  86359. onSuccess();
  86360. };
  86361. var onerror = function (message, exception) {
  86362. onError(message, exception);
  86363. };
  86364. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  86365. };
  86366. return TextureAssetTask;
  86367. }(AbstractAssetTask));
  86368. BABYLON.TextureAssetTask = TextureAssetTask;
  86369. /**
  86370. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  86371. */
  86372. var CubeTextureAssetTask = /** @class */ (function (_super) {
  86373. __extends(CubeTextureAssetTask, _super);
  86374. /**
  86375. * Creates a new CubeTextureAssetTask
  86376. * @param name defines the name of the task
  86377. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86378. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86379. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86380. * @param files defines the explicit list of files (undefined by default)
  86381. */
  86382. function CubeTextureAssetTask(
  86383. /**
  86384. * Defines the name of the task
  86385. */
  86386. name,
  86387. /**
  86388. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86389. */
  86390. url,
  86391. /**
  86392. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86393. */
  86394. extensions,
  86395. /**
  86396. * Defines if mipmaps should not be generated (default is false)
  86397. */
  86398. noMipmap,
  86399. /**
  86400. * Defines the explicit list of files (undefined by default)
  86401. */
  86402. files) {
  86403. var _this = _super.call(this, name) || this;
  86404. _this.name = name;
  86405. _this.url = url;
  86406. _this.extensions = extensions;
  86407. _this.noMipmap = noMipmap;
  86408. _this.files = files;
  86409. return _this;
  86410. }
  86411. /**
  86412. * Execute the current task
  86413. * @param scene defines the scene where you want your assets to be loaded
  86414. * @param onSuccess is a callback called when the task is successfully executed
  86415. * @param onError is a callback called if an error occurs
  86416. */
  86417. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86418. var onload = function () {
  86419. onSuccess();
  86420. };
  86421. var onerror = function (message, exception) {
  86422. onError(message, exception);
  86423. };
  86424. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  86425. };
  86426. return CubeTextureAssetTask;
  86427. }(AbstractAssetTask));
  86428. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  86429. /**
  86430. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  86431. */
  86432. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  86433. __extends(HDRCubeTextureAssetTask, _super);
  86434. /**
  86435. * Creates a new HDRCubeTextureAssetTask object
  86436. * @param name defines the name of the task
  86437. * @param url defines the location of the file to load
  86438. * @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.
  86439. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86440. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86441. * @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)
  86442. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86443. */
  86444. function HDRCubeTextureAssetTask(
  86445. /**
  86446. * Defines the name of the task
  86447. */
  86448. name,
  86449. /**
  86450. * Defines the location of the file to load
  86451. */
  86452. url,
  86453. /**
  86454. * 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.
  86455. */
  86456. size,
  86457. /**
  86458. * Defines if mipmaps should not be generated (default is false)
  86459. */
  86460. noMipmap,
  86461. /**
  86462. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86463. */
  86464. generateHarmonics,
  86465. /**
  86466. * 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)
  86467. */
  86468. useInGammaSpace,
  86469. /**
  86470. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86471. */
  86472. usePMREMGenerator) {
  86473. if (noMipmap === void 0) { noMipmap = false; }
  86474. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86475. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86476. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86477. var _this = _super.call(this, name) || this;
  86478. _this.name = name;
  86479. _this.url = url;
  86480. _this.size = size;
  86481. _this.noMipmap = noMipmap;
  86482. _this.generateHarmonics = generateHarmonics;
  86483. _this.useInGammaSpace = useInGammaSpace;
  86484. _this.usePMREMGenerator = usePMREMGenerator;
  86485. return _this;
  86486. }
  86487. /**
  86488. * Execute the current task
  86489. * @param scene defines the scene where you want your assets to be loaded
  86490. * @param onSuccess is a callback called when the task is successfully executed
  86491. * @param onError is a callback called if an error occurs
  86492. */
  86493. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86494. var onload = function () {
  86495. onSuccess();
  86496. };
  86497. var onerror = function (message, exception) {
  86498. onError(message, exception);
  86499. };
  86500. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  86501. };
  86502. return HDRCubeTextureAssetTask;
  86503. }(AbstractAssetTask));
  86504. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  86505. /**
  86506. * This class can be used to easily import assets into a scene
  86507. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  86508. */
  86509. var AssetsManager = /** @class */ (function () {
  86510. /**
  86511. * Creates a new AssetsManager
  86512. * @param scene defines the scene to work on
  86513. */
  86514. function AssetsManager(scene) {
  86515. this._isLoading = false;
  86516. this._tasks = new Array();
  86517. this._waitingTasksCount = 0;
  86518. this._totalTasksCount = 0;
  86519. /**
  86520. * Observable called when all tasks are processed
  86521. */
  86522. this.onTaskSuccessObservable = new BABYLON.Observable();
  86523. /**
  86524. * Observable called when a task had an error
  86525. */
  86526. this.onTaskErrorObservable = new BABYLON.Observable();
  86527. /**
  86528. * Observable called when a task is successful
  86529. */
  86530. this.onTasksDoneObservable = new BABYLON.Observable();
  86531. /**
  86532. * Observable called when a task is done (whatever the result is)
  86533. */
  86534. this.onProgressObservable = new BABYLON.Observable();
  86535. /**
  86536. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  86537. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  86538. */
  86539. this.useDefaultLoadingScreen = true;
  86540. this._scene = scene;
  86541. }
  86542. /**
  86543. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  86544. * @param taskName defines the name of the new task
  86545. * @param meshesNames defines the name of meshes to load
  86546. * @param rootUrl defines the root url to use to locate files
  86547. * @param sceneFilename defines the filename of the scene file
  86548. * @returns a new {BABYLON.MeshAssetTask} object
  86549. */
  86550. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  86551. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  86552. this._tasks.push(task);
  86553. return task;
  86554. };
  86555. /**
  86556. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  86557. * @param taskName defines the name of the new task
  86558. * @param url defines the url of the file to load
  86559. * @returns a new {BABYLON.TextFileAssetTask} object
  86560. */
  86561. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  86562. var task = new TextFileAssetTask(taskName, url);
  86563. this._tasks.push(task);
  86564. return task;
  86565. };
  86566. /**
  86567. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  86568. * @param taskName defines the name of the new task
  86569. * @param url defines the url of the file to load
  86570. * @returns a new {BABYLON.BinaryFileAssetTask} object
  86571. */
  86572. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  86573. var task = new BinaryFileAssetTask(taskName, url);
  86574. this._tasks.push(task);
  86575. return task;
  86576. };
  86577. /**
  86578. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  86579. * @param taskName defines the name of the new task
  86580. * @param url defines the url of the file to load
  86581. * @returns a new {BABYLON.ImageAssetTask} object
  86582. */
  86583. AssetsManager.prototype.addImageTask = function (taskName, url) {
  86584. var task = new ImageAssetTask(taskName, url);
  86585. this._tasks.push(task);
  86586. return task;
  86587. };
  86588. /**
  86589. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  86590. * @param taskName defines the name of the new task
  86591. * @param url defines the url of the file to load
  86592. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86593. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  86594. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  86595. * @returns a new {BABYLON.TextureAssetTask} object
  86596. */
  86597. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  86598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86599. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  86600. this._tasks.push(task);
  86601. return task;
  86602. };
  86603. /**
  86604. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  86605. * @param taskName defines the name of the new task
  86606. * @param url defines the url of the file to load
  86607. * @param extensions defines the extension to use to load the cube map (can be null)
  86608. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86609. * @param files defines the list of files to load (can be null)
  86610. * @returns a new {BABYLON.CubeTextureAssetTask} object
  86611. */
  86612. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  86613. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  86614. this._tasks.push(task);
  86615. return task;
  86616. };
  86617. /**
  86618. *
  86619. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  86620. * @param taskName defines the name of the new task
  86621. * @param url defines the url of the file to load
  86622. * @param size defines the size you want for the cubemap (can be null)
  86623. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86624. * @param generateHarmonics defines if you want to automatically generate (true by default)
  86625. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  86626. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  86627. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  86628. */
  86629. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  86630. if (noMipmap === void 0) { noMipmap = false; }
  86631. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86632. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86633. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86634. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  86635. this._tasks.push(task);
  86636. return task;
  86637. };
  86638. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  86639. var _this = this;
  86640. this._waitingTasksCount--;
  86641. try {
  86642. if (task.taskState === AssetTaskState.DONE) {
  86643. // Let's remove successfull tasks
  86644. BABYLON.Tools.SetImmediate(function () {
  86645. var index = _this._tasks.indexOf(task);
  86646. if (index > -1) {
  86647. _this._tasks.splice(index, 1);
  86648. }
  86649. });
  86650. }
  86651. if (this.onProgress) {
  86652. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  86653. }
  86654. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  86655. }
  86656. catch (e) {
  86657. BABYLON.Tools.Error("Error running progress callbacks.");
  86658. console.log(e);
  86659. }
  86660. if (this._waitingTasksCount === 0) {
  86661. try {
  86662. if (this.onFinish) {
  86663. this.onFinish(this._tasks);
  86664. }
  86665. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86666. }
  86667. catch (e) {
  86668. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  86669. console.log(e);
  86670. }
  86671. this._isLoading = false;
  86672. this._scene.getEngine().hideLoadingUI();
  86673. }
  86674. };
  86675. AssetsManager.prototype._runTask = function (task) {
  86676. var _this = this;
  86677. var done = function () {
  86678. try {
  86679. if (_this.onTaskSuccess) {
  86680. _this.onTaskSuccess(task);
  86681. }
  86682. _this.onTaskSuccessObservable.notifyObservers(task);
  86683. _this._decreaseWaitingTasksCount(task);
  86684. }
  86685. catch (e) {
  86686. error("Error executing task success callbacks", e);
  86687. }
  86688. };
  86689. var error = function (message, exception) {
  86690. task._setErrorObject(message, exception);
  86691. if (_this.onTaskError) {
  86692. _this.onTaskError(task);
  86693. }
  86694. _this.onTaskErrorObservable.notifyObservers(task);
  86695. _this._decreaseWaitingTasksCount(task);
  86696. };
  86697. task.run(this._scene, done, error);
  86698. };
  86699. /**
  86700. * Reset the {BABYLON.AssetsManager} and remove all tasks
  86701. * @return the current instance of the {BABYLON.AssetsManager}
  86702. */
  86703. AssetsManager.prototype.reset = function () {
  86704. this._isLoading = false;
  86705. this._tasks = new Array();
  86706. return this;
  86707. };
  86708. /**
  86709. * Start the loading process
  86710. * @return the current instance of the {BABYLON.AssetsManager}
  86711. */
  86712. AssetsManager.prototype.load = function () {
  86713. if (this._isLoading) {
  86714. return this;
  86715. }
  86716. this._isLoading = true;
  86717. this._waitingTasksCount = this._tasks.length;
  86718. this._totalTasksCount = this._tasks.length;
  86719. if (this._waitingTasksCount === 0) {
  86720. this._isLoading = false;
  86721. if (this.onFinish) {
  86722. this.onFinish(this._tasks);
  86723. }
  86724. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86725. return this;
  86726. }
  86727. if (this.useDefaultLoadingScreen) {
  86728. this._scene.getEngine().displayLoadingUI();
  86729. }
  86730. for (var index = 0; index < this._tasks.length; index++) {
  86731. var task = this._tasks[index];
  86732. this._runTask(task);
  86733. }
  86734. return this;
  86735. };
  86736. return AssetsManager;
  86737. }());
  86738. BABYLON.AssetsManager = AssetsManager;
  86739. })(BABYLON || (BABYLON = {}));
  86740. //# sourceMappingURL=babylon.assetsManager.js.map
  86741. var BABYLON;
  86742. (function (BABYLON) {
  86743. var serializedGeometries = [];
  86744. var serializeGeometry = function (geometry, serializationGeometries) {
  86745. if (serializedGeometries[geometry.id]) {
  86746. return;
  86747. }
  86748. if (geometry.doNotSerialize) {
  86749. return;
  86750. }
  86751. if (geometry instanceof BABYLON.BoxGeometry) {
  86752. serializationGeometries.boxes.push(geometry.serialize());
  86753. }
  86754. else if (geometry instanceof BABYLON.SphereGeometry) {
  86755. serializationGeometries.spheres.push(geometry.serialize());
  86756. }
  86757. else if (geometry instanceof BABYLON.CylinderGeometry) {
  86758. serializationGeometries.cylinders.push(geometry.serialize());
  86759. }
  86760. else if (geometry instanceof BABYLON.TorusGeometry) {
  86761. serializationGeometries.toruses.push(geometry.serialize());
  86762. }
  86763. else if (geometry instanceof BABYLON.GroundGeometry) {
  86764. serializationGeometries.grounds.push(geometry.serialize());
  86765. }
  86766. else if (geometry instanceof BABYLON.Plane) {
  86767. serializationGeometries.planes.push(geometry.serialize());
  86768. }
  86769. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  86770. serializationGeometries.torusKnots.push(geometry.serialize());
  86771. }
  86772. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  86773. throw new Error("Unknown primitive type");
  86774. }
  86775. else {
  86776. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  86777. }
  86778. serializedGeometries[geometry.id] = true;
  86779. };
  86780. var serializeMesh = function (mesh, serializationScene) {
  86781. var serializationObject = {};
  86782. // Geometry
  86783. var geometry = mesh._geometry;
  86784. if (geometry) {
  86785. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  86786. // 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
  86787. serializeGeometry(geometry, serializationScene.geometries);
  86788. }
  86789. }
  86790. // Custom
  86791. if (mesh.serialize) {
  86792. mesh.serialize(serializationObject);
  86793. }
  86794. return serializationObject;
  86795. };
  86796. var finalizeSingleMesh = function (mesh, serializationObject) {
  86797. //only works if the mesh is already loaded
  86798. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86799. //serialize material
  86800. if (mesh.material) {
  86801. if (mesh.material instanceof BABYLON.StandardMaterial) {
  86802. serializationObject.materials = serializationObject.materials || [];
  86803. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86804. serializationObject.materials.push(mesh.material.serialize());
  86805. }
  86806. }
  86807. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  86808. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  86809. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86810. serializationObject.multiMaterials.push(mesh.material.serialize());
  86811. }
  86812. }
  86813. }
  86814. //serialize geometry
  86815. var geometry = mesh._geometry;
  86816. if (geometry) {
  86817. if (!serializationObject.geometries) {
  86818. serializationObject.geometries = {};
  86819. serializationObject.geometries.boxes = [];
  86820. serializationObject.geometries.spheres = [];
  86821. serializationObject.geometries.cylinders = [];
  86822. serializationObject.geometries.toruses = [];
  86823. serializationObject.geometries.grounds = [];
  86824. serializationObject.geometries.planes = [];
  86825. serializationObject.geometries.torusKnots = [];
  86826. serializationObject.geometries.vertexData = [];
  86827. }
  86828. serializeGeometry(geometry, serializationObject.geometries);
  86829. }
  86830. // Skeletons
  86831. if (mesh.skeleton) {
  86832. serializationObject.skeletons = serializationObject.skeletons || [];
  86833. serializationObject.skeletons.push(mesh.skeleton.serialize());
  86834. }
  86835. //serialize the actual mesh
  86836. serializationObject.meshes = serializationObject.meshes || [];
  86837. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86838. }
  86839. };
  86840. var SceneSerializer = /** @class */ (function () {
  86841. function SceneSerializer() {
  86842. }
  86843. SceneSerializer.ClearCache = function () {
  86844. serializedGeometries = [];
  86845. };
  86846. SceneSerializer.Serialize = function (scene) {
  86847. var serializationObject = {};
  86848. SceneSerializer.ClearCache();
  86849. // Scene
  86850. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  86851. serializationObject.autoClear = scene.autoClear;
  86852. serializationObject.clearColor = scene.clearColor.asArray();
  86853. serializationObject.ambientColor = scene.ambientColor.asArray();
  86854. serializationObject.gravity = scene.gravity.asArray();
  86855. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  86856. serializationObject.workerCollisions = scene.workerCollisions;
  86857. // Fog
  86858. if (scene.fogMode && scene.fogMode !== 0) {
  86859. serializationObject.fogMode = scene.fogMode;
  86860. serializationObject.fogColor = scene.fogColor.asArray();
  86861. serializationObject.fogStart = scene.fogStart;
  86862. serializationObject.fogEnd = scene.fogEnd;
  86863. serializationObject.fogDensity = scene.fogDensity;
  86864. }
  86865. //Physics
  86866. if (scene.isPhysicsEnabled()) {
  86867. var physicEngine = scene.getPhysicsEngine();
  86868. if (physicEngine) {
  86869. serializationObject.physicsEnabled = true;
  86870. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  86871. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  86872. }
  86873. }
  86874. // Metadata
  86875. if (scene.metadata) {
  86876. serializationObject.metadata = scene.metadata;
  86877. }
  86878. // Morph targets
  86879. serializationObject.morphTargetManagers = [];
  86880. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  86881. var abstractMesh = _a[_i];
  86882. var manager = abstractMesh.morphTargetManager;
  86883. if (manager) {
  86884. serializationObject.morphTargetManagers.push(manager.serialize());
  86885. }
  86886. }
  86887. // Lights
  86888. serializationObject.lights = [];
  86889. var index;
  86890. var light;
  86891. for (index = 0; index < scene.lights.length; index++) {
  86892. light = scene.lights[index];
  86893. if (!light.doNotSerialize) {
  86894. serializationObject.lights.push(light.serialize());
  86895. }
  86896. }
  86897. // Cameras
  86898. serializationObject.cameras = [];
  86899. for (index = 0; index < scene.cameras.length; index++) {
  86900. var camera = scene.cameras[index];
  86901. if (!camera.doNotSerialize) {
  86902. serializationObject.cameras.push(camera.serialize());
  86903. }
  86904. }
  86905. if (scene.activeCamera) {
  86906. serializationObject.activeCameraID = scene.activeCamera.id;
  86907. }
  86908. // Animations
  86909. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  86910. // Materials
  86911. serializationObject.materials = [];
  86912. serializationObject.multiMaterials = [];
  86913. var material;
  86914. for (index = 0; index < scene.materials.length; index++) {
  86915. material = scene.materials[index];
  86916. if (!material.doNotSerialize) {
  86917. serializationObject.materials.push(material.serialize());
  86918. }
  86919. }
  86920. // MultiMaterials
  86921. serializationObject.multiMaterials = [];
  86922. for (index = 0; index < scene.multiMaterials.length; index++) {
  86923. var multiMaterial = scene.multiMaterials[index];
  86924. serializationObject.multiMaterials.push(multiMaterial.serialize());
  86925. }
  86926. // Environment texture
  86927. if (scene.environmentTexture) {
  86928. serializationObject.environmentTexture = scene.environmentTexture.name;
  86929. }
  86930. // Skeletons
  86931. serializationObject.skeletons = [];
  86932. for (index = 0; index < scene.skeletons.length; index++) {
  86933. var skeleton = scene.skeletons[index];
  86934. if (!skeleton.doNotSerialize) {
  86935. serializationObject.skeletons.push(skeleton.serialize());
  86936. }
  86937. }
  86938. // Transform nodes
  86939. serializationObject.transformNodes = [];
  86940. for (index = 0; index < scene.transformNodes.length; index++) {
  86941. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  86942. }
  86943. // Geometries
  86944. serializationObject.geometries = {};
  86945. serializationObject.geometries.boxes = [];
  86946. serializationObject.geometries.spheres = [];
  86947. serializationObject.geometries.cylinders = [];
  86948. serializationObject.geometries.toruses = [];
  86949. serializationObject.geometries.grounds = [];
  86950. serializationObject.geometries.planes = [];
  86951. serializationObject.geometries.torusKnots = [];
  86952. serializationObject.geometries.vertexData = [];
  86953. serializedGeometries = [];
  86954. var geometries = scene.getGeometries();
  86955. for (index = 0; index < geometries.length; index++) {
  86956. var geometry = geometries[index];
  86957. if (geometry.isReady()) {
  86958. serializeGeometry(geometry, serializationObject.geometries);
  86959. }
  86960. }
  86961. // Meshes
  86962. serializationObject.meshes = [];
  86963. for (index = 0; index < scene.meshes.length; index++) {
  86964. var abstractMesh = scene.meshes[index];
  86965. if (abstractMesh instanceof BABYLON.Mesh) {
  86966. var mesh = abstractMesh;
  86967. if (!mesh.doNotSerialize) {
  86968. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86969. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86970. }
  86971. }
  86972. }
  86973. }
  86974. // Particles Systems
  86975. serializationObject.particleSystems = [];
  86976. for (index = 0; index < scene.particleSystems.length; index++) {
  86977. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  86978. }
  86979. // Lens flares
  86980. serializationObject.lensFlareSystems = [];
  86981. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  86982. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  86983. }
  86984. // Shadows
  86985. serializationObject.shadowGenerators = [];
  86986. for (index = 0; index < scene.lights.length; index++) {
  86987. light = scene.lights[index];
  86988. var shadowGenerator = light.getShadowGenerator();
  86989. if (shadowGenerator) {
  86990. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  86991. }
  86992. }
  86993. // Action Manager
  86994. if (scene.actionManager) {
  86995. serializationObject.actions = scene.actionManager.serialize("scene");
  86996. }
  86997. // Audio
  86998. serializationObject.sounds = [];
  86999. for (index = 0; index < scene.soundTracks.length; index++) {
  87000. var soundtrack = scene.soundTracks[index];
  87001. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  87002. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  87003. }
  87004. }
  87005. return serializationObject;
  87006. };
  87007. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  87008. if (withParents === void 0) { withParents = false; }
  87009. if (withChildren === void 0) { withChildren = false; }
  87010. var serializationObject = {};
  87011. SceneSerializer.ClearCache();
  87012. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  87013. if (withParents || withChildren) {
  87014. //deliberate for loop! not for each, appended should be processed as well.
  87015. for (var i = 0; i < toSerialize.length; ++i) {
  87016. if (withChildren) {
  87017. toSerialize[i].getDescendants().forEach(function (node) {
  87018. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  87019. toSerialize.push(node);
  87020. }
  87021. });
  87022. }
  87023. //make sure the array doesn't contain the object already
  87024. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  87025. toSerialize.push(toSerialize[i].parent);
  87026. }
  87027. }
  87028. }
  87029. toSerialize.forEach(function (mesh) {
  87030. finalizeSingleMesh(mesh, serializationObject);
  87031. });
  87032. return serializationObject;
  87033. };
  87034. return SceneSerializer;
  87035. }());
  87036. BABYLON.SceneSerializer = SceneSerializer;
  87037. })(BABYLON || (BABYLON = {}));
  87038. //# sourceMappingURL=babylon.sceneSerializer.js.map
  87039. var BABYLON;
  87040. (function (BABYLON) {
  87041. var ReflectionProbe = /** @class */ (function () {
  87042. function ReflectionProbe(name, size, scene, generateMipMaps) {
  87043. if (generateMipMaps === void 0) { generateMipMaps = true; }
  87044. var _this = this;
  87045. this.name = name;
  87046. this._viewMatrix = BABYLON.Matrix.Identity();
  87047. this._target = BABYLON.Vector3.Zero();
  87048. this._add = BABYLON.Vector3.Zero();
  87049. this._invertYAxis = false;
  87050. this.position = BABYLON.Vector3.Zero();
  87051. this._scene = scene;
  87052. this._scene.reflectionProbes.push(this);
  87053. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  87054. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  87055. switch (faceIndex) {
  87056. case 0:
  87057. _this._add.copyFromFloats(1, 0, 0);
  87058. break;
  87059. case 1:
  87060. _this._add.copyFromFloats(-1, 0, 0);
  87061. break;
  87062. case 2:
  87063. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  87064. break;
  87065. case 3:
  87066. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  87067. break;
  87068. case 4:
  87069. _this._add.copyFromFloats(0, 0, 1);
  87070. break;
  87071. case 5:
  87072. _this._add.copyFromFloats(0, 0, -1);
  87073. break;
  87074. }
  87075. if (_this._attachedMesh) {
  87076. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  87077. }
  87078. _this.position.addToRef(_this._add, _this._target);
  87079. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  87080. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  87081. scene._forcedViewPosition = _this.position;
  87082. });
  87083. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  87084. scene._forcedViewPosition = null;
  87085. scene.updateTransformMatrix(true);
  87086. });
  87087. if (scene.activeCamera) {
  87088. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87089. }
  87090. }
  87091. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  87092. get: function () {
  87093. return this._renderTargetTexture.samples;
  87094. },
  87095. set: function (value) {
  87096. this._renderTargetTexture.samples = value;
  87097. },
  87098. enumerable: true,
  87099. configurable: true
  87100. });
  87101. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  87102. get: function () {
  87103. return this._renderTargetTexture.refreshRate;
  87104. },
  87105. set: function (value) {
  87106. this._renderTargetTexture.refreshRate = value;
  87107. },
  87108. enumerable: true,
  87109. configurable: true
  87110. });
  87111. ReflectionProbe.prototype.getScene = function () {
  87112. return this._scene;
  87113. };
  87114. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  87115. get: function () {
  87116. return this._renderTargetTexture;
  87117. },
  87118. enumerable: true,
  87119. configurable: true
  87120. });
  87121. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  87122. get: function () {
  87123. return this._renderTargetTexture.renderList;
  87124. },
  87125. enumerable: true,
  87126. configurable: true
  87127. });
  87128. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  87129. this._attachedMesh = mesh;
  87130. };
  87131. /**
  87132. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  87133. *
  87134. * @param renderingGroupId The rendering group id corresponding to its index
  87135. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  87136. */
  87137. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  87138. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  87139. };
  87140. ReflectionProbe.prototype.dispose = function () {
  87141. var index = this._scene.reflectionProbes.indexOf(this);
  87142. if (index !== -1) {
  87143. // Remove from the scene if found
  87144. this._scene.reflectionProbes.splice(index, 1);
  87145. }
  87146. if (this._renderTargetTexture) {
  87147. this._renderTargetTexture.dispose();
  87148. this._renderTargetTexture = null;
  87149. }
  87150. };
  87151. return ReflectionProbe;
  87152. }());
  87153. BABYLON.ReflectionProbe = ReflectionProbe;
  87154. })(BABYLON || (BABYLON = {}));
  87155. //# sourceMappingURL=babylon.reflectionProbe.js.map
  87156. var BABYLON;
  87157. (function (BABYLON) {
  87158. var Layer = /** @class */ (function () {
  87159. function Layer(name, imgUrl, scene, isBackground, color) {
  87160. this.name = name;
  87161. this.scale = new BABYLON.Vector2(1, 1);
  87162. this.offset = new BABYLON.Vector2(0, 0);
  87163. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  87164. this.layerMask = 0x0FFFFFFF;
  87165. this._vertexBuffers = {};
  87166. // Events
  87167. /**
  87168. * An event triggered when the layer is disposed.
  87169. * @type {BABYLON.Observable}
  87170. */
  87171. this.onDisposeObservable = new BABYLON.Observable();
  87172. /**
  87173. * An event triggered before rendering the scene
  87174. * @type {BABYLON.Observable}
  87175. */
  87176. this.onBeforeRenderObservable = new BABYLON.Observable();
  87177. /**
  87178. * An event triggered after rendering the scene
  87179. * @type {BABYLON.Observable}
  87180. */
  87181. this.onAfterRenderObservable = new BABYLON.Observable();
  87182. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  87183. this.isBackground = isBackground === undefined ? true : isBackground;
  87184. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  87185. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  87186. this._scene.layers.push(this);
  87187. var engine = this._scene.getEngine();
  87188. // VBO
  87189. var vertices = [];
  87190. vertices.push(1, 1);
  87191. vertices.push(-1, 1);
  87192. vertices.push(-1, -1);
  87193. vertices.push(1, -1);
  87194. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87195. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  87196. this._createIndexBuffer();
  87197. // Effects
  87198. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  87199. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  87200. }
  87201. Object.defineProperty(Layer.prototype, "onDispose", {
  87202. set: function (callback) {
  87203. if (this._onDisposeObserver) {
  87204. this.onDisposeObservable.remove(this._onDisposeObserver);
  87205. }
  87206. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  87207. },
  87208. enumerable: true,
  87209. configurable: true
  87210. });
  87211. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  87212. set: function (callback) {
  87213. if (this._onBeforeRenderObserver) {
  87214. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  87215. }
  87216. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  87217. },
  87218. enumerable: true,
  87219. configurable: true
  87220. });
  87221. Object.defineProperty(Layer.prototype, "onAfterRender", {
  87222. set: function (callback) {
  87223. if (this._onAfterRenderObserver) {
  87224. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87225. }
  87226. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  87227. },
  87228. enumerable: true,
  87229. configurable: true
  87230. });
  87231. Layer.prototype._createIndexBuffer = function () {
  87232. var engine = this._scene.getEngine();
  87233. // Indices
  87234. var indices = [];
  87235. indices.push(0);
  87236. indices.push(1);
  87237. indices.push(2);
  87238. indices.push(0);
  87239. indices.push(2);
  87240. indices.push(3);
  87241. this._indexBuffer = engine.createIndexBuffer(indices);
  87242. };
  87243. Layer.prototype._rebuild = function () {
  87244. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87245. if (vb) {
  87246. vb._rebuild();
  87247. }
  87248. this._createIndexBuffer();
  87249. };
  87250. Layer.prototype.render = function () {
  87251. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  87252. // Check
  87253. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  87254. return;
  87255. var engine = this._scene.getEngine();
  87256. this.onBeforeRenderObservable.notifyObservers(this);
  87257. // Render
  87258. engine.enableEffect(currentEffect);
  87259. engine.setState(false);
  87260. // Texture
  87261. currentEffect.setTexture("textureSampler", this.texture);
  87262. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  87263. // Color
  87264. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  87265. // Scale / offset
  87266. currentEffect.setVector2("offset", this.offset);
  87267. currentEffect.setVector2("scale", this.scale);
  87268. // VBOs
  87269. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  87270. // Draw order
  87271. if (!this.alphaTest) {
  87272. engine.setAlphaMode(this.alphaBlendingMode);
  87273. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87274. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87275. }
  87276. else {
  87277. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87278. }
  87279. this.onAfterRenderObservable.notifyObservers(this);
  87280. };
  87281. Layer.prototype.dispose = function () {
  87282. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87283. if (vertexBuffer) {
  87284. vertexBuffer.dispose();
  87285. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87286. }
  87287. if (this._indexBuffer) {
  87288. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87289. this._indexBuffer = null;
  87290. }
  87291. if (this.texture) {
  87292. this.texture.dispose();
  87293. this.texture = null;
  87294. }
  87295. // Remove from scene
  87296. var index = this._scene.layers.indexOf(this);
  87297. this._scene.layers.splice(index, 1);
  87298. // Callback
  87299. this.onDisposeObservable.notifyObservers(this);
  87300. this.onDisposeObservable.clear();
  87301. this.onAfterRenderObservable.clear();
  87302. this.onBeforeRenderObservable.clear();
  87303. };
  87304. return Layer;
  87305. }());
  87306. BABYLON.Layer = Layer;
  87307. })(BABYLON || (BABYLON = {}));
  87308. //# sourceMappingURL=babylon.layer.js.map
  87309. var BABYLON;
  87310. (function (BABYLON) {
  87311. var TextureTools = /** @class */ (function () {
  87312. function TextureTools() {
  87313. }
  87314. /**
  87315. * Uses the GPU to create a copy texture rescaled at a given size
  87316. * @param texture Texture to copy from
  87317. * @param width Desired width
  87318. * @param height Desired height
  87319. * @return Generated texture
  87320. */
  87321. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  87322. if (useBilinearMode === void 0) { useBilinearMode = true; }
  87323. var scene = texture.getScene();
  87324. var engine = scene.getEngine();
  87325. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  87326. rtt.wrapU = texture.wrapU;
  87327. rtt.wrapV = texture.wrapV;
  87328. rtt.uOffset = texture.uOffset;
  87329. rtt.vOffset = texture.vOffset;
  87330. rtt.uScale = texture.uScale;
  87331. rtt.vScale = texture.vScale;
  87332. rtt.uAng = texture.uAng;
  87333. rtt.vAng = texture.vAng;
  87334. rtt.wAng = texture.wAng;
  87335. rtt.coordinatesIndex = texture.coordinatesIndex;
  87336. rtt.level = texture.level;
  87337. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  87338. rtt._texture.isReady = false;
  87339. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87340. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87341. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87342. passPostProcess.getEffect().executeWhenCompiled(function () {
  87343. passPostProcess.onApply = function (effect) {
  87344. effect.setTexture("textureSampler", texture);
  87345. };
  87346. var internalTexture = rtt.getInternalTexture();
  87347. if (internalTexture) {
  87348. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  87349. engine.unBindFramebuffer(internalTexture);
  87350. rtt.disposeFramebufferObjects();
  87351. passPostProcess.dispose();
  87352. internalTexture.isReady = true;
  87353. }
  87354. });
  87355. return rtt;
  87356. };
  87357. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  87358. if (!scene._environmentBRDFTexture) {
  87359. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87360. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87361. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87362. scene._environmentBRDFTexture = texture;
  87363. }
  87364. return scene._environmentBRDFTexture;
  87365. };
  87366. 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=";
  87367. return TextureTools;
  87368. }());
  87369. BABYLON.TextureTools = TextureTools;
  87370. })(BABYLON || (BABYLON = {}));
  87371. //# sourceMappingURL=babylon.textureTools.js.map
  87372. var BABYLON;
  87373. (function (BABYLON) {
  87374. var FramingBehavior = /** @class */ (function () {
  87375. function FramingBehavior() {
  87376. this._mode = FramingBehavior.FitFrustumSidesMode;
  87377. this._radiusScale = 1.0;
  87378. this._positionScale = 0.5;
  87379. this._defaultElevation = 0.3;
  87380. this._elevationReturnTime = 1500;
  87381. this._elevationReturnWaitTime = 1000;
  87382. this._zoomStopsAnimation = false;
  87383. this._framingTime = 1500;
  87384. this._isPointerDown = false;
  87385. this._lastInteractionTime = -Infinity;
  87386. // Framing control
  87387. this._animatables = new Array();
  87388. this._betaIsAnimating = false;
  87389. }
  87390. Object.defineProperty(FramingBehavior.prototype, "name", {
  87391. get: function () {
  87392. return "Framing";
  87393. },
  87394. enumerable: true,
  87395. configurable: true
  87396. });
  87397. Object.defineProperty(FramingBehavior.prototype, "mode", {
  87398. /**
  87399. * Gets current mode used by the behavior.
  87400. */
  87401. get: function () {
  87402. return this._mode;
  87403. },
  87404. /**
  87405. * Sets the current mode used by the behavior
  87406. */
  87407. set: function (mode) {
  87408. this._mode = mode;
  87409. },
  87410. enumerable: true,
  87411. configurable: true
  87412. });
  87413. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  87414. /**
  87415. * Gets the scale applied to the radius
  87416. */
  87417. get: function () {
  87418. return this._radiusScale;
  87419. },
  87420. /**
  87421. * Sets the scale applied to the radius (1 by default)
  87422. */
  87423. set: function (radius) {
  87424. this._radiusScale = radius;
  87425. },
  87426. enumerable: true,
  87427. configurable: true
  87428. });
  87429. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  87430. /**
  87431. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87432. */
  87433. get: function () {
  87434. return this._positionScale;
  87435. },
  87436. /**
  87437. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87438. */
  87439. set: function (scale) {
  87440. this._positionScale = scale;
  87441. },
  87442. enumerable: true,
  87443. configurable: true
  87444. });
  87445. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  87446. /**
  87447. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87448. * behaviour is triggered, in radians.
  87449. */
  87450. get: function () {
  87451. return this._defaultElevation;
  87452. },
  87453. /**
  87454. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87455. * behaviour is triggered, in radians.
  87456. */
  87457. set: function (elevation) {
  87458. this._defaultElevation = elevation;
  87459. },
  87460. enumerable: true,
  87461. configurable: true
  87462. });
  87463. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  87464. /**
  87465. * Gets the time (in milliseconds) taken to return to the default beta position.
  87466. * Negative value indicates camera should not return to default.
  87467. */
  87468. get: function () {
  87469. return this._elevationReturnTime;
  87470. },
  87471. /**
  87472. * Sets the time (in milliseconds) taken to return to the default beta position.
  87473. * Negative value indicates camera should not return to default.
  87474. */
  87475. set: function (speed) {
  87476. this._elevationReturnTime = speed;
  87477. },
  87478. enumerable: true,
  87479. configurable: true
  87480. });
  87481. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  87482. /**
  87483. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87484. */
  87485. get: function () {
  87486. return this._elevationReturnWaitTime;
  87487. },
  87488. /**
  87489. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87490. */
  87491. set: function (time) {
  87492. this._elevationReturnWaitTime = time;
  87493. },
  87494. enumerable: true,
  87495. configurable: true
  87496. });
  87497. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  87498. /**
  87499. * Gets the flag that indicates if user zooming should stop animation.
  87500. */
  87501. get: function () {
  87502. return this._zoomStopsAnimation;
  87503. },
  87504. /**
  87505. * Sets the flag that indicates if user zooming should stop animation.
  87506. */
  87507. set: function (flag) {
  87508. this._zoomStopsAnimation = flag;
  87509. },
  87510. enumerable: true,
  87511. configurable: true
  87512. });
  87513. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  87514. /**
  87515. * Gets the transition time when framing the mesh, in milliseconds
  87516. */
  87517. get: function () {
  87518. return this._framingTime;
  87519. },
  87520. /**
  87521. * Sets the transition time when framing the mesh, in milliseconds
  87522. */
  87523. set: function (time) {
  87524. this._framingTime = time;
  87525. },
  87526. enumerable: true,
  87527. configurable: true
  87528. });
  87529. FramingBehavior.prototype.init = function () {
  87530. // Do notihng
  87531. };
  87532. FramingBehavior.prototype.attach = function (camera) {
  87533. var _this = this;
  87534. this._attachedCamera = camera;
  87535. var scene = this._attachedCamera.getScene();
  87536. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  87537. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87538. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87539. _this._isPointerDown = true;
  87540. return;
  87541. }
  87542. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87543. _this._isPointerDown = false;
  87544. }
  87545. });
  87546. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87547. if (mesh) {
  87548. _this.zoomOnMesh(mesh);
  87549. }
  87550. });
  87551. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87552. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87553. _this._applyUserInteraction();
  87554. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  87555. // back to the default position after a given timeout
  87556. _this._maintainCameraAboveGround();
  87557. });
  87558. };
  87559. FramingBehavior.prototype.detach = function () {
  87560. if (!this._attachedCamera) {
  87561. return;
  87562. }
  87563. var scene = this._attachedCamera.getScene();
  87564. if (this._onPrePointerObservableObserver) {
  87565. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87566. }
  87567. if (this._onAfterCheckInputsObserver) {
  87568. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87569. }
  87570. if (this._onMeshTargetChangedObserver) {
  87571. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87572. }
  87573. this._attachedCamera = null;
  87574. };
  87575. /**
  87576. * Targets the given mesh and updates zoom level accordingly.
  87577. * @param mesh The mesh to target.
  87578. * @param radius Optional. If a cached radius position already exists, overrides default.
  87579. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87580. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87581. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87582. */
  87583. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87584. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87585. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87586. mesh.computeWorldMatrix(true);
  87587. var boundingBox = mesh.getBoundingInfo().boundingBox;
  87588. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  87589. };
  87590. /**
  87591. * Targets the given mesh with its children and updates zoom level accordingly.
  87592. * @param mesh The mesh to target.
  87593. * @param radius Optional. If a cached radius position already exists, overrides default.
  87594. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87595. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87596. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87597. */
  87598. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87599. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87600. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87601. mesh.computeWorldMatrix(true);
  87602. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  87603. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  87604. };
  87605. /**
  87606. * Targets the given meshes with their children and updates zoom level accordingly.
  87607. * @param meshes The mesh to target.
  87608. * @param radius Optional. If a cached radius position already exists, overrides default.
  87609. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87610. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87611. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87612. */
  87613. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  87614. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87615. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87616. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  87617. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  87618. for (var i = 0; i < meshes.length; i++) {
  87619. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  87620. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  87621. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  87622. }
  87623. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  87624. };
  87625. /**
  87626. * Targets the given mesh and updates zoom level accordingly.
  87627. * @param mesh The mesh to target.
  87628. * @param radius Optional. If a cached radius position already exists, overrides default.
  87629. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87630. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87631. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87632. */
  87633. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  87634. var _this = this;
  87635. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87636. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87637. var zoomTarget;
  87638. if (!this._attachedCamera) {
  87639. return;
  87640. }
  87641. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  87642. var bottom = minimumWorld.y;
  87643. var top = maximumWorld.y;
  87644. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  87645. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  87646. if (focusOnOriginXZ) {
  87647. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  87648. }
  87649. else {
  87650. var centerWorld = minimumWorld.add(radiusWorld);
  87651. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  87652. }
  87653. if (!this._vectorTransition) {
  87654. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  87655. }
  87656. this._betaIsAnimating = true;
  87657. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  87658. if (animatable) {
  87659. this._animatables.push(animatable);
  87660. }
  87661. // sets the radius and lower radius bounds
  87662. // Small delta ensures camera is not always at lower zoom limit.
  87663. var radius = 0;
  87664. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  87665. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87666. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  87667. radius = position;
  87668. }
  87669. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87670. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87671. if (this._attachedCamera.lowerRadiusLimit === null) {
  87672. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  87673. }
  87674. }
  87675. // Set sensibilities
  87676. var extend = maximumWorld.subtract(minimumWorld).length();
  87677. this._attachedCamera.panningSensibility = 5000 / extend;
  87678. this._attachedCamera.wheelPrecision = 100 / radius;
  87679. // transition to new radius
  87680. if (!this._radiusTransition) {
  87681. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87682. }
  87683. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  87684. if (onAnimationEnd) {
  87685. onAnimationEnd();
  87686. }
  87687. if (_this._attachedCamera) {
  87688. _this._attachedCamera.storeState();
  87689. }
  87690. });
  87691. if (animatable) {
  87692. this._animatables.push(animatable);
  87693. }
  87694. };
  87695. /**
  87696. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  87697. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  87698. * frustum width.
  87699. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  87700. * to fully enclose the mesh in the viewing frustum.
  87701. */
  87702. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  87703. var size = maximumWorld.subtract(minimumWorld);
  87704. var boxVectorGlobalDiagonal = size.length();
  87705. var frustumSlope = this._getFrustumSlope();
  87706. // Formula for setting distance
  87707. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  87708. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  87709. // Horizon distance
  87710. var radius = radiusWithoutFraming * this._radiusScale;
  87711. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  87712. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  87713. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  87714. var camera = this._attachedCamera;
  87715. if (!camera) {
  87716. return 0;
  87717. }
  87718. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87719. // Don't exceed the requested limit
  87720. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  87721. }
  87722. // Don't exceed the upper radius limit
  87723. if (camera.upperRadiusLimit) {
  87724. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  87725. }
  87726. return distance;
  87727. };
  87728. /**
  87729. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  87730. * is automatically returned to its default position (expected to be above ground plane).
  87731. */
  87732. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  87733. var _this = this;
  87734. if (this._elevationReturnTime < 0) {
  87735. return;
  87736. }
  87737. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  87738. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  87739. var limitBeta = Math.PI * 0.5;
  87740. // Bring the camera back up if below the ground plane
  87741. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  87742. this._betaIsAnimating = true;
  87743. //Transition to new position
  87744. this.stopAllAnimations();
  87745. if (!this._betaTransition) {
  87746. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87747. }
  87748. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  87749. _this._clearAnimationLocks();
  87750. _this.stopAllAnimations();
  87751. });
  87752. if (animatabe) {
  87753. this._animatables.push(animatabe);
  87754. }
  87755. }
  87756. };
  87757. /**
  87758. * Returns the frustum slope based on the canvas ratio and camera FOV
  87759. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  87760. */
  87761. FramingBehavior.prototype._getFrustumSlope = function () {
  87762. // Calculate the viewport ratio
  87763. // Aspect Ratio is Height/Width.
  87764. var camera = this._attachedCamera;
  87765. if (!camera) {
  87766. return BABYLON.Vector2.Zero();
  87767. }
  87768. var engine = camera.getScene().getEngine();
  87769. var aspectRatio = engine.getAspectRatio(camera);
  87770. // Camera FOV is the vertical field of view (top-bottom) in radians.
  87771. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  87772. var frustumSlopeY = Math.tan(camera.fov / 2);
  87773. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  87774. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  87775. // along the forward vector.
  87776. var frustumSlopeX = frustumSlopeY * aspectRatio;
  87777. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  87778. };
  87779. /**
  87780. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  87781. */
  87782. FramingBehavior.prototype._clearAnimationLocks = function () {
  87783. this._betaIsAnimating = false;
  87784. };
  87785. /**
  87786. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87787. */
  87788. FramingBehavior.prototype._applyUserInteraction = function () {
  87789. if (this.isUserIsMoving) {
  87790. this._lastInteractionTime = BABYLON.Tools.Now;
  87791. this.stopAllAnimations();
  87792. this._clearAnimationLocks();
  87793. }
  87794. };
  87795. /**
  87796. * Stops and removes all animations that have been applied to the camera
  87797. */
  87798. FramingBehavior.prototype.stopAllAnimations = function () {
  87799. if (this._attachedCamera) {
  87800. this._attachedCamera.animations = [];
  87801. }
  87802. while (this._animatables.length) {
  87803. if (this._animatables[0]) {
  87804. this._animatables[0].onAnimationEnd = null;
  87805. this._animatables[0].stop();
  87806. }
  87807. this._animatables.shift();
  87808. }
  87809. };
  87810. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  87811. /**
  87812. * Gets a value indicating if the user is moving the camera
  87813. */
  87814. get: function () {
  87815. if (!this._attachedCamera) {
  87816. return false;
  87817. }
  87818. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87819. this._attachedCamera.inertialBetaOffset !== 0 ||
  87820. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87821. this._attachedCamera.inertialPanningX !== 0 ||
  87822. this._attachedCamera.inertialPanningY !== 0 ||
  87823. this._isPointerDown;
  87824. },
  87825. enumerable: true,
  87826. configurable: true
  87827. });
  87828. /**
  87829. * The easing function used by animations
  87830. */
  87831. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  87832. /**
  87833. * The easing mode used by animations
  87834. */
  87835. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  87836. // Statics
  87837. /**
  87838. * The camera can move all the way towards the mesh.
  87839. */
  87840. FramingBehavior.IgnoreBoundsSizeMode = 0;
  87841. /**
  87842. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  87843. */
  87844. FramingBehavior.FitFrustumSidesMode = 1;
  87845. return FramingBehavior;
  87846. }());
  87847. BABYLON.FramingBehavior = FramingBehavior;
  87848. })(BABYLON || (BABYLON = {}));
  87849. //# sourceMappingURL=babylon.framingBehavior.js.map
  87850. var BABYLON;
  87851. (function (BABYLON) {
  87852. /**
  87853. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  87854. */
  87855. var BouncingBehavior = /** @class */ (function () {
  87856. function BouncingBehavior() {
  87857. /**
  87858. * The duration of the animation, in milliseconds
  87859. */
  87860. this.transitionDuration = 450;
  87861. /**
  87862. * Length of the distance animated by the transition when lower radius is reached
  87863. */
  87864. this.lowerRadiusTransitionRange = 2;
  87865. /**
  87866. * Length of the distance animated by the transition when upper radius is reached
  87867. */
  87868. this.upperRadiusTransitionRange = -2;
  87869. this._autoTransitionRange = false;
  87870. // Animations
  87871. this._radiusIsAnimating = false;
  87872. this._radiusBounceTransition = null;
  87873. this._animatables = new Array();
  87874. }
  87875. Object.defineProperty(BouncingBehavior.prototype, "name", {
  87876. get: function () {
  87877. return "Bouncing";
  87878. },
  87879. enumerable: true,
  87880. configurable: true
  87881. });
  87882. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  87883. /**
  87884. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87885. */
  87886. get: function () {
  87887. return this._autoTransitionRange;
  87888. },
  87889. /**
  87890. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87891. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  87892. */
  87893. set: function (value) {
  87894. var _this = this;
  87895. if (this._autoTransitionRange === value) {
  87896. return;
  87897. }
  87898. this._autoTransitionRange = value;
  87899. var camera = this._attachedCamera;
  87900. if (!camera) {
  87901. return;
  87902. }
  87903. if (value) {
  87904. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87905. if (!mesh) {
  87906. return;
  87907. }
  87908. mesh.computeWorldMatrix(true);
  87909. var diagonal = mesh.getBoundingInfo().diagonalLength;
  87910. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  87911. _this.upperRadiusTransitionRange = diagonal * 0.05;
  87912. });
  87913. }
  87914. else if (this._onMeshTargetChangedObserver) {
  87915. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87916. }
  87917. },
  87918. enumerable: true,
  87919. configurable: true
  87920. });
  87921. BouncingBehavior.prototype.init = function () {
  87922. // Do notihng
  87923. };
  87924. BouncingBehavior.prototype.attach = function (camera) {
  87925. var _this = this;
  87926. this._attachedCamera = camera;
  87927. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87928. if (!_this._attachedCamera) {
  87929. return;
  87930. }
  87931. // Add the bounce animation to the lower radius limit
  87932. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  87933. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  87934. }
  87935. // Add the bounce animation to the upper radius limit
  87936. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  87937. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  87938. }
  87939. });
  87940. };
  87941. BouncingBehavior.prototype.detach = function () {
  87942. if (!this._attachedCamera) {
  87943. return;
  87944. }
  87945. if (this._onAfterCheckInputsObserver) {
  87946. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87947. }
  87948. if (this._onMeshTargetChangedObserver) {
  87949. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87950. }
  87951. this._attachedCamera = null;
  87952. };
  87953. /**
  87954. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  87955. * @param radiusLimit The limit to check against.
  87956. * @return Bool to indicate if at limit.
  87957. */
  87958. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  87959. if (!this._attachedCamera) {
  87960. return false;
  87961. }
  87962. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  87963. return true;
  87964. }
  87965. return false;
  87966. };
  87967. /**
  87968. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  87969. * @param radiusDelta The delta by which to animate to. Can be negative.
  87970. */
  87971. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  87972. var _this = this;
  87973. if (!this._attachedCamera) {
  87974. return;
  87975. }
  87976. if (!this._radiusBounceTransition) {
  87977. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  87978. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  87979. }
  87980. // Prevent zoom until bounce has completed
  87981. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  87982. this._attachedCamera.wheelPrecision = Infinity;
  87983. this._attachedCamera.inertialRadiusOffset = 0;
  87984. // Animate to the radius limit
  87985. this.stopAllAnimations();
  87986. this._radiusIsAnimating = true;
  87987. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  87988. if (animatable) {
  87989. this._animatables.push(animatable);
  87990. }
  87991. };
  87992. /**
  87993. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  87994. */
  87995. BouncingBehavior.prototype._clearAnimationLocks = function () {
  87996. this._radiusIsAnimating = false;
  87997. if (this._attachedCamera) {
  87998. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  87999. }
  88000. };
  88001. /**
  88002. * Stops and removes all animations that have been applied to the camera
  88003. */
  88004. BouncingBehavior.prototype.stopAllAnimations = function () {
  88005. if (this._attachedCamera) {
  88006. this._attachedCamera.animations = [];
  88007. }
  88008. while (this._animatables.length) {
  88009. this._animatables[0].onAnimationEnd = null;
  88010. this._animatables[0].stop();
  88011. this._animatables.shift();
  88012. }
  88013. };
  88014. /**
  88015. * The easing function used by animations
  88016. */
  88017. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  88018. /**
  88019. * The easing mode used by animations
  88020. */
  88021. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  88022. return BouncingBehavior;
  88023. }());
  88024. BABYLON.BouncingBehavior = BouncingBehavior;
  88025. })(BABYLON || (BABYLON = {}));
  88026. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  88027. var BABYLON;
  88028. (function (BABYLON) {
  88029. var AutoRotationBehavior = /** @class */ (function () {
  88030. function AutoRotationBehavior() {
  88031. this._zoomStopsAnimation = false;
  88032. this._idleRotationSpeed = 0.05;
  88033. this._idleRotationWaitTime = 2000;
  88034. this._idleRotationSpinupTime = 2000;
  88035. this._isPointerDown = false;
  88036. this._lastFrameTime = null;
  88037. this._lastInteractionTime = -Infinity;
  88038. this._cameraRotationSpeed = 0;
  88039. this._lastFrameRadius = 0;
  88040. }
  88041. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  88042. get: function () {
  88043. return "AutoRotation";
  88044. },
  88045. enumerable: true,
  88046. configurable: true
  88047. });
  88048. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  88049. /**
  88050. * Gets the flag that indicates if user zooming should stop animation.
  88051. */
  88052. get: function () {
  88053. return this._zoomStopsAnimation;
  88054. },
  88055. /**
  88056. * Sets the flag that indicates if user zooming should stop animation.
  88057. */
  88058. set: function (flag) {
  88059. this._zoomStopsAnimation = flag;
  88060. },
  88061. enumerable: true,
  88062. configurable: true
  88063. });
  88064. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  88065. /**
  88066. * Gets the default speed at which the camera rotates around the model.
  88067. */
  88068. get: function () {
  88069. return this._idleRotationSpeed;
  88070. },
  88071. /**
  88072. * Sets the default speed at which the camera rotates around the model.
  88073. */
  88074. set: function (speed) {
  88075. this._idleRotationSpeed = speed;
  88076. },
  88077. enumerable: true,
  88078. configurable: true
  88079. });
  88080. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  88081. /**
  88082. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  88083. */
  88084. get: function () {
  88085. return this._idleRotationWaitTime;
  88086. },
  88087. /**
  88088. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  88089. */
  88090. set: function (time) {
  88091. this._idleRotationWaitTime = time;
  88092. },
  88093. enumerable: true,
  88094. configurable: true
  88095. });
  88096. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  88097. /**
  88098. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88099. */
  88100. get: function () {
  88101. return this._idleRotationSpinupTime;
  88102. },
  88103. /**
  88104. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88105. */
  88106. set: function (time) {
  88107. this._idleRotationSpinupTime = time;
  88108. },
  88109. enumerable: true,
  88110. configurable: true
  88111. });
  88112. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  88113. /**
  88114. * Gets a value indicating if the camera is currently rotating because of this behavior
  88115. */
  88116. get: function () {
  88117. return Math.abs(this._cameraRotationSpeed) > 0;
  88118. },
  88119. enumerable: true,
  88120. configurable: true
  88121. });
  88122. AutoRotationBehavior.prototype.init = function () {
  88123. // Do notihng
  88124. };
  88125. AutoRotationBehavior.prototype.attach = function (camera) {
  88126. var _this = this;
  88127. this._attachedCamera = camera;
  88128. var scene = this._attachedCamera.getScene();
  88129. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88130. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88131. _this._isPointerDown = true;
  88132. return;
  88133. }
  88134. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88135. _this._isPointerDown = false;
  88136. }
  88137. });
  88138. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88139. var now = BABYLON.Tools.Now;
  88140. var dt = 0;
  88141. if (_this._lastFrameTime != null) {
  88142. dt = now - _this._lastFrameTime;
  88143. }
  88144. _this._lastFrameTime = now;
  88145. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88146. _this._applyUserInteraction();
  88147. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  88148. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  88149. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  88150. // Step camera rotation by rotation speed
  88151. if (_this._attachedCamera) {
  88152. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  88153. }
  88154. });
  88155. };
  88156. AutoRotationBehavior.prototype.detach = function () {
  88157. if (!this._attachedCamera) {
  88158. return;
  88159. }
  88160. var scene = this._attachedCamera.getScene();
  88161. if (this._onPrePointerObservableObserver) {
  88162. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88163. }
  88164. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88165. this._attachedCamera = null;
  88166. };
  88167. /**
  88168. * Returns true if user is scrolling.
  88169. * @return true if user is scrolling.
  88170. */
  88171. AutoRotationBehavior.prototype._userIsZooming = function () {
  88172. if (!this._attachedCamera) {
  88173. return false;
  88174. }
  88175. return this._attachedCamera.inertialRadiusOffset !== 0;
  88176. };
  88177. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  88178. if (!this._attachedCamera) {
  88179. return false;
  88180. }
  88181. var zoomHasHitLimit = false;
  88182. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  88183. zoomHasHitLimit = true;
  88184. }
  88185. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  88186. this._lastFrameRadius = this._attachedCamera.radius;
  88187. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  88188. };
  88189. /**
  88190. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88191. */
  88192. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  88193. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  88194. this._lastInteractionTime = BABYLON.Tools.Now;
  88195. }
  88196. };
  88197. // Tools
  88198. AutoRotationBehavior.prototype._userIsMoving = function () {
  88199. if (!this._attachedCamera) {
  88200. return false;
  88201. }
  88202. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88203. this._attachedCamera.inertialBetaOffset !== 0 ||
  88204. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88205. this._attachedCamera.inertialPanningX !== 0 ||
  88206. this._attachedCamera.inertialPanningY !== 0 ||
  88207. this._isPointerDown;
  88208. };
  88209. return AutoRotationBehavior;
  88210. }());
  88211. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  88212. })(BABYLON || (BABYLON = {}));
  88213. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  88214. var BABYLON;
  88215. (function (BABYLON) {
  88216. var NullEngineOptions = /** @class */ (function () {
  88217. function NullEngineOptions() {
  88218. this.renderWidth = 512;
  88219. this.renderHeight = 256;
  88220. this.textureSize = 512;
  88221. this.deterministicLockstep = false;
  88222. this.lockstepMaxSteps = 4;
  88223. }
  88224. return NullEngineOptions;
  88225. }());
  88226. BABYLON.NullEngineOptions = NullEngineOptions;
  88227. /**
  88228. * The null engine class provides support for headless version of babylon.js.
  88229. * This can be used in server side scenario or for testing purposes
  88230. */
  88231. var NullEngine = /** @class */ (function (_super) {
  88232. __extends(NullEngine, _super);
  88233. function NullEngine(options) {
  88234. if (options === void 0) { options = new NullEngineOptions(); }
  88235. var _this = _super.call(this, null) || this;
  88236. if (options.deterministicLockstep === undefined) {
  88237. options.deterministicLockstep = false;
  88238. }
  88239. if (options.lockstepMaxSteps === undefined) {
  88240. options.lockstepMaxSteps = 4;
  88241. }
  88242. _this._options = options;
  88243. // Init caps
  88244. // We consider we are on a webgl1 capable device
  88245. _this._caps = new BABYLON.EngineCapabilities();
  88246. _this._caps.maxTexturesImageUnits = 16;
  88247. _this._caps.maxVertexTextureImageUnits = 16;
  88248. _this._caps.maxTextureSize = 512;
  88249. _this._caps.maxCubemapTextureSize = 512;
  88250. _this._caps.maxRenderTextureSize = 512;
  88251. _this._caps.maxVertexAttribs = 16;
  88252. _this._caps.maxVaryingVectors = 16;
  88253. _this._caps.maxFragmentUniformVectors = 16;
  88254. _this._caps.maxVertexUniformVectors = 16;
  88255. // Extensions
  88256. _this._caps.standardDerivatives = false;
  88257. _this._caps.astc = null;
  88258. _this._caps.s3tc = null;
  88259. _this._caps.pvrtc = null;
  88260. _this._caps.etc1 = null;
  88261. _this._caps.etc2 = null;
  88262. _this._caps.textureAnisotropicFilterExtension = null;
  88263. _this._caps.maxAnisotropy = 0;
  88264. _this._caps.uintIndices = false;
  88265. _this._caps.fragmentDepthSupported = false;
  88266. _this._caps.highPrecisionShaderSupported = true;
  88267. _this._caps.colorBufferFloat = false;
  88268. _this._caps.textureFloat = false;
  88269. _this._caps.textureFloatLinearFiltering = false;
  88270. _this._caps.textureFloatRender = false;
  88271. _this._caps.textureHalfFloat = false;
  88272. _this._caps.textureHalfFloatLinearFiltering = false;
  88273. _this._caps.textureHalfFloatRender = false;
  88274. _this._caps.textureLOD = false;
  88275. _this._caps.drawBuffersExtension = false;
  88276. _this._caps.depthTextureExtension = false;
  88277. _this._caps.vertexArrayObject = false;
  88278. _this._caps.instancedArrays = false;
  88279. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  88280. // Wrappers
  88281. if (typeof URL === "undefined") {
  88282. URL = {
  88283. createObjectURL: function () { },
  88284. revokeObjectURL: function () { }
  88285. };
  88286. }
  88287. if (typeof Blob === "undefined") {
  88288. Blob = function () { };
  88289. }
  88290. return _this;
  88291. }
  88292. NullEngine.prototype.isDeterministicLockStep = function () {
  88293. return this._options.deterministicLockstep;
  88294. };
  88295. NullEngine.prototype.getLockstepMaxSteps = function () {
  88296. return this._options.lockstepMaxSteps;
  88297. };
  88298. NullEngine.prototype.getHardwareScalingLevel = function () {
  88299. return 1.0;
  88300. };
  88301. NullEngine.prototype.createVertexBuffer = function (vertices) {
  88302. return {
  88303. capacity: 0,
  88304. references: 1,
  88305. is32Bits: false
  88306. };
  88307. };
  88308. NullEngine.prototype.createIndexBuffer = function (indices) {
  88309. return {
  88310. capacity: 0,
  88311. references: 1,
  88312. is32Bits: false
  88313. };
  88314. };
  88315. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  88316. if (stencil === void 0) { stencil = false; }
  88317. };
  88318. NullEngine.prototype.getRenderWidth = function (useScreen) {
  88319. if (useScreen === void 0) { useScreen = false; }
  88320. if (!useScreen && this._currentRenderTarget) {
  88321. return this._currentRenderTarget.width;
  88322. }
  88323. return this._options.renderWidth;
  88324. };
  88325. NullEngine.prototype.getRenderHeight = function (useScreen) {
  88326. if (useScreen === void 0) { useScreen = false; }
  88327. if (!useScreen && this._currentRenderTarget) {
  88328. return this._currentRenderTarget.height;
  88329. }
  88330. return this._options.renderHeight;
  88331. };
  88332. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  88333. this._cachedViewport = viewport;
  88334. };
  88335. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  88336. return {
  88337. transformFeedback: null,
  88338. __SPECTOR_rebuildProgram: null
  88339. };
  88340. };
  88341. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  88342. return [];
  88343. };
  88344. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  88345. return [];
  88346. };
  88347. NullEngine.prototype.bindSamplers = function (effect) {
  88348. this._currentEffect = null;
  88349. };
  88350. NullEngine.prototype.enableEffect = function (effect) {
  88351. this._currentEffect = effect;
  88352. if (effect.onBind) {
  88353. effect.onBind(effect);
  88354. }
  88355. effect.onBindObservable.notifyObservers(effect);
  88356. };
  88357. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  88358. if (zOffset === void 0) { zOffset = 0; }
  88359. if (reverseSide === void 0) { reverseSide = false; }
  88360. };
  88361. NullEngine.prototype.setIntArray = function (uniform, array) {
  88362. };
  88363. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  88364. };
  88365. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  88366. };
  88367. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  88368. };
  88369. NullEngine.prototype.setFloatArray = function (uniform, array) {
  88370. };
  88371. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  88372. };
  88373. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  88374. };
  88375. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  88376. };
  88377. NullEngine.prototype.setArray = function (uniform, array) {
  88378. };
  88379. NullEngine.prototype.setArray2 = function (uniform, array) {
  88380. };
  88381. NullEngine.prototype.setArray3 = function (uniform, array) {
  88382. };
  88383. NullEngine.prototype.setArray4 = function (uniform, array) {
  88384. };
  88385. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  88386. };
  88387. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  88388. };
  88389. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  88390. };
  88391. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  88392. };
  88393. NullEngine.prototype.setFloat = function (uniform, value) {
  88394. };
  88395. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  88396. };
  88397. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  88398. };
  88399. NullEngine.prototype.setBool = function (uniform, bool) {
  88400. };
  88401. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  88402. };
  88403. NullEngine.prototype.setColor3 = function (uniform, color3) {
  88404. };
  88405. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  88406. };
  88407. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  88408. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  88409. if (this._alphaMode === mode) {
  88410. return;
  88411. }
  88412. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  88413. if (!noDepthWriteChange) {
  88414. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  88415. }
  88416. this._alphaMode = mode;
  88417. };
  88418. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  88419. };
  88420. NullEngine.prototype.wipeCaches = function (bruteForce) {
  88421. if (this.preventCacheWipeBetweenFrames) {
  88422. return;
  88423. }
  88424. this.resetTextureCache();
  88425. this._currentEffect = null;
  88426. if (bruteForce) {
  88427. this._currentProgram = null;
  88428. this._stencilState.reset();
  88429. this._depthCullingState.reset();
  88430. this._alphaState.reset();
  88431. }
  88432. this._cachedVertexBuffers = null;
  88433. this._cachedIndexBuffer = null;
  88434. this._cachedEffectForVertexBuffers = null;
  88435. };
  88436. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  88437. };
  88438. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  88439. };
  88440. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  88441. };
  88442. NullEngine.prototype._createTexture = function () {
  88443. return {};
  88444. };
  88445. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  88446. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88447. if (onLoad === void 0) { onLoad = null; }
  88448. if (onError === void 0) { onError = null; }
  88449. if (buffer === void 0) { buffer = null; }
  88450. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  88451. var url = String(urlArg);
  88452. texture.url = url;
  88453. texture.generateMipMaps = !noMipmap;
  88454. texture.samplingMode = samplingMode;
  88455. texture.invertY = invertY;
  88456. texture.baseWidth = this._options.textureSize;
  88457. texture.baseHeight = this._options.textureSize;
  88458. texture.width = this._options.textureSize;
  88459. texture.height = this._options.textureSize;
  88460. if (format) {
  88461. texture.format = format;
  88462. }
  88463. texture.isReady = true;
  88464. if (onLoad) {
  88465. onLoad();
  88466. }
  88467. return texture;
  88468. };
  88469. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  88470. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  88471. if (options !== undefined && typeof options === "object") {
  88472. fullOptions.generateMipMaps = options.generateMipMaps;
  88473. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  88474. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  88475. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  88476. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  88477. }
  88478. else {
  88479. fullOptions.generateMipMaps = options;
  88480. fullOptions.generateDepthBuffer = true;
  88481. fullOptions.generateStencilBuffer = false;
  88482. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88483. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  88484. }
  88485. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  88486. var width = size.width || size;
  88487. var height = size.height || size;
  88488. texture._depthStencilBuffer = {};
  88489. texture._framebuffer = {};
  88490. texture.baseWidth = width;
  88491. texture.baseHeight = height;
  88492. texture.width = width;
  88493. texture.height = height;
  88494. texture.isReady = true;
  88495. texture.samples = 1;
  88496. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  88497. texture.samplingMode = fullOptions.samplingMode;
  88498. texture.type = fullOptions.type;
  88499. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  88500. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  88501. return texture;
  88502. };
  88503. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  88504. texture.samplingMode = samplingMode;
  88505. };
  88506. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  88507. if (this._currentRenderTarget) {
  88508. this.unBindFramebuffer(this._currentRenderTarget);
  88509. }
  88510. this._currentRenderTarget = texture;
  88511. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  88512. if (this._cachedViewport && !forceFullscreenViewport) {
  88513. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  88514. }
  88515. };
  88516. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  88517. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  88518. this._currentRenderTarget = null;
  88519. if (onBeforeUnbind) {
  88520. if (texture._MSAAFramebuffer) {
  88521. this._currentFramebuffer = texture._framebuffer;
  88522. }
  88523. onBeforeUnbind();
  88524. }
  88525. this._currentFramebuffer = null;
  88526. };
  88527. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  88528. var vbo = {
  88529. capacity: 1,
  88530. references: 1,
  88531. is32Bits: false
  88532. };
  88533. return vbo;
  88534. };
  88535. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  88536. if (offset === void 0) { offset = 0; }
  88537. };
  88538. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  88539. };
  88540. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  88541. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  88542. this._boundTexturesCache[this._activeChannel] = texture;
  88543. }
  88544. };
  88545. NullEngine.prototype._bindTexture = function (channel, texture) {
  88546. if (channel < 0) {
  88547. return;
  88548. }
  88549. this._bindTextureDirectly(0, texture);
  88550. };
  88551. NullEngine.prototype._releaseBuffer = function (buffer) {
  88552. buffer.references--;
  88553. if (buffer.references === 0) {
  88554. return true;
  88555. }
  88556. return false;
  88557. };
  88558. return NullEngine;
  88559. }(BABYLON.Engine));
  88560. BABYLON.NullEngine = NullEngine;
  88561. })(BABYLON || (BABYLON = {}));
  88562. //# sourceMappingURL=babylon.nullEngine.js.map
  88563. var BABYLON;
  88564. (function (BABYLON) {
  88565. /**
  88566. * This class can be used to get instrumentation data from a Babylon engine
  88567. */
  88568. var EngineInstrumentation = /** @class */ (function () {
  88569. function EngineInstrumentation(engine) {
  88570. this.engine = engine;
  88571. this._captureGPUFrameTime = false;
  88572. this._gpuFrameTime = new BABYLON.PerfCounter();
  88573. this._captureShaderCompilationTime = false;
  88574. this._shaderCompilationTime = new BABYLON.PerfCounter();
  88575. // Observers
  88576. this._onBeginFrameObserver = null;
  88577. this._onEndFrameObserver = null;
  88578. this._onBeforeShaderCompilationObserver = null;
  88579. this._onAfterShaderCompilationObserver = null;
  88580. }
  88581. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  88582. // Properties
  88583. /**
  88584. * Gets the perf counter used for GPU frame time
  88585. */
  88586. get: function () {
  88587. return this._gpuFrameTime;
  88588. },
  88589. enumerable: true,
  88590. configurable: true
  88591. });
  88592. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  88593. /**
  88594. * Gets the GPU frame time capture status
  88595. */
  88596. get: function () {
  88597. return this._captureGPUFrameTime;
  88598. },
  88599. /**
  88600. * Enable or disable the GPU frame time capture
  88601. */
  88602. set: function (value) {
  88603. var _this = this;
  88604. if (value === this._captureGPUFrameTime) {
  88605. return;
  88606. }
  88607. this._captureGPUFrameTime = value;
  88608. if (value) {
  88609. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  88610. if (!_this._gpuFrameTimeToken) {
  88611. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  88612. }
  88613. });
  88614. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  88615. if (!_this._gpuFrameTimeToken) {
  88616. return;
  88617. }
  88618. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  88619. if (time > -1) {
  88620. _this._gpuFrameTimeToken = null;
  88621. _this._gpuFrameTime.fetchNewFrame();
  88622. _this._gpuFrameTime.addCount(time, true);
  88623. }
  88624. });
  88625. }
  88626. else {
  88627. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88628. this._onBeginFrameObserver = null;
  88629. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88630. this._onEndFrameObserver = null;
  88631. }
  88632. },
  88633. enumerable: true,
  88634. configurable: true
  88635. });
  88636. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  88637. /**
  88638. * Gets the perf counter used for shader compilation time
  88639. */
  88640. get: function () {
  88641. return this._shaderCompilationTime;
  88642. },
  88643. enumerable: true,
  88644. configurable: true
  88645. });
  88646. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  88647. /**
  88648. * Gets the shader compilation time capture status
  88649. */
  88650. get: function () {
  88651. return this._captureShaderCompilationTime;
  88652. },
  88653. /**
  88654. * Enable or disable the shader compilation time capture
  88655. */
  88656. set: function (value) {
  88657. var _this = this;
  88658. if (value === this._captureShaderCompilationTime) {
  88659. return;
  88660. }
  88661. this._captureShaderCompilationTime = value;
  88662. if (value) {
  88663. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  88664. _this._shaderCompilationTime.fetchNewFrame();
  88665. _this._shaderCompilationTime.beginMonitoring();
  88666. });
  88667. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  88668. _this._shaderCompilationTime.endMonitoring();
  88669. });
  88670. }
  88671. else {
  88672. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88673. this._onBeforeShaderCompilationObserver = null;
  88674. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88675. this._onAfterShaderCompilationObserver = null;
  88676. }
  88677. },
  88678. enumerable: true,
  88679. configurable: true
  88680. });
  88681. EngineInstrumentation.prototype.dispose = function () {
  88682. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88683. this._onBeginFrameObserver = null;
  88684. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88685. this._onEndFrameObserver = null;
  88686. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88687. this._onBeforeShaderCompilationObserver = null;
  88688. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88689. this._onAfterShaderCompilationObserver = null;
  88690. this.engine = null;
  88691. };
  88692. return EngineInstrumentation;
  88693. }());
  88694. BABYLON.EngineInstrumentation = EngineInstrumentation;
  88695. })(BABYLON || (BABYLON = {}));
  88696. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  88697. var BABYLON;
  88698. (function (BABYLON) {
  88699. /**
  88700. * This class can be used to get instrumentation data from a Babylon engine
  88701. */
  88702. var SceneInstrumentation = /** @class */ (function () {
  88703. function SceneInstrumentation(scene) {
  88704. var _this = this;
  88705. this.scene = scene;
  88706. this._captureActiveMeshesEvaluationTime = false;
  88707. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  88708. this._captureRenderTargetsRenderTime = false;
  88709. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  88710. this._captureFrameTime = false;
  88711. this._frameTime = new BABYLON.PerfCounter();
  88712. this._captureRenderTime = false;
  88713. this._renderTime = new BABYLON.PerfCounter();
  88714. this._captureInterFrameTime = false;
  88715. this._interFrameTime = new BABYLON.PerfCounter();
  88716. this._captureParticlesRenderTime = false;
  88717. this._particlesRenderTime = new BABYLON.PerfCounter();
  88718. this._captureSpritesRenderTime = false;
  88719. this._spritesRenderTime = new BABYLON.PerfCounter();
  88720. this._capturePhysicsTime = false;
  88721. this._physicsTime = new BABYLON.PerfCounter();
  88722. this._captureAnimationsTime = false;
  88723. this._animationsTime = new BABYLON.PerfCounter();
  88724. // Observers
  88725. this._onBeforeActiveMeshesEvaluationObserver = null;
  88726. this._onAfterActiveMeshesEvaluationObserver = null;
  88727. this._onBeforeRenderTargetsRenderObserver = null;
  88728. this._onAfterRenderTargetsRenderObserver = null;
  88729. this._onAfterRenderObserver = null;
  88730. this._onBeforeDrawPhaseObserver = null;
  88731. this._onAfterDrawPhaseObserver = null;
  88732. this._onBeforeAnimationsObserver = null;
  88733. this._onBeforeParticlesRenderingObserver = null;
  88734. this._onAfterParticlesRenderingObserver = null;
  88735. this._onBeforeSpritesRenderingObserver = null;
  88736. this._onAfterSpritesRenderingObserver = null;
  88737. this._onBeforePhysicsObserver = null;
  88738. this._onAfterPhysicsObserver = null;
  88739. this._onAfterAnimationsObserver = null;
  88740. // Before render
  88741. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  88742. if (_this._captureActiveMeshesEvaluationTime) {
  88743. _this._activeMeshesEvaluationTime.fetchNewFrame();
  88744. }
  88745. if (_this._captureRenderTargetsRenderTime) {
  88746. _this._renderTargetsRenderTime.fetchNewFrame();
  88747. }
  88748. if (_this._captureFrameTime) {
  88749. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  88750. _this._frameTime.beginMonitoring();
  88751. }
  88752. if (_this._captureInterFrameTime) {
  88753. _this._interFrameTime.endMonitoring();
  88754. }
  88755. if (_this._captureParticlesRenderTime) {
  88756. _this._particlesRenderTime.fetchNewFrame();
  88757. }
  88758. if (_this._captureSpritesRenderTime) {
  88759. _this._spritesRenderTime.fetchNewFrame();
  88760. }
  88761. if (_this._captureAnimationsTime) {
  88762. _this._animationsTime.beginMonitoring();
  88763. }
  88764. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  88765. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  88766. });
  88767. // After render
  88768. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  88769. if (_this._captureFrameTime) {
  88770. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  88771. _this._frameTime.endMonitoring();
  88772. }
  88773. if (_this._captureRenderTime) {
  88774. _this._renderTime.endMonitoring(false);
  88775. }
  88776. if (_this._captureInterFrameTime) {
  88777. _this._interFrameTime.beginMonitoring();
  88778. }
  88779. });
  88780. }
  88781. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  88782. // Properties
  88783. /**
  88784. * Gets the perf counter used for active meshes evaluation time
  88785. */
  88786. get: function () {
  88787. return this._activeMeshesEvaluationTime;
  88788. },
  88789. enumerable: true,
  88790. configurable: true
  88791. });
  88792. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  88793. /**
  88794. * Gets the active meshes evaluation time capture status
  88795. */
  88796. get: function () {
  88797. return this._captureActiveMeshesEvaluationTime;
  88798. },
  88799. /**
  88800. * Enable or disable the active meshes evaluation time capture
  88801. */
  88802. set: function (value) {
  88803. var _this = this;
  88804. if (value === this._captureActiveMeshesEvaluationTime) {
  88805. return;
  88806. }
  88807. this._captureActiveMeshesEvaluationTime = value;
  88808. if (value) {
  88809. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  88810. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  88811. _this._activeMeshesEvaluationTime.beginMonitoring();
  88812. });
  88813. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  88814. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  88815. _this._activeMeshesEvaluationTime.endMonitoring();
  88816. });
  88817. }
  88818. else {
  88819. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88820. this._onBeforeActiveMeshesEvaluationObserver = null;
  88821. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88822. this._onAfterActiveMeshesEvaluationObserver = null;
  88823. }
  88824. },
  88825. enumerable: true,
  88826. configurable: true
  88827. });
  88828. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  88829. /**
  88830. * Gets the perf counter used for render targets render time
  88831. */
  88832. get: function () {
  88833. return this._renderTargetsRenderTime;
  88834. },
  88835. enumerable: true,
  88836. configurable: true
  88837. });
  88838. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  88839. /**
  88840. * Gets the render targets render time capture status
  88841. */
  88842. get: function () {
  88843. return this._captureRenderTargetsRenderTime;
  88844. },
  88845. /**
  88846. * Enable or disable the render targets render time capture
  88847. */
  88848. set: function (value) {
  88849. var _this = this;
  88850. if (value === this._captureRenderTargetsRenderTime) {
  88851. return;
  88852. }
  88853. this._captureRenderTargetsRenderTime = value;
  88854. if (value) {
  88855. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  88856. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  88857. _this._renderTargetsRenderTime.beginMonitoring();
  88858. });
  88859. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  88860. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  88861. _this._renderTargetsRenderTime.endMonitoring(false);
  88862. });
  88863. }
  88864. else {
  88865. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88866. this._onBeforeRenderTargetsRenderObserver = null;
  88867. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88868. this._onAfterRenderTargetsRenderObserver = null;
  88869. }
  88870. },
  88871. enumerable: true,
  88872. configurable: true
  88873. });
  88874. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  88875. /**
  88876. * Gets the perf counter used for particles render time
  88877. */
  88878. get: function () {
  88879. return this._particlesRenderTime;
  88880. },
  88881. enumerable: true,
  88882. configurable: true
  88883. });
  88884. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  88885. /**
  88886. * Gets the particles render time capture status
  88887. */
  88888. get: function () {
  88889. return this._captureParticlesRenderTime;
  88890. },
  88891. /**
  88892. * Enable or disable the particles render time capture
  88893. */
  88894. set: function (value) {
  88895. var _this = this;
  88896. if (value === this._captureParticlesRenderTime) {
  88897. return;
  88898. }
  88899. this._captureParticlesRenderTime = value;
  88900. if (value) {
  88901. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  88902. BABYLON.Tools.StartPerformanceCounter("Particles");
  88903. _this._particlesRenderTime.beginMonitoring();
  88904. });
  88905. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  88906. BABYLON.Tools.EndPerformanceCounter("Particles");
  88907. _this._particlesRenderTime.endMonitoring(false);
  88908. });
  88909. }
  88910. else {
  88911. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88912. this._onBeforeParticlesRenderingObserver = null;
  88913. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88914. this._onAfterParticlesRenderingObserver = null;
  88915. }
  88916. },
  88917. enumerable: true,
  88918. configurable: true
  88919. });
  88920. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  88921. /**
  88922. * Gets the perf counter used for sprites render time
  88923. */
  88924. get: function () {
  88925. return this._spritesRenderTime;
  88926. },
  88927. enumerable: true,
  88928. configurable: true
  88929. });
  88930. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  88931. /**
  88932. * Gets the sprites render time capture status
  88933. */
  88934. get: function () {
  88935. return this._captureSpritesRenderTime;
  88936. },
  88937. /**
  88938. * Enable or disable the sprites render time capture
  88939. */
  88940. set: function (value) {
  88941. var _this = this;
  88942. if (value === this._captureSpritesRenderTime) {
  88943. return;
  88944. }
  88945. this._captureSpritesRenderTime = value;
  88946. if (value) {
  88947. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  88948. BABYLON.Tools.StartPerformanceCounter("Sprites");
  88949. _this._spritesRenderTime.beginMonitoring();
  88950. });
  88951. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  88952. BABYLON.Tools.EndPerformanceCounter("Sprites");
  88953. _this._spritesRenderTime.endMonitoring(false);
  88954. });
  88955. }
  88956. else {
  88957. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88958. this._onBeforeSpritesRenderingObserver = null;
  88959. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88960. this._onAfterSpritesRenderingObserver = null;
  88961. }
  88962. },
  88963. enumerable: true,
  88964. configurable: true
  88965. });
  88966. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  88967. /**
  88968. * Gets the perf counter used for physics time
  88969. */
  88970. get: function () {
  88971. return this._physicsTime;
  88972. },
  88973. enumerable: true,
  88974. configurable: true
  88975. });
  88976. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  88977. /**
  88978. * Gets the physics time capture status
  88979. */
  88980. get: function () {
  88981. return this._capturePhysicsTime;
  88982. },
  88983. /**
  88984. * Enable or disable the physics time capture
  88985. */
  88986. set: function (value) {
  88987. var _this = this;
  88988. if (value === this._capturePhysicsTime) {
  88989. return;
  88990. }
  88991. this._capturePhysicsTime = value;
  88992. if (value) {
  88993. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  88994. BABYLON.Tools.StartPerformanceCounter("Physics");
  88995. _this._physicsTime.beginMonitoring();
  88996. });
  88997. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  88998. BABYLON.Tools.EndPerformanceCounter("Physics");
  88999. _this._physicsTime.endMonitoring();
  89000. });
  89001. }
  89002. else {
  89003. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89004. this._onBeforePhysicsObserver = null;
  89005. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89006. this._onAfterPhysicsObserver = null;
  89007. }
  89008. },
  89009. enumerable: true,
  89010. configurable: true
  89011. });
  89012. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  89013. /**
  89014. * Gets the perf counter used for animations time
  89015. */
  89016. get: function () {
  89017. return this._animationsTime;
  89018. },
  89019. enumerable: true,
  89020. configurable: true
  89021. });
  89022. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  89023. /**
  89024. * Gets the animations time capture status
  89025. */
  89026. get: function () {
  89027. return this._captureAnimationsTime;
  89028. },
  89029. /**
  89030. * Enable or disable the animations time capture
  89031. */
  89032. set: function (value) {
  89033. var _this = this;
  89034. if (value === this._captureAnimationsTime) {
  89035. return;
  89036. }
  89037. this._captureAnimationsTime = value;
  89038. if (value) {
  89039. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  89040. _this._animationsTime.endMonitoring();
  89041. });
  89042. }
  89043. else {
  89044. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89045. this._onAfterAnimationsObserver = null;
  89046. }
  89047. },
  89048. enumerable: true,
  89049. configurable: true
  89050. });
  89051. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  89052. /**
  89053. * Gets the perf counter used for frame time capture
  89054. */
  89055. get: function () {
  89056. return this._frameTime;
  89057. },
  89058. enumerable: true,
  89059. configurable: true
  89060. });
  89061. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  89062. /**
  89063. * Gets the frame time capture status
  89064. */
  89065. get: function () {
  89066. return this._captureFrameTime;
  89067. },
  89068. /**
  89069. * Enable or disable the frame time capture
  89070. */
  89071. set: function (value) {
  89072. this._captureFrameTime = value;
  89073. },
  89074. enumerable: true,
  89075. configurable: true
  89076. });
  89077. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  89078. /**
  89079. * Gets the perf counter used for inter-frames time capture
  89080. */
  89081. get: function () {
  89082. return this._interFrameTime;
  89083. },
  89084. enumerable: true,
  89085. configurable: true
  89086. });
  89087. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  89088. /**
  89089. * Gets the inter-frames time capture status
  89090. */
  89091. get: function () {
  89092. return this._captureInterFrameTime;
  89093. },
  89094. /**
  89095. * Enable or disable the inter-frames time capture
  89096. */
  89097. set: function (value) {
  89098. this._captureInterFrameTime = value;
  89099. },
  89100. enumerable: true,
  89101. configurable: true
  89102. });
  89103. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  89104. /**
  89105. * Gets the perf counter used for render time capture
  89106. */
  89107. get: function () {
  89108. return this._renderTime;
  89109. },
  89110. enumerable: true,
  89111. configurable: true
  89112. });
  89113. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  89114. /**
  89115. * Gets the render time capture status
  89116. */
  89117. get: function () {
  89118. return this._captureRenderTime;
  89119. },
  89120. /**
  89121. * Enable or disable the render time capture
  89122. */
  89123. set: function (value) {
  89124. var _this = this;
  89125. if (value === this._captureRenderTime) {
  89126. return;
  89127. }
  89128. this._captureRenderTime = value;
  89129. if (value) {
  89130. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  89131. _this._renderTime.beginMonitoring();
  89132. BABYLON.Tools.StartPerformanceCounter("Main render");
  89133. });
  89134. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  89135. _this._renderTime.endMonitoring(false);
  89136. BABYLON.Tools.EndPerformanceCounter("Main render");
  89137. });
  89138. }
  89139. else {
  89140. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89141. this._onBeforeDrawPhaseObserver = null;
  89142. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89143. this._onAfterDrawPhaseObserver = null;
  89144. }
  89145. },
  89146. enumerable: true,
  89147. configurable: true
  89148. });
  89149. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  89150. /**
  89151. * Gets the perf counter used for draw calls
  89152. */
  89153. get: function () {
  89154. return this.scene.getEngine()._drawCalls;
  89155. },
  89156. enumerable: true,
  89157. configurable: true
  89158. });
  89159. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  89160. /**
  89161. * Gets the perf counter used for texture collisions
  89162. */
  89163. get: function () {
  89164. return this.scene.getEngine()._textureCollisions;
  89165. },
  89166. enumerable: true,
  89167. configurable: true
  89168. });
  89169. SceneInstrumentation.prototype.dispose = function () {
  89170. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89171. this._onAfterRenderObserver = null;
  89172. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89173. this._onBeforeActiveMeshesEvaluationObserver = null;
  89174. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89175. this._onAfterActiveMeshesEvaluationObserver = null;
  89176. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89177. this._onBeforeRenderTargetsRenderObserver = null;
  89178. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89179. this._onAfterRenderTargetsRenderObserver = null;
  89180. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  89181. this._onBeforeAnimationsObserver = null;
  89182. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89183. this._onBeforeParticlesRenderingObserver = null;
  89184. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89185. this._onAfterParticlesRenderingObserver = null;
  89186. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89187. this._onBeforeSpritesRenderingObserver = null;
  89188. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89189. this._onAfterSpritesRenderingObserver = null;
  89190. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89191. this._onBeforeDrawPhaseObserver = null;
  89192. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89193. this._onAfterDrawPhaseObserver = null;
  89194. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89195. this._onBeforePhysicsObserver = null;
  89196. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89197. this._onAfterPhysicsObserver = null;
  89198. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89199. this._onAfterAnimationsObserver = null;
  89200. this.scene = null;
  89201. };
  89202. return SceneInstrumentation;
  89203. }());
  89204. BABYLON.SceneInstrumentation = SceneInstrumentation;
  89205. })(BABYLON || (BABYLON = {}));
  89206. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  89207. var BABYLON;
  89208. (function (BABYLON) {
  89209. var _TimeToken = /** @class */ (function () {
  89210. function _TimeToken() {
  89211. this._timeElapsedQueryEnded = false;
  89212. }
  89213. return _TimeToken;
  89214. }());
  89215. BABYLON._TimeToken = _TimeToken;
  89216. })(BABYLON || (BABYLON = {}));
  89217. //# sourceMappingURL=babylon.timeToken.js.map
  89218. var BABYLON;
  89219. (function (BABYLON) {
  89220. /**
  89221. * Background material defines definition.
  89222. * @ignore Mainly internal Use
  89223. */
  89224. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  89225. __extends(BackgroundMaterialDefines, _super);
  89226. /**
  89227. * Constructor of the defines.
  89228. */
  89229. function BackgroundMaterialDefines() {
  89230. var _this = _super.call(this) || this;
  89231. /**
  89232. * True if the diffuse texture is in use.
  89233. */
  89234. _this.DIFFUSE = false;
  89235. /**
  89236. * The direct UV channel to use.
  89237. */
  89238. _this.DIFFUSEDIRECTUV = 0;
  89239. /**
  89240. * True if the diffuse texture is in gamma space.
  89241. */
  89242. _this.GAMMADIFFUSE = false;
  89243. /**
  89244. * True if the diffuse texture has opacity in the alpha channel.
  89245. */
  89246. _this.DIFFUSEHASALPHA = false;
  89247. /**
  89248. * True if you want the material to fade to transparent at grazing angle.
  89249. */
  89250. _this.OPACITYFRESNEL = false;
  89251. /**
  89252. * True if an extra blur needs to be added in the reflection.
  89253. */
  89254. _this.REFLECTIONBLUR = false;
  89255. /**
  89256. * True if you want the material to fade to reflection at grazing angle.
  89257. */
  89258. _this.REFLECTIONFRESNEL = false;
  89259. /**
  89260. * True if you want the material to falloff as far as you move away from the scene center.
  89261. */
  89262. _this.REFLECTIONFALLOFF = false;
  89263. /**
  89264. * False if the current Webgl implementation does not support the texture lod extension.
  89265. */
  89266. _this.TEXTURELODSUPPORT = false;
  89267. /**
  89268. * True to ensure the data are premultiplied.
  89269. */
  89270. _this.PREMULTIPLYALPHA = false;
  89271. /**
  89272. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  89273. */
  89274. _this.USERGBCOLOR = false;
  89275. /**
  89276. * True to add noise in order to reduce the banding effect.
  89277. */
  89278. _this.NOISE = false;
  89279. /**
  89280. * is the reflection texture in BGR color scheme?
  89281. * Mainly used to solve a bug in ios10 video tag
  89282. */
  89283. _this.REFLECTIONBGR = false;
  89284. _this.IMAGEPROCESSING = false;
  89285. _this.VIGNETTE = false;
  89286. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  89287. _this.VIGNETTEBLENDMODEOPAQUE = false;
  89288. _this.TONEMAPPING = false;
  89289. _this.CONTRAST = false;
  89290. _this.COLORCURVES = false;
  89291. _this.COLORGRADING = false;
  89292. _this.COLORGRADING3D = false;
  89293. _this.SAMPLER3DGREENDEPTH = false;
  89294. _this.SAMPLER3DBGRMAP = false;
  89295. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  89296. _this.EXPOSURE = false;
  89297. _this.GRAIN = false;
  89298. // Reflection.
  89299. _this.REFLECTION = false;
  89300. _this.REFLECTIONMAP_3D = false;
  89301. _this.REFLECTIONMAP_SPHERICAL = false;
  89302. _this.REFLECTIONMAP_PLANAR = false;
  89303. _this.REFLECTIONMAP_CUBIC = false;
  89304. _this.REFLECTIONMAP_PROJECTION = false;
  89305. _this.REFLECTIONMAP_SKYBOX = false;
  89306. _this.REFLECTIONMAP_EXPLICIT = false;
  89307. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89308. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89309. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89310. _this.INVERTCUBICMAP = false;
  89311. _this.REFLECTIONMAP_OPPOSITEZ = false;
  89312. _this.LODINREFLECTIONALPHA = false;
  89313. _this.GAMMAREFLECTION = false;
  89314. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  89315. // Default BJS.
  89316. _this.MAINUV1 = false;
  89317. _this.MAINUV2 = false;
  89318. _this.UV1 = false;
  89319. _this.UV2 = false;
  89320. _this.CLIPPLANE = false;
  89321. _this.POINTSIZE = false;
  89322. _this.FOG = false;
  89323. _this.NORMAL = false;
  89324. _this.NUM_BONE_INFLUENCERS = 0;
  89325. _this.BonesPerMesh = 0;
  89326. _this.INSTANCES = false;
  89327. _this.SHADOWFLOAT = false;
  89328. _this.rebuild();
  89329. return _this;
  89330. }
  89331. return BackgroundMaterialDefines;
  89332. }(BABYLON.MaterialDefines));
  89333. /**
  89334. * Background material used to create an efficient environement around your scene.
  89335. */
  89336. var BackgroundMaterial = /** @class */ (function (_super) {
  89337. __extends(BackgroundMaterial, _super);
  89338. /**
  89339. * Instantiates a Background Material in the given scene
  89340. * @param name The friendly name of the material
  89341. * @param scene The scene to add the material to
  89342. */
  89343. function BackgroundMaterial(name, scene) {
  89344. var _this = _super.call(this, name, scene) || this;
  89345. /**
  89346. * Key light Color (multiply against the R channel of the environement texture)
  89347. */
  89348. _this.primaryColor = BABYLON.Color3.White();
  89349. /**
  89350. * Key light Level (allowing HDR output of the background)
  89351. */
  89352. _this.primaryLevel = 1;
  89353. /**
  89354. * Secondary light Color (multiply against the G channel of the environement texture)
  89355. */
  89356. _this.secondaryColor = BABYLON.Color3.Gray();
  89357. /**
  89358. * Secondary light Level (allowing HDR output of the background)
  89359. */
  89360. _this.secondaryLevel = 1;
  89361. /**
  89362. * Tertiary light Color (multiply against the B channel of the environement texture)
  89363. */
  89364. _this.tertiaryColor = BABYLON.Color3.Black();
  89365. /**
  89366. * Tertiary light Level (allowing HDR output of the background)
  89367. */
  89368. _this.tertiaryLevel = 1;
  89369. /**
  89370. * Reflection Texture used in the material.
  89371. * Should be author in a specific way for the best result (refer to the documentation).
  89372. */
  89373. _this.reflectionTexture = null;
  89374. /**
  89375. * Reflection Texture level of blur.
  89376. *
  89377. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  89378. * texture twice.
  89379. */
  89380. _this.reflectionBlur = 0;
  89381. /**
  89382. * Diffuse Texture used in the material.
  89383. * Should be author in a specific way for the best result (refer to the documentation).
  89384. */
  89385. _this.diffuseTexture = null;
  89386. _this._shadowLights = null;
  89387. /**
  89388. * Specify the list of lights casting shadow on the material.
  89389. * All scene shadow lights will be included if null.
  89390. */
  89391. _this.shadowLights = null;
  89392. /**
  89393. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  89394. * soft lighting on the background.
  89395. */
  89396. _this.shadowBlurScale = 1;
  89397. /**
  89398. * Helps adjusting the shadow to a softer level if required.
  89399. * 0 means black shadows and 1 means no shadows.
  89400. */
  89401. _this.shadowLevel = 0;
  89402. /**
  89403. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  89404. * It is usually zero but might be interesting to modify according to your setup.
  89405. */
  89406. _this.sceneCenter = BABYLON.Vector3.Zero();
  89407. /**
  89408. * This helps specifying that the material is falling off to the sky box at grazing angle.
  89409. * This helps ensuring a nice transition when the camera goes under the ground.
  89410. */
  89411. _this.opacityFresnel = true;
  89412. /**
  89413. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  89414. * This helps adding a mirror texture on the ground.
  89415. */
  89416. _this.reflectionFresnel = false;
  89417. /**
  89418. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  89419. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  89420. */
  89421. _this.reflectionFalloffDistance = 0.0;
  89422. /**
  89423. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  89424. */
  89425. _this.reflectionAmount = 1.0;
  89426. /**
  89427. * This specifies the weight of the reflection at grazing angle.
  89428. */
  89429. _this.reflectionReflectance0 = 0.05;
  89430. /**
  89431. * This specifies the weight of the reflection at a perpendicular point of view.
  89432. */
  89433. _this.reflectionReflectance90 = 0.5;
  89434. /**
  89435. * Helps to directly use the maps channels instead of their level.
  89436. */
  89437. _this.useRGBColor = true;
  89438. /**
  89439. * This helps reducing the banding effect that could occur on the background.
  89440. */
  89441. _this.enableNoise = false;
  89442. _this._fovMultiplier = 1.0;
  89443. /**
  89444. * Enable the FOV adjustment feature controlled by fovMultiplier.
  89445. * @type {boolean}
  89446. */
  89447. _this.useEquirectangularFOV = false;
  89448. _this._maxSimultaneousLights = 4;
  89449. /**
  89450. * Number of Simultaneous lights allowed on the material.
  89451. */
  89452. _this.maxSimultaneousLights = 4;
  89453. /**
  89454. * Keep track of the image processing observer to allow dispose and replace.
  89455. */
  89456. _this._imageProcessingObserver = null;
  89457. /**
  89458. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  89459. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  89460. */
  89461. _this.switchToBGR = false;
  89462. // Temp values kept as cache in the material.
  89463. _this._renderTargets = new BABYLON.SmartArray(16);
  89464. _this._reflectionControls = BABYLON.Vector4.Zero();
  89465. // Setup the default processing configuration to the scene.
  89466. _this._attachImageProcessingConfiguration(null);
  89467. _this.getRenderTargetTextures = function () {
  89468. _this._renderTargets.reset();
  89469. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  89470. _this._renderTargets.push(_this._diffuseTexture);
  89471. }
  89472. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  89473. _this._renderTargets.push(_this._reflectionTexture);
  89474. }
  89475. return _this._renderTargets;
  89476. };
  89477. return _this;
  89478. }
  89479. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  89480. /**
  89481. * Sets the reflection reflectance fresnel values according to the default standard
  89482. * empirically know to work well :-)
  89483. */
  89484. set: function (value) {
  89485. var reflectionWeight = value;
  89486. if (reflectionWeight < 0.5) {
  89487. reflectionWeight = reflectionWeight * 2.0;
  89488. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  89489. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  89490. }
  89491. else {
  89492. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  89493. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  89494. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  89495. }
  89496. },
  89497. enumerable: true,
  89498. configurable: true
  89499. });
  89500. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  89501. /**
  89502. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  89503. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  89504. * Recommended to be keep at 1.0 except for special cases.
  89505. */
  89506. get: function () {
  89507. return this._fovMultiplier;
  89508. },
  89509. set: function (value) {
  89510. if (isNaN(value)) {
  89511. value = 1.0;
  89512. }
  89513. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  89514. },
  89515. enumerable: true,
  89516. configurable: true
  89517. });
  89518. /**
  89519. * Attaches a new image processing configuration to the PBR Material.
  89520. * @param configuration (if null the scene configuration will be use)
  89521. */
  89522. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  89523. var _this = this;
  89524. if (configuration === this._imageProcessingConfiguration) {
  89525. return;
  89526. }
  89527. // Detaches observer.
  89528. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89529. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89530. }
  89531. // Pick the scene configuration if needed.
  89532. if (!configuration) {
  89533. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  89534. }
  89535. else {
  89536. this._imageProcessingConfiguration = configuration;
  89537. }
  89538. // Attaches observer.
  89539. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89540. _this._markAllSubMeshesAsImageProcessingDirty();
  89541. });
  89542. };
  89543. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  89544. /**
  89545. * Gets the image processing configuration used either in this material.
  89546. */
  89547. get: function () {
  89548. return this._imageProcessingConfiguration;
  89549. },
  89550. /**
  89551. * Sets the Default image processing configuration used either in the this material.
  89552. *
  89553. * If sets to null, the scene one is in use.
  89554. */
  89555. set: function (value) {
  89556. this._attachImageProcessingConfiguration(value);
  89557. // Ensure the effect will be rebuilt.
  89558. this._markAllSubMeshesAsTexturesDirty();
  89559. },
  89560. enumerable: true,
  89561. configurable: true
  89562. });
  89563. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  89564. /**
  89565. * Gets wether the color curves effect is enabled.
  89566. */
  89567. get: function () {
  89568. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89569. },
  89570. /**
  89571. * Sets wether the color curves effect is enabled.
  89572. */
  89573. set: function (value) {
  89574. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89575. },
  89576. enumerable: true,
  89577. configurable: true
  89578. });
  89579. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  89580. /**
  89581. * Gets wether the color grading effect is enabled.
  89582. */
  89583. get: function () {
  89584. return this.imageProcessingConfiguration.colorGradingEnabled;
  89585. },
  89586. /**
  89587. * Gets wether the color grading effect is enabled.
  89588. */
  89589. set: function (value) {
  89590. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89591. },
  89592. enumerable: true,
  89593. configurable: true
  89594. });
  89595. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  89596. /**
  89597. * Gets wether tonemapping is enabled or not.
  89598. */
  89599. get: function () {
  89600. return this._imageProcessingConfiguration.toneMappingEnabled;
  89601. },
  89602. /**
  89603. * Sets wether tonemapping is enabled or not
  89604. */
  89605. set: function (value) {
  89606. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89607. },
  89608. enumerable: true,
  89609. configurable: true
  89610. });
  89611. ;
  89612. ;
  89613. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  89614. /**
  89615. * The camera exposure used on this material.
  89616. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89617. * This corresponds to a photographic exposure.
  89618. */
  89619. get: function () {
  89620. return this._imageProcessingConfiguration.exposure;
  89621. },
  89622. /**
  89623. * The camera exposure used on this material.
  89624. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89625. * This corresponds to a photographic exposure.
  89626. */
  89627. set: function (value) {
  89628. this._imageProcessingConfiguration.exposure = value;
  89629. },
  89630. enumerable: true,
  89631. configurable: true
  89632. });
  89633. ;
  89634. ;
  89635. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  89636. /**
  89637. * Gets The camera contrast used on this material.
  89638. */
  89639. get: function () {
  89640. return this._imageProcessingConfiguration.contrast;
  89641. },
  89642. /**
  89643. * Sets The camera contrast used on this material.
  89644. */
  89645. set: function (value) {
  89646. this._imageProcessingConfiguration.contrast = value;
  89647. },
  89648. enumerable: true,
  89649. configurable: true
  89650. });
  89651. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  89652. /**
  89653. * Gets the Color Grading 2D Lookup Texture.
  89654. */
  89655. get: function () {
  89656. return this._imageProcessingConfiguration.colorGradingTexture;
  89657. },
  89658. /**
  89659. * Sets the Color Grading 2D Lookup Texture.
  89660. */
  89661. set: function (value) {
  89662. this.imageProcessingConfiguration.colorGradingTexture = value;
  89663. },
  89664. enumerable: true,
  89665. configurable: true
  89666. });
  89667. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  89668. /**
  89669. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89670. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89671. * 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;
  89672. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89673. */
  89674. get: function () {
  89675. return this.imageProcessingConfiguration.colorCurves;
  89676. },
  89677. /**
  89678. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89679. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89680. * 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;
  89681. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89682. */
  89683. set: function (value) {
  89684. this.imageProcessingConfiguration.colorCurves = value;
  89685. },
  89686. enumerable: true,
  89687. configurable: true
  89688. });
  89689. /**
  89690. * The entire material has been created in order to prevent overdraw.
  89691. * @returns false
  89692. */
  89693. BackgroundMaterial.prototype.needAlphaTesting = function () {
  89694. return true;
  89695. };
  89696. /**
  89697. * The entire material has been created in order to prevent overdraw.
  89698. * @returns true if blending is enable
  89699. */
  89700. BackgroundMaterial.prototype.needAlphaBlending = function () {
  89701. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  89702. };
  89703. /**
  89704. * Checks wether the material is ready to be rendered for a given mesh.
  89705. * @param mesh The mesh to render
  89706. * @param subMesh The submesh to check against
  89707. * @param useInstances Specify wether or not the material is used with instances
  89708. * @returns true if all the dependencies are ready (Textures, Effects...)
  89709. */
  89710. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89711. var _this = this;
  89712. if (useInstances === void 0) { useInstances = false; }
  89713. if (subMesh.effect && this.isFrozen) {
  89714. if (this._wasPreviouslyReady) {
  89715. return true;
  89716. }
  89717. }
  89718. if (!subMesh._materialDefines) {
  89719. subMesh._materialDefines = new BackgroundMaterialDefines();
  89720. }
  89721. var scene = this.getScene();
  89722. var defines = subMesh._materialDefines;
  89723. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89724. if (defines._renderId === scene.getRenderId()) {
  89725. return true;
  89726. }
  89727. }
  89728. var engine = scene.getEngine();
  89729. // Lights
  89730. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  89731. defines._needNormals = true;
  89732. // Textures
  89733. if (defines._areTexturesDirty) {
  89734. defines._needUVs = false;
  89735. if (scene.texturesEnabled) {
  89736. if (scene.getEngine().getCaps().textureLOD) {
  89737. defines.TEXTURELODSUPPORT = true;
  89738. }
  89739. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89740. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  89741. return false;
  89742. }
  89743. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  89744. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  89745. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  89746. defines.OPACITYFRESNEL = this._opacityFresnel;
  89747. }
  89748. else {
  89749. defines.DIFFUSE = false;
  89750. defines.DIFFUSEHASALPHA = false;
  89751. defines.GAMMADIFFUSE = false;
  89752. defines.OPACITYFRESNEL = false;
  89753. }
  89754. var reflectionTexture = this._reflectionTexture;
  89755. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89756. if (!reflectionTexture.isReadyOrNotBlocking()) {
  89757. return false;
  89758. }
  89759. defines.REFLECTION = true;
  89760. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  89761. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  89762. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  89763. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  89764. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  89765. defines.REFLECTIONBGR = this.switchToBGR;
  89766. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  89767. defines.INVERTCUBICMAP = true;
  89768. }
  89769. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  89770. switch (reflectionTexture.coordinatesMode) {
  89771. case BABYLON.Texture.CUBIC_MODE:
  89772. case BABYLON.Texture.INVCUBIC_MODE:
  89773. defines.REFLECTIONMAP_CUBIC = true;
  89774. break;
  89775. case BABYLON.Texture.EXPLICIT_MODE:
  89776. defines.REFLECTIONMAP_EXPLICIT = true;
  89777. break;
  89778. case BABYLON.Texture.PLANAR_MODE:
  89779. defines.REFLECTIONMAP_PLANAR = true;
  89780. break;
  89781. case BABYLON.Texture.PROJECTION_MODE:
  89782. defines.REFLECTIONMAP_PROJECTION = true;
  89783. break;
  89784. case BABYLON.Texture.SKYBOX_MODE:
  89785. defines.REFLECTIONMAP_SKYBOX = true;
  89786. break;
  89787. case BABYLON.Texture.SPHERICAL_MODE:
  89788. defines.REFLECTIONMAP_SPHERICAL = true;
  89789. break;
  89790. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  89791. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  89792. break;
  89793. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  89794. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  89795. break;
  89796. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  89797. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  89798. break;
  89799. }
  89800. if (this.reflectionFresnel) {
  89801. defines.REFLECTIONFRESNEL = true;
  89802. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  89803. this._reflectionControls.x = this.reflectionAmount;
  89804. this._reflectionControls.y = this.reflectionReflectance0;
  89805. this._reflectionControls.z = this.reflectionReflectance90;
  89806. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  89807. }
  89808. else {
  89809. defines.REFLECTIONFRESNEL = false;
  89810. defines.REFLECTIONFALLOFF = false;
  89811. }
  89812. }
  89813. else {
  89814. defines.REFLECTION = false;
  89815. defines.REFLECTIONFALLOFF = false;
  89816. defines.REFLECTIONBLUR = false;
  89817. defines.REFLECTIONMAP_3D = false;
  89818. defines.REFLECTIONMAP_SPHERICAL = false;
  89819. defines.REFLECTIONMAP_PLANAR = false;
  89820. defines.REFLECTIONMAP_CUBIC = false;
  89821. defines.REFLECTIONMAP_PROJECTION = false;
  89822. defines.REFLECTIONMAP_SKYBOX = false;
  89823. defines.REFLECTIONMAP_EXPLICIT = false;
  89824. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89825. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89826. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89827. defines.INVERTCUBICMAP = false;
  89828. defines.REFLECTIONMAP_OPPOSITEZ = false;
  89829. defines.LODINREFLECTIONALPHA = false;
  89830. defines.GAMMAREFLECTION = false;
  89831. }
  89832. }
  89833. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  89834. defines.USERGBCOLOR = this._useRGBColor;
  89835. defines.NOISE = this._enableNoise;
  89836. }
  89837. if (defines._areImageProcessingDirty) {
  89838. if (!this._imageProcessingConfiguration.isReady()) {
  89839. return false;
  89840. }
  89841. this._imageProcessingConfiguration.prepareDefines(defines);
  89842. }
  89843. // Misc.
  89844. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  89845. // Values that need to be evaluated on every frame
  89846. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  89847. // Attribs
  89848. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  89849. if (mesh) {
  89850. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89851. mesh.createNormals(true);
  89852. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  89853. }
  89854. }
  89855. }
  89856. // Get correct effect
  89857. if (defines.isDirty) {
  89858. defines.markAsProcessed();
  89859. scene.resetCachedMaterial();
  89860. // Fallbacks
  89861. var fallbacks = new BABYLON.EffectFallbacks();
  89862. if (defines.FOG) {
  89863. fallbacks.addFallback(0, "FOG");
  89864. }
  89865. if (defines.POINTSIZE) {
  89866. fallbacks.addFallback(1, "POINTSIZE");
  89867. }
  89868. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  89869. if (defines.NUM_BONE_INFLUENCERS > 0) {
  89870. fallbacks.addCPUSkinningFallback(0, mesh);
  89871. }
  89872. //Attributes
  89873. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89874. if (defines.NORMAL) {
  89875. attribs.push(BABYLON.VertexBuffer.NormalKind);
  89876. }
  89877. if (defines.UV1) {
  89878. attribs.push(BABYLON.VertexBuffer.UVKind);
  89879. }
  89880. if (defines.UV2) {
  89881. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89882. }
  89883. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  89884. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  89885. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  89886. "vFogInfos", "vFogColor", "pointSize",
  89887. "vClipPlane", "mBones",
  89888. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  89889. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  89890. "shadowLevel", "alpha",
  89891. "vBackgroundCenter", "vReflectionControl",
  89892. "vDiffuseInfos", "diffuseMatrix",
  89893. ];
  89894. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  89895. var uniformBuffers = ["Material", "Scene"];
  89896. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  89897. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  89898. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  89899. uniformsNames: uniforms,
  89900. uniformBuffersNames: uniformBuffers,
  89901. samplers: samplers,
  89902. defines: defines,
  89903. maxSimultaneousLights: this._maxSimultaneousLights
  89904. });
  89905. var onCompiled = function (effect) {
  89906. if (_this.onCompiled) {
  89907. _this.onCompiled(effect);
  89908. }
  89909. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  89910. };
  89911. var join = defines.toString();
  89912. subMesh.setEffect(scene.getEngine().createEffect("background", {
  89913. attributes: attribs,
  89914. uniformsNames: uniforms,
  89915. uniformBuffersNames: uniformBuffers,
  89916. samplers: samplers,
  89917. defines: join,
  89918. fallbacks: fallbacks,
  89919. onCompiled: onCompiled,
  89920. onError: this.onError,
  89921. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  89922. }, engine), defines);
  89923. this.buildUniformLayout();
  89924. }
  89925. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89926. return false;
  89927. }
  89928. defines._renderId = scene.getRenderId();
  89929. this._wasPreviouslyReady = true;
  89930. return true;
  89931. };
  89932. /**
  89933. * Build the uniform buffer used in the material.
  89934. */
  89935. BackgroundMaterial.prototype.buildUniformLayout = function () {
  89936. // Order is important !
  89937. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  89938. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  89939. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  89940. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  89941. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  89942. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  89943. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  89944. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  89945. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  89946. this._uniformBuffer.addUniform("pointSize", 1);
  89947. this._uniformBuffer.addUniform("shadowLevel", 1);
  89948. this._uniformBuffer.addUniform("alpha", 1);
  89949. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  89950. this._uniformBuffer.addUniform("vReflectionControl", 4);
  89951. this._uniformBuffer.create();
  89952. };
  89953. /**
  89954. * Unbind the material.
  89955. */
  89956. BackgroundMaterial.prototype.unbind = function () {
  89957. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  89958. this._uniformBuffer.setTexture("diffuseSampler", null);
  89959. }
  89960. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  89961. this._uniformBuffer.setTexture("reflectionSampler", null);
  89962. }
  89963. _super.prototype.unbind.call(this);
  89964. };
  89965. /**
  89966. * Bind only the world matrix to the material.
  89967. * @param world The world matrix to bind.
  89968. */
  89969. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  89970. this._activeEffect.setMatrix("world", world);
  89971. };
  89972. /**
  89973. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  89974. * @param world The world matrix to bind.
  89975. * @param subMesh The submesh to bind for.
  89976. */
  89977. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89978. var scene = this.getScene();
  89979. var defines = subMesh._materialDefines;
  89980. if (!defines) {
  89981. return;
  89982. }
  89983. var effect = subMesh.effect;
  89984. if (!effect) {
  89985. return;
  89986. }
  89987. this._activeEffect = effect;
  89988. // Matrices
  89989. this.bindOnlyWorldMatrix(world);
  89990. // Bones
  89991. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  89992. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  89993. if (mustRebind) {
  89994. this._uniformBuffer.bindToEffect(effect, "Material");
  89995. this.bindViewProjection(effect);
  89996. var reflectionTexture = this._reflectionTexture;
  89997. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  89998. // Texture uniforms
  89999. if (scene.texturesEnabled) {
  90000. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90001. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  90002. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  90003. }
  90004. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90005. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  90006. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  90007. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  90008. }
  90009. }
  90010. if (this.shadowLevel > 0) {
  90011. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  90012. }
  90013. this._uniformBuffer.updateFloat("alpha", this.alpha);
  90014. // Point size
  90015. if (this.pointsCloud) {
  90016. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  90017. }
  90018. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  90019. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  90020. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  90021. }
  90022. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  90023. // Textures
  90024. if (scene.texturesEnabled) {
  90025. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90026. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  90027. }
  90028. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90029. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  90030. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90031. }
  90032. else if (!defines.REFLECTIONBLUR) {
  90033. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90034. }
  90035. else {
  90036. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  90037. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  90038. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  90039. }
  90040. if (defines.REFLECTIONFRESNEL) {
  90041. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  90042. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  90043. }
  90044. }
  90045. }
  90046. // Clip plane
  90047. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  90048. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  90049. }
  90050. if (mustRebind || !this.isFrozen) {
  90051. if (scene.lightsEnabled) {
  90052. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  90053. }
  90054. // View
  90055. this.bindView(effect);
  90056. // Fog
  90057. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90058. // image processing
  90059. this._imageProcessingConfiguration.bind(this._activeEffect);
  90060. }
  90061. this._uniformBuffer.update();
  90062. this._afterBind(mesh);
  90063. };
  90064. /**
  90065. * Dispose the material.
  90066. * @param forceDisposeEffect Force disposal of the associated effect.
  90067. * @param forceDisposeTextures Force disposal of the associated textures.
  90068. */
  90069. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  90070. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  90071. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  90072. if (forceDisposeTextures) {
  90073. if (this.diffuseTexture) {
  90074. this.diffuseTexture.dispose();
  90075. }
  90076. if (this.reflectionTexture) {
  90077. this.reflectionTexture.dispose();
  90078. }
  90079. }
  90080. this._renderTargets.dispose();
  90081. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90082. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90083. }
  90084. _super.prototype.dispose.call(this, forceDisposeEffect);
  90085. };
  90086. /**
  90087. * Clones the material.
  90088. * @param name The cloned name.
  90089. * @returns The cloned material.
  90090. */
  90091. BackgroundMaterial.prototype.clone = function (name) {
  90092. var _this = this;
  90093. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  90094. };
  90095. /**
  90096. * Serializes the current material to its JSON representation.
  90097. * @returns The JSON representation.
  90098. */
  90099. BackgroundMaterial.prototype.serialize = function () {
  90100. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90101. serializationObject.customType = "BABYLON.BackgroundMaterial";
  90102. return serializationObject;
  90103. };
  90104. /**
  90105. * Gets the class name of the material
  90106. * @returns "BackgroundMaterial"
  90107. */
  90108. BackgroundMaterial.prototype.getClassName = function () {
  90109. return "BackgroundMaterial";
  90110. };
  90111. /**
  90112. * Parse a JSON input to create back a background material.
  90113. * @param source The JSON data to parse
  90114. * @param scene The scene to create the parsed material in
  90115. * @param rootUrl The root url of the assets the material depends upon
  90116. * @returns the instantiated BackgroundMaterial.
  90117. */
  90118. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  90119. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  90120. };
  90121. /**
  90122. * Standard reflectance value at parallel view angle.
  90123. */
  90124. BackgroundMaterial.StandardReflectance0 = 0.05;
  90125. /**
  90126. * Standard reflectance value at grazing angle.
  90127. */
  90128. BackgroundMaterial.StandardReflectance90 = 0.5;
  90129. __decorate([
  90130. BABYLON.serializeAsColor3()
  90131. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  90132. __decorate([
  90133. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90134. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  90135. __decorate([
  90136. BABYLON.serialize()
  90137. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  90138. __decorate([
  90139. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90140. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  90141. __decorate([
  90142. BABYLON.serializeAsColor3()
  90143. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  90144. __decorate([
  90145. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90146. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  90147. __decorate([
  90148. BABYLON.serialize()
  90149. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  90150. __decorate([
  90151. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90152. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  90153. __decorate([
  90154. BABYLON.serializeAsColor3()
  90155. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  90156. __decorate([
  90157. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90158. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  90159. __decorate([
  90160. BABYLON.serialize()
  90161. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  90162. __decorate([
  90163. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90164. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  90165. __decorate([
  90166. BABYLON.serializeAsTexture()
  90167. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  90168. __decorate([
  90169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90170. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  90171. __decorate([
  90172. BABYLON.serialize()
  90173. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  90174. __decorate([
  90175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90176. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  90177. __decorate([
  90178. BABYLON.serializeAsTexture()
  90179. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  90180. __decorate([
  90181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90182. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  90183. __decorate([
  90184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90185. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  90186. __decorate([
  90187. BABYLON.serialize()
  90188. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  90189. __decorate([
  90190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90191. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  90192. __decorate([
  90193. BABYLON.serialize()
  90194. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  90195. __decorate([
  90196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90197. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  90198. __decorate([
  90199. BABYLON.serializeAsVector3()
  90200. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  90201. __decorate([
  90202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90203. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  90204. __decorate([
  90205. BABYLON.serialize()
  90206. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  90207. __decorate([
  90208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90209. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  90210. __decorate([
  90211. BABYLON.serialize()
  90212. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  90213. __decorate([
  90214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90215. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  90216. __decorate([
  90217. BABYLON.serialize()
  90218. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  90219. __decorate([
  90220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90221. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  90222. __decorate([
  90223. BABYLON.serialize()
  90224. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  90225. __decorate([
  90226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90227. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  90228. __decorate([
  90229. BABYLON.serialize()
  90230. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  90231. __decorate([
  90232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90233. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  90234. __decorate([
  90235. BABYLON.serialize()
  90236. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  90237. __decorate([
  90238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90239. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  90240. __decorate([
  90241. BABYLON.serialize()
  90242. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  90243. __decorate([
  90244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90245. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  90246. __decorate([
  90247. BABYLON.serialize()
  90248. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  90249. __decorate([
  90250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90251. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  90252. __decorate([
  90253. BABYLON.serialize()
  90254. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  90255. __decorate([
  90256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90257. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  90258. __decorate([
  90259. BABYLON.serializeAsImageProcessingConfiguration()
  90260. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  90261. return BackgroundMaterial;
  90262. }(BABYLON.PushMaterial));
  90263. BABYLON.BackgroundMaterial = BackgroundMaterial;
  90264. })(BABYLON || (BABYLON = {}));
  90265. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  90266. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90267. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90268. s = arguments[i];
  90269. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90270. t[p] = s[p];
  90271. }
  90272. return t;
  90273. };
  90274. var BABYLON;
  90275. (function (BABYLON) {
  90276. /**
  90277. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  90278. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  90279. * It also helps with the default setup of your imageProcessing configuration.
  90280. */
  90281. var EnvironmentHelper = /** @class */ (function () {
  90282. /**
  90283. * constructor
  90284. * @param options
  90285. * @param scene The scene to add the material to
  90286. */
  90287. function EnvironmentHelper(options, scene) {
  90288. var _this = this;
  90289. this._errorHandler = function (message, exception) {
  90290. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  90291. };
  90292. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  90293. this._scene = scene;
  90294. this.onErrorObservable = new BABYLON.Observable();
  90295. this._setupBackground();
  90296. this._setupImageProcessing();
  90297. }
  90298. /**
  90299. * Creates the default options for the helper.
  90300. */
  90301. EnvironmentHelper._getDefaultOptions = function () {
  90302. return {
  90303. createGround: true,
  90304. groundSize: 15,
  90305. groundTexture: this._groundTextureCDNUrl,
  90306. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90307. groundOpacity: 0.9,
  90308. enableGroundShadow: true,
  90309. groundShadowLevel: 0.5,
  90310. enableGroundMirror: false,
  90311. groundMirrorSizeRatio: 0.3,
  90312. groundMirrorBlurKernel: 64,
  90313. groundMirrorAmount: 1,
  90314. groundMirrorFresnelWeight: 1,
  90315. groundMirrorFallOffDistance: 0,
  90316. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  90317. groundYBias: 0.00001,
  90318. createSkybox: true,
  90319. skyboxSize: 20,
  90320. skyboxTexture: this._skyboxTextureCDNUrl,
  90321. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90322. backgroundYRotation: 0,
  90323. sizeAuto: true,
  90324. rootPosition: BABYLON.Vector3.Zero(),
  90325. setupImageProcessing: true,
  90326. environmentTexture: this._environmentTextureCDNUrl,
  90327. cameraExposure: 0.8,
  90328. cameraContrast: 1.2,
  90329. toneMappingEnabled: true,
  90330. };
  90331. };
  90332. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  90333. /**
  90334. * Gets the root mesh created by the helper.
  90335. */
  90336. get: function () {
  90337. return this._rootMesh;
  90338. },
  90339. enumerable: true,
  90340. configurable: true
  90341. });
  90342. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  90343. /**
  90344. * Gets the skybox created by the helper.
  90345. */
  90346. get: function () {
  90347. return this._skybox;
  90348. },
  90349. enumerable: true,
  90350. configurable: true
  90351. });
  90352. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  90353. /**
  90354. * Gets the skybox texture created by the helper.
  90355. */
  90356. get: function () {
  90357. return this._skyboxTexture;
  90358. },
  90359. enumerable: true,
  90360. configurable: true
  90361. });
  90362. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  90363. /**
  90364. * Gets the skybox material created by the helper.
  90365. */
  90366. get: function () {
  90367. return this._skyboxMaterial;
  90368. },
  90369. enumerable: true,
  90370. configurable: true
  90371. });
  90372. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  90373. /**
  90374. * Gets the ground mesh created by the helper.
  90375. */
  90376. get: function () {
  90377. return this._ground;
  90378. },
  90379. enumerable: true,
  90380. configurable: true
  90381. });
  90382. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  90383. /**
  90384. * Gets the ground texture created by the helper.
  90385. */
  90386. get: function () {
  90387. return this._groundTexture;
  90388. },
  90389. enumerable: true,
  90390. configurable: true
  90391. });
  90392. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  90393. /**
  90394. * Gets the ground mirror created by the helper.
  90395. */
  90396. get: function () {
  90397. return this._groundMirror;
  90398. },
  90399. enumerable: true,
  90400. configurable: true
  90401. });
  90402. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  90403. /**
  90404. * Gets the ground mirror render list to helps pushing the meshes
  90405. * you wish in the ground reflection.
  90406. */
  90407. get: function () {
  90408. if (this._groundMirror) {
  90409. return this._groundMirror.renderList;
  90410. }
  90411. return null;
  90412. },
  90413. enumerable: true,
  90414. configurable: true
  90415. });
  90416. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  90417. /**
  90418. * Gets the ground material created by the helper.
  90419. */
  90420. get: function () {
  90421. return this._groundMaterial;
  90422. },
  90423. enumerable: true,
  90424. configurable: true
  90425. });
  90426. /**
  90427. * Updates the background according to the new options
  90428. * @param options
  90429. */
  90430. EnvironmentHelper.prototype.updateOptions = function (options) {
  90431. var newOptions = __assign({}, this._options, options);
  90432. if (this._ground && !newOptions.createGround) {
  90433. this._ground.dispose();
  90434. this._ground = null;
  90435. }
  90436. if (this._groundMaterial && !newOptions.createGround) {
  90437. this._groundMaterial.dispose();
  90438. this._groundMaterial = null;
  90439. }
  90440. if (this._groundTexture) {
  90441. if (this._options.groundTexture != newOptions.groundTexture) {
  90442. this._groundTexture.dispose();
  90443. this._groundTexture = null;
  90444. }
  90445. }
  90446. if (this._skybox && !newOptions.createSkybox) {
  90447. this._skybox.dispose();
  90448. this._skybox = null;
  90449. }
  90450. if (this._skyboxMaterial && !newOptions.createSkybox) {
  90451. this._skyboxMaterial.dispose();
  90452. this._skyboxMaterial = null;
  90453. }
  90454. if (this._skyboxTexture) {
  90455. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  90456. this._skyboxTexture.dispose();
  90457. this._skyboxTexture = null;
  90458. }
  90459. }
  90460. if (this._groundMirror && !newOptions.enableGroundMirror) {
  90461. this._groundMirror.dispose();
  90462. this._groundMirror = null;
  90463. }
  90464. if (this._scene.environmentTexture) {
  90465. if (this._options.environmentTexture != newOptions.environmentTexture) {
  90466. this._scene.environmentTexture.dispose();
  90467. }
  90468. }
  90469. this._options = newOptions;
  90470. this._setupBackground();
  90471. this._setupImageProcessing();
  90472. };
  90473. /**
  90474. * Sets the primary color of all the available elements.
  90475. * @param color
  90476. */
  90477. EnvironmentHelper.prototype.setMainColor = function (color) {
  90478. if (this.groundMaterial) {
  90479. this.groundMaterial.primaryColor = color;
  90480. }
  90481. if (this.skyboxMaterial) {
  90482. this.skyboxMaterial.primaryColor = color;
  90483. }
  90484. if (this.groundMirror) {
  90485. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  90486. }
  90487. };
  90488. /**
  90489. * Setup the image processing according to the specified options.
  90490. */
  90491. EnvironmentHelper.prototype._setupImageProcessing = function () {
  90492. if (this._options.setupImageProcessing) {
  90493. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  90494. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  90495. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  90496. this._setupEnvironmentTexture();
  90497. }
  90498. };
  90499. /**
  90500. * Setup the environment texture according to the specified options.
  90501. */
  90502. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  90503. if (this._scene.environmentTexture) {
  90504. return;
  90505. }
  90506. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  90507. this._scene.environmentTexture = this._options.environmentTexture;
  90508. return;
  90509. }
  90510. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  90511. this._scene.environmentTexture = environmentTexture;
  90512. };
  90513. /**
  90514. * Setup the background according to the specified options.
  90515. */
  90516. EnvironmentHelper.prototype._setupBackground = function () {
  90517. if (!this._rootMesh) {
  90518. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  90519. }
  90520. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  90521. var sceneSize = this._getSceneSize();
  90522. if (this._options.createGround) {
  90523. this._setupGround(sceneSize);
  90524. this._setupGroundMaterial();
  90525. this._setupGroundDiffuseTexture();
  90526. if (this._options.enableGroundMirror) {
  90527. this._setupGroundMirrorTexture(sceneSize);
  90528. }
  90529. this._setupMirrorInGroundMaterial();
  90530. }
  90531. if (this._options.createSkybox) {
  90532. this._setupSkybox(sceneSize);
  90533. this._setupSkyboxMaterial();
  90534. this._setupSkyboxReflectionTexture();
  90535. }
  90536. this._rootMesh.position.x = sceneSize.rootPosition.x;
  90537. this._rootMesh.position.z = sceneSize.rootPosition.z;
  90538. this._rootMesh.position.y = sceneSize.rootPosition.y;
  90539. };
  90540. /**
  90541. * Get the scene sizes according to the setup.
  90542. */
  90543. EnvironmentHelper.prototype._getSceneSize = function () {
  90544. var _this = this;
  90545. var groundSize = this._options.groundSize;
  90546. var skyboxSize = this._options.skyboxSize;
  90547. var rootPosition = this._options.rootPosition;
  90548. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  90549. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90550. }
  90551. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  90552. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  90553. });
  90554. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  90555. if (this._options.sizeAuto) {
  90556. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  90557. this._scene.activeCamera.upperRadiusLimit) {
  90558. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  90559. skyboxSize = groundSize;
  90560. }
  90561. var sceneDiagonalLenght = sceneDiagonal.length();
  90562. if (sceneDiagonalLenght > groundSize) {
  90563. groundSize = sceneDiagonalLenght * 2;
  90564. skyboxSize = groundSize;
  90565. }
  90566. // 10 % bigger.
  90567. groundSize *= 1.1;
  90568. skyboxSize *= 1.5;
  90569. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  90570. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  90571. }
  90572. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90573. };
  90574. /**
  90575. * Setup the ground according to the specified options.
  90576. */
  90577. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  90578. var _this = this;
  90579. if (!this._ground) {
  90580. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  90581. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  90582. this._ground.parent = this._rootMesh;
  90583. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  90584. }
  90585. this._ground.receiveShadows = this._options.enableGroundShadow;
  90586. };
  90587. /**
  90588. * Setup the ground material according to the specified options.
  90589. */
  90590. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  90591. if (!this._groundMaterial) {
  90592. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  90593. }
  90594. this._groundMaterial.alpha = this._options.groundOpacity;
  90595. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  90596. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  90597. this._groundMaterial.primaryLevel = 1;
  90598. this._groundMaterial.primaryColor = this._options.groundColor;
  90599. this._groundMaterial.secondaryLevel = 0;
  90600. this._groundMaterial.tertiaryLevel = 0;
  90601. this._groundMaterial.useRGBColor = false;
  90602. this._groundMaterial.enableNoise = true;
  90603. if (this._ground) {
  90604. this._ground.material = this._groundMaterial;
  90605. }
  90606. };
  90607. /**
  90608. * Setup the ground diffuse texture according to the specified options.
  90609. */
  90610. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  90611. if (!this._groundMaterial) {
  90612. return;
  90613. }
  90614. if (this._groundTexture) {
  90615. return;
  90616. }
  90617. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  90618. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  90619. return;
  90620. }
  90621. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  90622. diffuseTexture.gammaSpace = false;
  90623. diffuseTexture.hasAlpha = true;
  90624. this._groundMaterial.diffuseTexture = diffuseTexture;
  90625. };
  90626. /**
  90627. * Setup the ground mirror texture according to the specified options.
  90628. */
  90629. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  90630. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90631. if (!this._groundMirror) {
  90632. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  90633. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  90634. this._groundMirror.anisotropicFilteringLevel = 1;
  90635. this._groundMirror.wrapU = wrapping;
  90636. this._groundMirror.wrapV = wrapping;
  90637. this._groundMirror.gammaSpace = false;
  90638. if (this._groundMirror.renderList) {
  90639. for (var i = 0; i < this._scene.meshes.length; i++) {
  90640. var mesh = this._scene.meshes[i];
  90641. if (mesh !== this._ground &&
  90642. mesh !== this._skybox &&
  90643. mesh !== this._rootMesh) {
  90644. this._groundMirror.renderList.push(mesh);
  90645. }
  90646. }
  90647. }
  90648. }
  90649. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  90650. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  90651. };
  90652. /**
  90653. * Setup the ground to receive the mirror texture.
  90654. */
  90655. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  90656. if (this._groundMaterial) {
  90657. this._groundMaterial.reflectionTexture = this._groundMirror;
  90658. this._groundMaterial.reflectionFresnel = true;
  90659. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  90660. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  90661. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  90662. }
  90663. };
  90664. /**
  90665. * Setup the skybox according to the specified options.
  90666. */
  90667. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  90668. var _this = this;
  90669. if (!this._skybox) {
  90670. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  90671. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  90672. }
  90673. this._skybox.parent = this._rootMesh;
  90674. };
  90675. /**
  90676. * Setup the skybox material according to the specified options.
  90677. */
  90678. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  90679. if (!this._skybox) {
  90680. return;
  90681. }
  90682. if (!this._skyboxMaterial) {
  90683. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  90684. }
  90685. this._skyboxMaterial.useRGBColor = false;
  90686. this._skyboxMaterial.primaryLevel = 1;
  90687. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  90688. this._skyboxMaterial.secondaryLevel = 0;
  90689. this._skyboxMaterial.tertiaryLevel = 0;
  90690. this._skyboxMaterial.enableNoise = true;
  90691. this._skybox.material = this._skyboxMaterial;
  90692. };
  90693. /**
  90694. * Setup the skybox reflection texture according to the specified options.
  90695. */
  90696. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  90697. if (!this._skyboxMaterial) {
  90698. return;
  90699. }
  90700. if (this._skyboxTexture) {
  90701. return;
  90702. }
  90703. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  90704. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90705. return;
  90706. }
  90707. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  90708. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  90709. this._skyboxTexture.gammaSpace = false;
  90710. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90711. };
  90712. /**
  90713. * Dispose all the elements created by the Helper.
  90714. */
  90715. EnvironmentHelper.prototype.dispose = function () {
  90716. if (this._groundMaterial) {
  90717. this._groundMaterial.dispose(true, true);
  90718. }
  90719. if (this._skyboxMaterial) {
  90720. this._skyboxMaterial.dispose(true, true);
  90721. }
  90722. this._rootMesh.dispose(false);
  90723. };
  90724. /**
  90725. * Default ground texture URL.
  90726. */
  90727. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  90728. /**
  90729. * Default skybox texture URL.
  90730. */
  90731. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  90732. /**
  90733. * Default environment texture URL.
  90734. */
  90735. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  90736. return EnvironmentHelper;
  90737. }());
  90738. BABYLON.EnvironmentHelper = EnvironmentHelper;
  90739. })(BABYLON || (BABYLON = {}));
  90740. //# sourceMappingURL=babylon.environmentHelper.js.map
  90741. var BABYLON;
  90742. (function (BABYLON) {
  90743. /**
  90744. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  90745. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  90746. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  90747. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  90748. */
  90749. var VideoDome = /** @class */ (function (_super) {
  90750. __extends(VideoDome, _super);
  90751. /**
  90752. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  90753. * @param name Element's name, child elements will append suffixes for their own names.
  90754. * @param urlsOrVideo
  90755. * @param options An object containing optional or exposed sub element properties:
  90756. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  90757. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  90758. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  90759. * @param options **loop=true** Automatically loop video on end.
  90760. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  90761. */
  90762. function VideoDome(name, urlsOrVideo, options, scene) {
  90763. var _this = _super.call(this, name, scene) || this;
  90764. // set defaults and manage values
  90765. name = name || "videoDome";
  90766. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  90767. options.clickToPlay = Boolean(options.clickToPlay);
  90768. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  90769. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  90770. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  90771. // create
  90772. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  90773. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  90774. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  90775. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  90776. flat: false,
  90777. radius: options.size,
  90778. subdivisions: options.resolution,
  90779. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  90780. }, scene);
  90781. // configure material
  90782. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  90783. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  90784. material.reflectionTexture = _this._videoTexture;
  90785. material.useEquirectangularFOV = true;
  90786. material.fovMultiplier = 1.0;
  90787. // configure mesh
  90788. _this._mesh.material = material;
  90789. _this._mesh.parent = _this;
  90790. // optional configuration
  90791. if (options.clickToPlay) {
  90792. scene.onPointerUp = function () {
  90793. _this._videoTexture.video.play();
  90794. };
  90795. }
  90796. return _this;
  90797. }
  90798. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  90799. /**
  90800. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90801. * Also see the options.resolution property.
  90802. */
  90803. get: function () {
  90804. return this._material.fovMultiplier;
  90805. },
  90806. set: function (value) {
  90807. this._material.fovMultiplier = value;
  90808. },
  90809. enumerable: true,
  90810. configurable: true
  90811. });
  90812. /**
  90813. * Releases all associated resources
  90814. */
  90815. VideoDome.prototype.dispose = function () {
  90816. _super.prototype.dispose.call(this);
  90817. this._videoTexture.dispose();
  90818. this._mesh.dispose();
  90819. this._material.dispose();
  90820. };
  90821. return VideoDome;
  90822. }(BABYLON.Node));
  90823. BABYLON.VideoDome = VideoDome;
  90824. })(BABYLON || (BABYLON = {}));
  90825. //# sourceMappingURL=babylon.videoDome.js.map
  90826. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0,1.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 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) {\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+gravity)*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","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","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","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}","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}","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}","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}","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"};
  90827. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef 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};","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};"};
  90828. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  90829. globalObject["BABYLON"] = BABYLON
  90830. return BABYLON;
  90831. });
  90832. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16)))
  90833. /***/ }),
  90834. /* 1 */
  90835. /***/ (function(module, exports, __webpack_require__) {
  90836. "use strict";
  90837. Object.defineProperty(exports, "__esModule", { value: true });
  90838. var babylonjs_1 = __webpack_require__(0);
  90839. var helper_1 = __webpack_require__(2);
  90840. var HTMLMapper = (function () {
  90841. function HTMLMapper() {
  90842. }
  90843. HTMLMapper.prototype.map = function (element) {
  90844. var config = {};
  90845. var _loop_1 = function (attrIdx) {
  90846. var attr = element.attributes.item(attrIdx);
  90847. var split = attr.nodeName.split('.');
  90848. split.reduce(function (currentConfig, key, idx) {
  90849. var camelKey = helper_1.kebabToCamel(key);
  90850. if (idx === split.length - 1) {
  90851. var val = attr.nodeValue;
  90852. if (val === "true") {
  90853. val = true;
  90854. }
  90855. else if (val === "false") {
  90856. val = false;
  90857. }
  90858. else {
  90859. var number = parseFloat(val);
  90860. if (!isNaN(number)) {
  90861. val = number;
  90862. }
  90863. }
  90864. currentConfig[camelKey] = val;
  90865. }
  90866. else {
  90867. currentConfig[camelKey] = currentConfig[camelKey] || {};
  90868. }
  90869. return currentConfig[camelKey];
  90870. }, config);
  90871. };
  90872. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  90873. _loop_1(attrIdx);
  90874. }
  90875. return config;
  90876. };
  90877. return HTMLMapper;
  90878. }());
  90879. var JSONMapper = (function () {
  90880. function JSONMapper() {
  90881. }
  90882. JSONMapper.prototype.map = function (rawSource) {
  90883. return JSON.parse(rawSource);
  90884. };
  90885. return JSONMapper;
  90886. }());
  90887. var DOMMapper = (function () {
  90888. function DOMMapper() {
  90889. }
  90890. DOMMapper.prototype.map = function (baseElement) {
  90891. var htmlMapper = new HTMLMapper();
  90892. var config = htmlMapper.map(baseElement);
  90893. var traverseChildren = function (element, partConfig) {
  90894. var children = element.children;
  90895. if (children.length) {
  90896. for (var i = 0; i < children.length; ++i) {
  90897. var item = children.item(i);
  90898. var configMapped = htmlMapper.map(item);
  90899. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  90900. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  90901. partConfig[key] = [];
  90902. }
  90903. else {
  90904. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  90905. partConfig.push(configMapped);
  90906. }
  90907. else if (partConfig[key]) {
  90908. element.setAttribute('array', 'true');
  90909. var oldItem = partConfig[key];
  90910. partConfig = [oldItem, configMapped];
  90911. }
  90912. else {
  90913. partConfig[key] = configMapped;
  90914. }
  90915. }
  90916. traverseChildren(item, partConfig[key] || configMapped);
  90917. }
  90918. }
  90919. return partConfig;
  90920. };
  90921. traverseChildren(baseElement, config);
  90922. return config;
  90923. };
  90924. return DOMMapper;
  90925. }());
  90926. var MapperManager = (function () {
  90927. function MapperManager() {
  90928. this.mappers = {
  90929. "html": new HTMLMapper(),
  90930. "json": new JSONMapper(),
  90931. "dom": new DOMMapper()
  90932. };
  90933. }
  90934. MapperManager.prototype.getMapper = function (type) {
  90935. if (!this.mappers[type]) {
  90936. babylonjs_1.Tools.Error("No mapper defined for " + type);
  90937. }
  90938. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  90939. };
  90940. MapperManager.prototype.registerMapper = function (type, mapper) {
  90941. this.mappers[type] = mapper;
  90942. };
  90943. MapperManager.DefaultMapper = 'json';
  90944. return MapperManager;
  90945. }());
  90946. exports.MapperManager = MapperManager;
  90947. exports.mapperManager = new MapperManager();
  90948. /***/ }),
  90949. /* 2 */
  90950. /***/ (function(module, exports, __webpack_require__) {
  90951. "use strict";
  90952. Object.defineProperty(exports, "__esModule", { value: true });
  90953. function isUrl(urlToCheck) {
  90954. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  90955. return true;
  90956. }
  90957. return false;
  90958. }
  90959. exports.isUrl = isUrl;
  90960. function kebabToCamel(s) {
  90961. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  90962. }
  90963. exports.kebabToCamel = kebabToCamel;
  90964. function camelToKebab(str) {
  90965. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  90966. }
  90967. exports.camelToKebab = camelToKebab;
  90968. /***/ }),
  90969. /* 3 */
  90970. /***/ (function(module, exports, __webpack_require__) {
  90971. "use strict";
  90972. Object.defineProperty(exports, "__esModule", { value: true });
  90973. var babylonjs_1 = __webpack_require__(0);
  90974. var ViewerManager = (function () {
  90975. function ViewerManager() {
  90976. this.viewers = {};
  90977. this.onViewerAddedObservable = new babylonjs_1.Observable();
  90978. }
  90979. ViewerManager.prototype.addViewer = function (viewer) {
  90980. this.viewers[viewer.getBaseId()] = viewer;
  90981. this._onViewerAdded(viewer);
  90982. };
  90983. ViewerManager.prototype.getViewerById = function (id) {
  90984. return this.viewers[id];
  90985. };
  90986. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  90987. for (var id in this.viewers) {
  90988. if (this.viewers[id].containerElement === element) {
  90989. return this.getViewerById(id);
  90990. }
  90991. }
  90992. };
  90993. ViewerManager.prototype.getViewerPromiseById = function (id) {
  90994. var _this = this;
  90995. return new Promise(function (resolve, reject) {
  90996. var localViewer = _this.getViewerById(id);
  90997. if (localViewer) {
  90998. return resolve(localViewer);
  90999. }
  91000. var viewerFunction = function (viewer) {
  91001. if (viewer.getBaseId() === id) {
  91002. resolve(viewer);
  91003. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  91004. }
  91005. };
  91006. _this.onViewerAddedObservable.add(viewerFunction);
  91007. });
  91008. };
  91009. ViewerManager.prototype._onViewerAdded = function (viewer) {
  91010. this.onViewerAdded && this.onViewerAdded(viewer);
  91011. this.onViewerAddedObservable.notifyObservers(viewer);
  91012. };
  91013. return ViewerManager;
  91014. }());
  91015. exports.ViewerManager = ViewerManager;
  91016. exports.viewerManager = new ViewerManager();
  91017. /***/ }),
  91018. /* 4 */
  91019. /***/ (function(module, exports, __webpack_require__) {
  91020. "use strict";
  91021. var __extends = (this && this.__extends) || (function () {
  91022. var extendStatics = Object.setPrototypeOf ||
  91023. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  91024. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91025. return function (d, b) {
  91026. extendStatics(d, b);
  91027. function __() { this.constructor = d; }
  91028. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  91029. };
  91030. })();
  91031. Object.defineProperty(exports, "__esModule", { value: true });
  91032. var viewer_1 = __webpack_require__(5);
  91033. var babylonjs_1 = __webpack_require__(0);
  91034. var DefaultViewer = (function (_super) {
  91035. __extends(DefaultViewer, _super);
  91036. function DefaultViewer(containerElement, initialConfiguration) {
  91037. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  91038. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  91039. _this.containerElement = containerElement;
  91040. _this.onModelLoaded = function (meshes) {
  91041. var hideLoadingDelay = 500;
  91042. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  91043. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  91044. }
  91045. setTimeout(function () {
  91046. _this.hideLoadingScreen();
  91047. }, hideLoadingDelay);
  91048. meshes[0].rotation.y += Math.PI;
  91049. return;
  91050. };
  91051. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  91052. return _this;
  91053. }
  91054. DefaultViewer.prototype.initScene = function () {
  91055. var _this = this;
  91056. return _super.prototype.initScene.call(this).then(function () {
  91057. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  91058. return _this.scene;
  91059. });
  91060. };
  91061. DefaultViewer.prototype.onTemplatesLoaded = function () {
  91062. var _this = this;
  91063. this.showLoadingScreen();
  91064. this.initNavbar();
  91065. var closeButton = document.getElementById('close-button');
  91066. if (closeButton) {
  91067. closeButton.addEventListener('pointerdown', function () {
  91068. _this.hideOverlayScreen();
  91069. });
  91070. }
  91071. return _super.prototype.onTemplatesLoaded.call(this);
  91072. };
  91073. DefaultViewer.prototype.initNavbar = function () {
  91074. var navbar = this.templateManager.getTemplate('navBar');
  91075. if (navbar) {
  91076. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  91077. var navbarShown_1 = true;
  91078. var timeoutCancel_1;
  91079. var triggerNavbar = function (show, evt) {
  91080. if (show === void 0) { show = false; }
  91081. if (!navbar || evt.button > 0)
  91082. return;
  91083. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  91084. if (show === navbarShown_1)
  91085. return;
  91086. if (show) {
  91087. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  91088. navbarShown_1 = show;
  91089. }
  91090. else {
  91091. var visibilityTimeout = 2000;
  91092. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  91093. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  91094. }
  91095. timeoutCancel_1 = setTimeout(function () {
  91096. if (navbar) {
  91097. navbar.parent.style.bottom = '-' + navbarHeight_1;
  91098. }
  91099. navbarShown_1 = show;
  91100. }, visibilityTimeout);
  91101. }
  91102. };
  91103. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  91104. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  91105. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  91106. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  91107. var viewerTemplate = this.templateManager.getTemplate('viewer');
  91108. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  91109. var triggerFullscren = function (eventData) {
  91110. if (viewerElement_1) {
  91111. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  91112. if (!fullscreenElement) {
  91113. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  91114. requestFullScreen.call(viewerElement_1);
  91115. }
  91116. else {
  91117. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  91118. exitFullscreen.call(document);
  91119. }
  91120. }
  91121. };
  91122. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  91123. }
  91124. };
  91125. DefaultViewer.prototype.prepareContainerElement = function () {
  91126. this.containerElement.style.position = 'relative';
  91127. this.containerElement.style.display = 'flex';
  91128. };
  91129. DefaultViewer.prototype.configureModel = function (modelConfiguration, focusMeshes) {
  91130. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91131. _super.prototype.configureModel.call(this, modelConfiguration, focusMeshes);
  91132. var navbar = this.templateManager.getTemplate('navBar');
  91133. if (!navbar)
  91134. return;
  91135. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  91136. if (metadataContainer) {
  91137. if (modelConfiguration.title !== undefined) {
  91138. var element = metadataContainer.querySelector('span.model-title');
  91139. if (element) {
  91140. element.innerHTML = modelConfiguration.title;
  91141. }
  91142. }
  91143. if (modelConfiguration.subtitle !== undefined) {
  91144. var element = metadataContainer.querySelector('span.model-subtitle');
  91145. if (element) {
  91146. element.innerHTML = modelConfiguration.subtitle;
  91147. }
  91148. }
  91149. if (modelConfiguration.thumbnail !== undefined) {
  91150. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  91151. }
  91152. }
  91153. };
  91154. DefaultViewer.prototype.loadModel = function (model) {
  91155. var _this = this;
  91156. if (model === void 0) { model = this.configuration.model; }
  91157. this.showLoadingScreen();
  91158. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  91159. console.log(error);
  91160. _this.hideLoadingScreen();
  91161. _this.showOverlayScreen('error');
  91162. return _this.scene;
  91163. });
  91164. };
  91165. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  91166. var _this = this;
  91167. var template = this.templateManager.getTemplate('overlay');
  91168. if (!template)
  91169. return Promise.resolve('Overlay template not found');
  91170. return template.show((function (template) {
  91171. var canvasRect = _this.containerElement.getBoundingClientRect();
  91172. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  91173. template.parent.style.display = 'flex';
  91174. template.parent.style.width = canvasRect.width + "px";
  91175. template.parent.style.height = canvasRect.height + "px";
  91176. template.parent.style.opacity = "1";
  91177. var subTemplate = _this.templateManager.getTemplate(subScreen);
  91178. if (!subTemplate) {
  91179. return Promise.reject(subScreen + ' template not found');
  91180. }
  91181. return subTemplate.show((function (template) {
  91182. template.parent.style.display = 'flex';
  91183. return Promise.resolve(template);
  91184. }));
  91185. }));
  91186. };
  91187. DefaultViewer.prototype.hideOverlayScreen = function () {
  91188. var template = this.templateManager.getTemplate('overlay');
  91189. if (!template)
  91190. return Promise.resolve('Overlay template not found');
  91191. return template.hide((function (template) {
  91192. template.parent.style.opacity = "0";
  91193. var onTransitionEnd = function () {
  91194. template.parent.removeEventListener("transitionend", onTransitionEnd);
  91195. template.parent.style.display = 'none';
  91196. };
  91197. template.parent.addEventListener("transitionend", onTransitionEnd);
  91198. var overlays = template.parent.querySelectorAll('.overlay');
  91199. if (overlays) {
  91200. for (var i = 0; i < overlays.length; ++i) {
  91201. var htmlElement = overlays.item(i);
  91202. htmlElement.style.display = 'none';
  91203. }
  91204. }
  91205. return Promise.resolve(template);
  91206. }));
  91207. };
  91208. DefaultViewer.prototype.showLoadingScreen = function () {
  91209. var _this = this;
  91210. var template = this.templateManager.getTemplate('loadingScreen');
  91211. if (!template)
  91212. return Promise.resolve('Loading Screen template not found');
  91213. return template.show((function (template) {
  91214. var canvasRect = _this.containerElement.getBoundingClientRect();
  91215. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  91216. template.parent.style.display = 'flex';
  91217. template.parent.style.width = canvasRect.width + "px";
  91218. template.parent.style.height = canvasRect.height + "px";
  91219. template.parent.style.opacity = "1";
  91220. template.parent.style.backgroundColor = "black";
  91221. return Promise.resolve(template);
  91222. }));
  91223. };
  91224. DefaultViewer.prototype.hideLoadingScreen = function () {
  91225. var template = this.templateManager.getTemplate('loadingScreen');
  91226. if (!template)
  91227. return Promise.resolve('Loading Screen template not found');
  91228. return template.hide((function (template) {
  91229. template.parent.style.opacity = "0";
  91230. var onTransitionEnd = function () {
  91231. template.parent.removeEventListener("transitionend", onTransitionEnd);
  91232. template.parent.style.display = 'none';
  91233. };
  91234. template.parent.addEventListener("transitionend", onTransitionEnd);
  91235. return Promise.resolve(template);
  91236. }));
  91237. };
  91238. DefaultViewer.prototype.configureLights = function (lightsConfiguration, focusMeshes) {
  91239. var _this = this;
  91240. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  91241. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91242. _super.prototype.configureLights.call(this, lightsConfiguration, focusMeshes);
  91243. if (this.configuration.lab && this.configuration.lab.flashlight) {
  91244. var pointerPosition = BABYLON.Vector3.Zero();
  91245. var lightTarget_1;
  91246. var angle = 0.5;
  91247. var exponent = Math.PI / 2;
  91248. if (typeof this.configuration.lab.flashlight === "object") {
  91249. exponent = this.configuration.lab.flashlight.exponent || exponent;
  91250. angle = this.configuration.lab.flashlight.angle || angle;
  91251. }
  91252. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  91253. if (typeof this.configuration.lab.flashlight === "object") {
  91254. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  91255. if (this.configuration.lab.flashlight.diffuse) {
  91256. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  91257. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  91258. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  91259. }
  91260. if (this.configuration.lab.flashlight.specular) {
  91261. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  91262. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  91263. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  91264. }
  91265. }
  91266. this.scene.constantlyUpdateMeshUnderPointer = true;
  91267. this.scene.onPointerObservable.add(function (eventData, eventState) {
  91268. if (eventData.type === 4 && eventData.pickInfo) {
  91269. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  91270. }
  91271. else {
  91272. lightTarget_1 = undefined;
  91273. }
  91274. });
  91275. var updateFlashlightFunction = function () {
  91276. if (_this.camera && flashlight) {
  91277. flashlight.position.copyFrom(_this.camera.position);
  91278. if (lightTarget_1) {
  91279. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  91280. }
  91281. }
  91282. };
  91283. this.scene.registerBeforeRender(updateFlashlightFunction);
  91284. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  91285. }
  91286. };
  91287. return DefaultViewer;
  91288. }(viewer_1.AbstractViewer));
  91289. exports.DefaultViewer = DefaultViewer;
  91290. /***/ }),
  91291. /* 5 */
  91292. /***/ (function(module, exports, __webpack_require__) {
  91293. "use strict";
  91294. Object.defineProperty(exports, "__esModule", { value: true });
  91295. var viewerManager_1 = __webpack_require__(3);
  91296. var templateManager_1 = __webpack_require__(19);
  91297. var loader_1 = __webpack_require__(22);
  91298. var babylonjs_1 = __webpack_require__(0);
  91299. var deepmerge = __webpack_require__(13);
  91300. var AbstractViewer = (function () {
  91301. function AbstractViewer(containerElement, initialConfiguration) {
  91302. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  91303. var _this = this;
  91304. this.containerElement = containerElement;
  91305. this.resize = function () {
  91306. if (!_this.isCanvasInDOM()) {
  91307. return;
  91308. }
  91309. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  91310. return;
  91311. }
  91312. _this.engine.resize();
  91313. };
  91314. this.render = function () {
  91315. _this.scene && _this.scene.activeCamera && _this.scene.render();
  91316. };
  91317. if (containerElement.id) {
  91318. this.baseId = containerElement.id;
  91319. }
  91320. else {
  91321. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  91322. }
  91323. this.onSceneInitObservable = new babylonjs_1.Observable();
  91324. this.onEngineInitObservable = new babylonjs_1.Observable();
  91325. this.onModelLoadedObservable = new babylonjs_1.Observable();
  91326. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  91327. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  91328. this.onInitDoneObservable = new babylonjs_1.Observable();
  91329. this.onLoaderInitObservable = new babylonjs_1.Observable();
  91330. this.registeredOnBeforerenderFunctions = [];
  91331. viewerManager_1.viewerManager.addViewer(this);
  91332. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  91333. this.prepareContainerElement();
  91334. loader_1.default.loadConfiguration(initialConfiguration, function (configuration) {
  91335. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  91336. if (_this.configuration.observers) {
  91337. _this.configureObservers(_this.configuration.observers);
  91338. }
  91339. var templateConfiguration = _this.configuration.templates || {};
  91340. _this.templateManager.initTemplate(templateConfiguration);
  91341. _this.templateManager.onAllLoaded.add(function () {
  91342. var canvas = _this.templateManager.getCanvas();
  91343. if (canvas) {
  91344. _this.canvas = canvas;
  91345. }
  91346. _this._onTemplateLoaded();
  91347. });
  91348. });
  91349. }
  91350. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  91351. get: function () {
  91352. return this._hdrSupport;
  91353. },
  91354. enumerable: true,
  91355. configurable: true
  91356. });
  91357. AbstractViewer.prototype.getBaseId = function () {
  91358. return this.baseId;
  91359. };
  91360. AbstractViewer.prototype.isCanvasInDOM = function () {
  91361. return !!this.canvas && !!this.canvas.parentElement;
  91362. };
  91363. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  91364. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  91365. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  91366. if (newConfiguration.scene) {
  91367. this.configureScene(newConfiguration.scene);
  91368. }
  91369. if (newConfiguration.optimizer) {
  91370. this.configureOptimizer(newConfiguration.optimizer);
  91371. }
  91372. if (newConfiguration.observers) {
  91373. this.configureObservers(newConfiguration.observers);
  91374. }
  91375. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  91376. this.configureModel(newConfiguration.model);
  91377. }
  91378. if (newConfiguration.lights) {
  91379. this.configureLights(newConfiguration.lights);
  91380. }
  91381. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  91382. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  91383. }
  91384. if (newConfiguration.camera) {
  91385. this.configureCamera(newConfiguration.camera);
  91386. }
  91387. };
  91388. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  91389. if (!skyboxConifguration && !groundConfiguration) {
  91390. if (this.environmentHelper) {
  91391. this.environmentHelper.dispose();
  91392. delete this.environmentHelper;
  91393. }
  91394. ;
  91395. return Promise.resolve(this.scene);
  91396. }
  91397. var options = {
  91398. createGround: !!groundConfiguration,
  91399. createSkybox: !!skyboxConifguration,
  91400. setupImageProcessing: false
  91401. };
  91402. if (groundConfiguration) {
  91403. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  91404. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  91405. if (groundSize) {
  91406. options.groundSize = groundSize;
  91407. }
  91408. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  91409. if (groundConfig.shadowLevel !== undefined) {
  91410. options.groundShadowLevel = groundConfig.shadowLevel;
  91411. }
  91412. options.enableGroundMirror = !!groundConfig.mirror;
  91413. if (groundConfig.texture) {
  91414. options.groundTexture = groundConfig.texture;
  91415. }
  91416. if (groundConfig.color) {
  91417. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  91418. }
  91419. if (groundConfig.opacity !== undefined) {
  91420. options.groundOpacity = groundConfig.opacity;
  91421. }
  91422. if (groundConfig.mirror) {
  91423. options.enableGroundMirror = true;
  91424. if (typeof groundConfig.mirror === "object") {
  91425. if (groundConfig.mirror.amount !== undefined)
  91426. options.groundMirrorAmount = groundConfig.mirror.amount;
  91427. if (groundConfig.mirror.sizeRatio !== undefined)
  91428. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  91429. if (groundConfig.mirror.blurKernel !== undefined)
  91430. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  91431. if (groundConfig.mirror.fresnelWeight !== undefined)
  91432. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  91433. if (groundConfig.mirror.fallOffDistance !== undefined)
  91434. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  91435. if (this.defaultPipelineTextureType !== undefined)
  91436. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  91437. }
  91438. }
  91439. }
  91440. var postInitSkyboxMaterial = false;
  91441. if (skyboxConifguration) {
  91442. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  91443. if (conf.material && conf.material.imageProcessingConfiguration) {
  91444. options.setupImageProcessing = false;
  91445. }
  91446. var skyboxSize = conf.scale;
  91447. if (skyboxSize) {
  91448. options.skyboxSize = skyboxSize;
  91449. }
  91450. options.sizeAuto = !options.skyboxSize;
  91451. if (conf.color) {
  91452. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  91453. }
  91454. if (conf.cubeTexture && conf.cubeTexture.url) {
  91455. if (typeof conf.cubeTexture.url === "string") {
  91456. options.skyboxTexture = conf.cubeTexture.url;
  91457. }
  91458. else {
  91459. postInitSkyboxMaterial = true;
  91460. }
  91461. }
  91462. if (conf.material && conf.material.imageProcessingConfiguration) {
  91463. postInitSkyboxMaterial = true;
  91464. }
  91465. }
  91466. options.setupImageProcessing = false;
  91467. if (!this.environmentHelper) {
  91468. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  91469. }
  91470. else {
  91471. var scene = this.environmentHelper.rootMesh.getScene();
  91472. if (scene !== this.scene) {
  91473. this.environmentHelper.dispose();
  91474. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  91475. }
  91476. else {
  91477. this.environmentHelper.updateOptions(options);
  91478. }
  91479. }
  91480. if (postInitSkyboxMaterial) {
  91481. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  91482. if (skyboxMaterial) {
  91483. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  91484. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  91485. }
  91486. }
  91487. }
  91488. };
  91489. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  91490. if (!this.scene) {
  91491. return;
  91492. }
  91493. if (sceneConfig.debug) {
  91494. this.scene.debugLayer.show();
  91495. }
  91496. else {
  91497. if (this.scene.debugLayer.isVisible()) {
  91498. this.scene.debugLayer.hide();
  91499. }
  91500. }
  91501. if (sceneConfig.clearColor) {
  91502. var cc = sceneConfig.clearColor;
  91503. var oldcc = this.scene.clearColor;
  91504. if (cc.r !== undefined) {
  91505. oldcc.r = cc.r;
  91506. }
  91507. if (cc.g !== undefined) {
  91508. oldcc.g = cc.g;
  91509. }
  91510. if (cc.b !== undefined) {
  91511. oldcc.b = cc.b;
  91512. }
  91513. if (cc.a !== undefined) {
  91514. oldcc.a = cc.a;
  91515. }
  91516. }
  91517. if (sceneConfig.imageProcessingConfiguration) {
  91518. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  91519. }
  91520. if (sceneConfig.environmentTexture) {
  91521. if (this.scene.environmentTexture) {
  91522. this.scene.environmentTexture.dispose();
  91523. }
  91524. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  91525. this.scene.environmentTexture = environmentTexture;
  91526. }
  91527. if (sceneConfig.autoRotate) {
  91528. this.camera.useAutoRotationBehavior = true;
  91529. }
  91530. };
  91531. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  91532. if (typeof optimizerConfig === 'boolean') {
  91533. if (this.sceneOptimizer) {
  91534. this.sceneOptimizer.stop();
  91535. this.sceneOptimizer.dispose();
  91536. delete this.sceneOptimizer;
  91537. }
  91538. if (optimizerConfig) {
  91539. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  91540. this.sceneOptimizer.start();
  91541. }
  91542. }
  91543. else {
  91544. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  91545. if (optimizerConfig.degradation) {
  91546. switch (optimizerConfig.degradation) {
  91547. case "low":
  91548. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  91549. break;
  91550. case "moderate":
  91551. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  91552. break;
  91553. case "hight":
  91554. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  91555. break;
  91556. }
  91557. }
  91558. if (this.sceneOptimizer) {
  91559. this.sceneOptimizer.stop();
  91560. this.sceneOptimizer.dispose();
  91561. }
  91562. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  91563. this.sceneOptimizer.start();
  91564. }
  91565. };
  91566. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  91567. if (observersConfiguration.onEngineInit) {
  91568. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  91569. }
  91570. else {
  91571. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  91572. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  91573. }
  91574. }
  91575. if (observersConfiguration.onSceneInit) {
  91576. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  91577. }
  91578. else {
  91579. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  91580. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  91581. }
  91582. }
  91583. if (observersConfiguration.onModelLoaded) {
  91584. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  91585. }
  91586. else {
  91587. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  91588. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  91589. }
  91590. }
  91591. };
  91592. AbstractViewer.prototype.configureCamera = function (cameraConfig, focusMeshes) {
  91593. var _this = this;
  91594. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91595. if (!this.scene.activeCamera) {
  91596. this.scene.createDefaultCamera(true, true, true);
  91597. this.camera = this.scene.activeCamera;
  91598. }
  91599. if (cameraConfig.position) {
  91600. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  91601. }
  91602. if (cameraConfig.rotation) {
  91603. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  91604. }
  91605. this.extendClassWithConfig(this.camera, cameraConfig);
  91606. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  91607. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  91608. if (cameraConfig.behaviors) {
  91609. for (var name_1 in cameraConfig.behaviors) {
  91610. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  91611. }
  91612. }
  91613. ;
  91614. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  91615. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  91616. });
  91617. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  91618. var sceneDiagonalLenght = sceneDiagonal.length();
  91619. if (isFinite(sceneDiagonalLenght))
  91620. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  91621. };
  91622. AbstractViewer.prototype.configureLights = function (lightsConfiguration, focusMeshes) {
  91623. var _this = this;
  91624. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  91625. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91626. if (!Object.keys(lightsConfiguration).length)
  91627. return;
  91628. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  91629. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  91630. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  91631. lightsAvailable.forEach(function (lName) {
  91632. if (lightsToConfigure.indexOf(lName) === -1) {
  91633. _this.scene.getLightByName(lName).dispose();
  91634. }
  91635. });
  91636. }
  91637. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  91638. var lightConfig = { type: 0 };
  91639. if (typeof lightsConfiguration[name] === 'object') {
  91640. lightConfig = lightsConfiguration[name];
  91641. }
  91642. lightConfig.name = name;
  91643. var light;
  91644. if (lightsAvailable.indexOf(name) === -1) {
  91645. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  91646. if (!constructor)
  91647. return;
  91648. light = constructor();
  91649. }
  91650. else {
  91651. light = _this.scene.getLightByName(name);
  91652. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  91653. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  91654. light.dispose();
  91655. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  91656. if (!constructor)
  91657. return;
  91658. light = constructor();
  91659. }
  91660. }
  91661. if (lightsConfiguration[name] === false) {
  91662. light.dispose();
  91663. return;
  91664. }
  91665. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  91666. light.setEnabled(enabled);
  91667. _this.extendClassWithConfig(light, lightConfig);
  91668. if (light instanceof babylonjs_1.ShadowLight) {
  91669. if (lightConfig.target) {
  91670. if (light.setDirectionToTarget) {
  91671. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  91672. light.setDirectionToTarget(target);
  91673. }
  91674. }
  91675. else if (lightConfig.direction) {
  91676. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  91677. light.direction = direction;
  91678. }
  91679. var shadowGenerator = light.getShadowGenerator();
  91680. if (lightConfig.shadowEnabled && _this.maxShadows) {
  91681. if (!shadowGenerator) {
  91682. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  91683. }
  91684. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  91685. var shadownMap = shadowGenerator.getShadowMap();
  91686. if (!shadownMap)
  91687. return;
  91688. var renderList = shadownMap.renderList;
  91689. for (var index = 0; index < focusMeshes.length; index++) {
  91690. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  91691. renderList && renderList.push(focusMeshes[index]);
  91692. }
  91693. }
  91694. }
  91695. else if (shadowGenerator) {
  91696. shadowGenerator.dispose();
  91697. }
  91698. }
  91699. });
  91700. };
  91701. AbstractViewer.prototype.configureModel = function (modelConfiguration, focusMeshes) {
  91702. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91703. var meshesWithNoParent = focusMeshes.filter(function (m) { return !m.parent; });
  91704. var updateMeshesWithNoParent = function (variable, value, param) {
  91705. meshesWithNoParent.forEach(function (mesh) {
  91706. if (param) {
  91707. mesh[variable][param] = value;
  91708. }
  91709. else {
  91710. mesh[variable] = value;
  91711. }
  91712. });
  91713. };
  91714. var updateXYZ = function (variable, configValues) {
  91715. if (configValues.x !== undefined) {
  91716. updateMeshesWithNoParent(variable, configValues.x, 'x');
  91717. }
  91718. if (configValues.y !== undefined) {
  91719. updateMeshesWithNoParent(variable, configValues.y, 'y');
  91720. }
  91721. if (configValues.z !== undefined) {
  91722. updateMeshesWithNoParent(variable, configValues.z, 'z');
  91723. }
  91724. if (configValues.w !== undefined) {
  91725. updateMeshesWithNoParent(variable, configValues.w, 'w');
  91726. }
  91727. };
  91728. if (modelConfiguration.position) {
  91729. updateXYZ('position', modelConfiguration.position);
  91730. }
  91731. if (modelConfiguration.rotation) {
  91732. if (modelConfiguration.rotation.w) {
  91733. meshesWithNoParent.forEach(function (mesh) {
  91734. if (!mesh.rotationQuaternion) {
  91735. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  91736. }
  91737. });
  91738. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  91739. }
  91740. else {
  91741. updateXYZ('rotation', modelConfiguration.rotation);
  91742. }
  91743. }
  91744. if (modelConfiguration.scaling) {
  91745. updateXYZ('scaling', modelConfiguration.scaling);
  91746. }
  91747. if (modelConfiguration.castShadow) {
  91748. focusMeshes.forEach(function (mesh) {
  91749. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  91750. });
  91751. }
  91752. if (modelConfiguration.normalize) {
  91753. var center = false;
  91754. var unitSize = false;
  91755. var parentIndex = void 0;
  91756. if (modelConfiguration.normalize === true) {
  91757. center = true;
  91758. unitSize = true;
  91759. parentIndex = 0;
  91760. }
  91761. else {
  91762. center = !!modelConfiguration.normalize.center;
  91763. unitSize = !!modelConfiguration.normalize.unitSize;
  91764. parentIndex = modelConfiguration.normalize.parentIndex;
  91765. }
  91766. var meshesToNormalize = [];
  91767. if (parentIndex !== undefined) {
  91768. meshesToNormalize.push(focusMeshes[parentIndex]);
  91769. }
  91770. else {
  91771. meshesToNormalize = meshesWithNoParent;
  91772. }
  91773. if (unitSize) {
  91774. meshesToNormalize.forEach(function (mesh) {
  91775. mesh.normalizeToUnitCube(true);
  91776. mesh.computeWorldMatrix(true);
  91777. });
  91778. }
  91779. if (center) {
  91780. meshesToNormalize.forEach(function (mesh) {
  91781. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  91782. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  91783. var halfSizeVec = sizeVec.scale(0.5);
  91784. var center = boundingInfo.min.add(halfSizeVec);
  91785. mesh.position = center.scale(-1);
  91786. mesh.position.y += halfSizeVec.y;
  91787. mesh.computeWorldMatrix(true);
  91788. });
  91789. }
  91790. }
  91791. };
  91792. AbstractViewer.prototype.dispose = function () {
  91793. window.removeEventListener('resize', this.resize);
  91794. if (this.sceneOptimizer) {
  91795. this.sceneOptimizer.stop();
  91796. this.sceneOptimizer.dispose();
  91797. }
  91798. if (this.scene.activeCamera) {
  91799. this.scene.activeCamera.detachControl(this.canvas);
  91800. }
  91801. this.scene.dispose();
  91802. this.engine.dispose();
  91803. this.templateManager.dispose();
  91804. };
  91805. AbstractViewer.prototype.onTemplatesLoaded = function () {
  91806. return Promise.resolve(this);
  91807. };
  91808. AbstractViewer.prototype._onTemplateLoaded = function () {
  91809. var _this = this;
  91810. return this.onTemplatesLoaded().then(function () {
  91811. var autoLoadModel = !!_this.configuration.model;
  91812. return _this.initEngine().then(function (engine) {
  91813. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  91814. }).then(function () {
  91815. if (autoLoadModel) {
  91816. return _this.loadModel();
  91817. }
  91818. else {
  91819. return _this.scene || _this.initScene();
  91820. }
  91821. }).then(function (scene) {
  91822. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  91823. }).then(function () {
  91824. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  91825. }).then(function () {
  91826. return _this;
  91827. });
  91828. });
  91829. };
  91830. AbstractViewer.prototype.initEngine = function () {
  91831. this.injectCustomShaders();
  91832. var canvasElement = this.templateManager.getCanvas();
  91833. if (!canvasElement) {
  91834. return Promise.reject('Canvas element not found!');
  91835. }
  91836. var config = this.configuration.engine || {};
  91837. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  91838. babylonjs_1.Database.IDBStorageEnabled = false;
  91839. if (!config.disableResize) {
  91840. window.addEventListener('resize', this.resize);
  91841. }
  91842. this.engine.runRenderLoop(this.render);
  91843. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  91844. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  91845. this.engine.setHardwareScalingLevel(scale);
  91846. }
  91847. this.handleHardwareLimitations();
  91848. return Promise.resolve(this.engine);
  91849. };
  91850. AbstractViewer.prototype.initScene = function () {
  91851. if (this.scene) {
  91852. this.scene.dispose();
  91853. }
  91854. this.scene = new babylonjs_1.Scene(this.engine);
  91855. this.scene.createDefaultLight(true);
  91856. if (this.configuration.scene) {
  91857. this.configureScene(this.configuration.scene);
  91858. if (this.configuration.optimizer) {
  91859. this.configureOptimizer(this.configuration.optimizer);
  91860. }
  91861. }
  91862. return Promise.resolve(this.scene);
  91863. };
  91864. AbstractViewer.prototype.loadModel = function (model, clearScene) {
  91865. var _this = this;
  91866. if (model === void 0) { model = this.configuration.model; }
  91867. if (clearScene === void 0) { clearScene = true; }
  91868. var modelUrl = (typeof model === 'string') ? model : model.url;
  91869. if (!modelUrl) {
  91870. return Promise.resolve(this.scene);
  91871. }
  91872. if (this.isLoading) {
  91873. this.nextLoading = function () {
  91874. delete _this.nextLoading;
  91875. _this.loadModel(model, clearScene);
  91876. };
  91877. return Promise.resolve(this.scene);
  91878. }
  91879. this.isLoading = true;
  91880. if ((typeof model === 'string')) {
  91881. if (this.configuration.model && typeof this.configuration.model === 'object') {
  91882. this.configuration.model.url = model;
  91883. }
  91884. }
  91885. else {
  91886. if (this.configuration.model) {
  91887. deepmerge(this.configuration.model, model);
  91888. }
  91889. else {
  91890. this.configuration.model = model;
  91891. }
  91892. }
  91893. var parts = modelUrl.split('/');
  91894. var filename = parts.pop();
  91895. var base = parts.join('/') + '/';
  91896. var plugin = (typeof model === 'string') ? undefined : model.loader;
  91897. return Promise.resolve(this.scene).then(function (scene) {
  91898. if (!scene)
  91899. return _this.initScene();
  91900. if (clearScene) {
  91901. scene.meshes.forEach(function (mesh) {
  91902. if (babylonjs_1.Tags.MatchesQuery(mesh, "viewerMesh")) {
  91903. mesh.dispose();
  91904. }
  91905. });
  91906. }
  91907. return scene;
  91908. }).then(function () {
  91909. return new Promise(function (resolve, reject) {
  91910. _this.lastUsedLoader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, _this.scene, function (meshes) {
  91911. meshes.forEach(function (mesh) {
  91912. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  91913. });
  91914. resolve(meshes);
  91915. }, function (progressEvent) {
  91916. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  91917. }, function (e, m, exception) {
  91918. _this.onModelLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception }).then(function () {
  91919. reject(exception);
  91920. });
  91921. }, plugin);
  91922. _this.onLoaderInitObservable.notifyObserversWithPromise(_this.lastUsedLoader);
  91923. });
  91924. }).then(function (meshes) {
  91925. return _this.onModelLoadedObservable.notifyObserversWithPromise(meshes)
  91926. .then(function () {
  91927. _this.configureModel(_this.configuration.model || model, meshes);
  91928. _this.configureLights(_this.configuration.lights);
  91929. if (_this.configuration.camera) {
  91930. _this.configureCamera(_this.configuration.camera, meshes);
  91931. }
  91932. return _this.initEnvironment(meshes);
  91933. }).then(function () {
  91934. _this.isLoading = false;
  91935. if (_this.nextLoading) {
  91936. return _this.nextLoading();
  91937. }
  91938. return _this.scene;
  91939. });
  91940. });
  91941. };
  91942. AbstractViewer.prototype.initEnvironment = function (focusMeshes) {
  91943. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  91944. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  91945. return Promise.resolve(this.scene);
  91946. };
  91947. AbstractViewer.prototype.handleHardwareLimitations = function () {
  91948. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  91949. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  91950. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  91951. this.maxShadows = 0;
  91952. }
  91953. else {
  91954. this.maxShadows = 3;
  91955. }
  91956. var caps = this.engine.getCaps();
  91957. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  91958. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  91959. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  91960. if (linearHalfFloatTargets) {
  91961. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  91962. this.shadowGeneratorBias = 0.002;
  91963. }
  91964. else if (linearFloatTargets) {
  91965. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  91966. this.shadowGeneratorBias = 0.001;
  91967. }
  91968. else {
  91969. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  91970. this.shadowGeneratorBias = 0.001;
  91971. }
  91972. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  91973. };
  91974. AbstractViewer.prototype.injectCustomShaders = function () {
  91975. var customShaders = this.configuration.customShaders;
  91976. if (!customShaders) {
  91977. return;
  91978. }
  91979. if (customShaders.shaders) {
  91980. Object.keys(customShaders.shaders).forEach(function (key) {
  91981. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  91982. });
  91983. }
  91984. if (customShaders.includes) {
  91985. Object.keys(customShaders.includes).forEach(function (key) {
  91986. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  91987. });
  91988. }
  91989. };
  91990. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  91991. var _this = this;
  91992. if (!config)
  91993. return;
  91994. Object.keys(config).forEach(function (key) {
  91995. if (key in object && typeof object[key] !== 'function') {
  91996. if (typeof object[key] === 'object') {
  91997. _this.extendClassWithConfig(object[key], config[key]);
  91998. }
  91999. else {
  92000. if (config[key] !== undefined) {
  92001. object[key] = config[key];
  92002. }
  92003. }
  92004. }
  92005. });
  92006. };
  92007. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  92008. var behavior;
  92009. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  92010. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  92011. switch (type) {
  92012. case 0:
  92013. this.camera.useAutoRotationBehavior = true;
  92014. behavior = this.camera.autoRotationBehavior;
  92015. break;
  92016. case 1:
  92017. this.camera.useBouncingBehavior = true;
  92018. behavior = this.camera.bouncingBehavior;
  92019. break;
  92020. case 2:
  92021. this.camera.useFramingBehavior = true;
  92022. behavior = this.camera.framingBehavior;
  92023. break;
  92024. default:
  92025. behavior = null;
  92026. break;
  92027. }
  92028. if (behavior) {
  92029. if (typeof behaviorConfig === "object") {
  92030. this.extendClassWithConfig(behavior, behaviorConfig);
  92031. }
  92032. }
  92033. switch (type) {
  92034. case 0:
  92035. break;
  92036. case 1:
  92037. break;
  92038. case 2:
  92039. if (config.zoomOnBoundingInfo) {
  92040. var meshes = payload;
  92041. var bounding = meshes[0].getHierarchyBoundingVectors();
  92042. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  92043. }
  92044. break;
  92045. }
  92046. };
  92047. return AbstractViewer;
  92048. }());
  92049. exports.AbstractViewer = AbstractViewer;
  92050. /***/ }),
  92051. /* 6 */
  92052. /***/ (function(module, exports) {
  92053. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  92054. /***/ }),
  92055. /* 7 */
  92056. /***/ (function(module, exports) {
  92057. 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}}>";
  92058. /***/ }),
  92059. /* 8 */
  92060. /***/ (function(module, exports) {
  92061. 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=="
  92062. /***/ }),
  92063. /* 9 */
  92064. /***/ (function(module, exports) {
  92065. 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>";
  92066. /***/ }),
  92067. /* 10 */
  92068. /***/ (function(module, exports) {
  92069. 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>";
  92070. /***/ }),
  92071. /* 11 */
  92072. /***/ (function(module, exports) {
  92073. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  92074. /***/ }),
  92075. /* 12 */
  92076. /***/ (function(module, exports) {
  92077. module.exports = "Error loading the model";
  92078. /***/ }),
  92079. /* 13 */
  92080. /***/ (function(module, exports, __webpack_require__) {
  92081. (function (global, factory) {
  92082. true ? module.exports = factory() :
  92083. typeof define === 'function' && define.amd ? define(factory) :
  92084. (global.deepmerge = factory());
  92085. }(this, (function () { 'use strict';
  92086. var isMergeableObject = function isMergeableObject(value) {
  92087. return isNonNullObject(value)
  92088. && !isSpecial(value)
  92089. };
  92090. function isNonNullObject(value) {
  92091. return !!value && typeof value === 'object'
  92092. }
  92093. function isSpecial(value) {
  92094. var stringValue = Object.prototype.toString.call(value);
  92095. return stringValue === '[object RegExp]'
  92096. || stringValue === '[object Date]'
  92097. || isReactElement(value)
  92098. }
  92099. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  92100. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  92101. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  92102. function isReactElement(value) {
  92103. return value.$$typeof === REACT_ELEMENT_TYPE
  92104. }
  92105. function emptyTarget(val) {
  92106. return Array.isArray(val) ? [] : {}
  92107. }
  92108. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  92109. var clone = !optionsArgument || optionsArgument.clone !== false;
  92110. return (clone && isMergeableObject(value))
  92111. ? deepmerge(emptyTarget(value), value, optionsArgument)
  92112. : value
  92113. }
  92114. function defaultArrayMerge(target, source, optionsArgument) {
  92115. return target.concat(source).map(function(element) {
  92116. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  92117. })
  92118. }
  92119. function mergeObject(target, source, optionsArgument) {
  92120. var destination = {};
  92121. if (isMergeableObject(target)) {
  92122. Object.keys(target).forEach(function(key) {
  92123. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  92124. });
  92125. }
  92126. Object.keys(source).forEach(function(key) {
  92127. if (!isMergeableObject(source[key]) || !target[key]) {
  92128. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  92129. } else {
  92130. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  92131. }
  92132. });
  92133. return destination
  92134. }
  92135. function deepmerge(target, source, optionsArgument) {
  92136. var sourceIsArray = Array.isArray(source);
  92137. var targetIsArray = Array.isArray(target);
  92138. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  92139. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  92140. if (!sourceAndTargetTypesMatch) {
  92141. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  92142. } else if (sourceIsArray) {
  92143. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  92144. return arrayMerge(target, source, optionsArgument)
  92145. } else {
  92146. return mergeObject(target, source, optionsArgument)
  92147. }
  92148. }
  92149. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  92150. if (!Array.isArray(array)) {
  92151. throw new Error('first argument should be an array')
  92152. }
  92153. return array.reduce(function(prev, next) {
  92154. return deepmerge(prev, next, optionsArgument)
  92155. }, {})
  92156. };
  92157. var deepmerge_1 = deepmerge;
  92158. return deepmerge_1;
  92159. })));
  92160. /***/ }),
  92161. /* 14 */
  92162. /***/ (function(module, exports, __webpack_require__) {
  92163. module.exports = __webpack_require__(15);
  92164. /***/ }),
  92165. /* 15 */
  92166. /***/ (function(module, exports, __webpack_require__) {
  92167. "use strict";
  92168. Object.defineProperty(exports, "__esModule", { value: true });
  92169. var mappers_1 = __webpack_require__(1);
  92170. exports.mapperManager = mappers_1.mapperManager;
  92171. var viewerManager_1 = __webpack_require__(3);
  92172. exports.viewerManager = viewerManager_1.viewerManager;
  92173. var defaultViewer_1 = __webpack_require__(4);
  92174. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  92175. var viewer_1 = __webpack_require__(5);
  92176. exports.AbstractViewer = viewer_1.AbstractViewer;
  92177. __webpack_require__(0);
  92178. __webpack_require__(30);
  92179. __webpack_require__(31);
  92180. var babylonjs_1 = __webpack_require__(0);
  92181. var initializer_1 = __webpack_require__(32);
  92182. exports.InitTags = initializer_1.InitTags;
  92183. babylonjs_1.PromisePolyfill.Apply();
  92184. exports.disableInit = false;
  92185. document.addEventListener("DOMContentLoaded", function (event) {
  92186. if (exports.disableInit)
  92187. return;
  92188. initializer_1.InitTags();
  92189. });
  92190. /***/ }),
  92191. /* 16 */
  92192. /***/ (function(module, exports) {
  92193. var g;
  92194. // This works in non-strict mode
  92195. g = (function() {
  92196. return this;
  92197. })();
  92198. try {
  92199. // This works if eval is allowed (see CSP)
  92200. g = g || Function("return this")() || (1,eval)("this");
  92201. } catch(e) {
  92202. // This works if the window reference is available
  92203. if(typeof window === "object")
  92204. g = window;
  92205. }
  92206. // g can still be undefined, but nothing to do about it...
  92207. // We return undefined, instead of nothing here, so it's
  92208. // easier to handle this case. if(!global) { ...}
  92209. module.exports = g;
  92210. /***/ }),
  92211. /* 17 */
  92212. /***/ (function(module, exports) {
  92213. module.exports = cannon;
  92214. /***/ }),
  92215. /* 18 */
  92216. /***/ (function(module, exports, __webpack_require__) {
  92217. /**
  92218. * from OimoPhysics DEV 1.1.0a AS3
  92219. * @author Saharan / http://el-ement.com/
  92220. *
  92221. * to Oimo.js 2015 JAVASCRIPT
  92222. * @author LoTh / http://lo-th.github.io/labs/
  92223. */
  92224. var OIMO = {
  92225. REVISION: "1.2",
  92226. // Global identification of next shape.
  92227. // This will be incremented every time a shape is created.
  92228. nextID: 0,
  92229. proxyID: 0,
  92230. // BroadPhase
  92231. BR_NULL: 0,
  92232. BR_BRUTE_FORCE: 1,
  92233. BR_SWEEP_AND_PRUNE: 2,
  92234. BR_BOUNDING_VOLUME_TREE: 3,
  92235. // body type
  92236. BODY_NULL: 0,
  92237. BODY_DYNAMIC: 1,
  92238. BODY_STATIC: 2,
  92239. // shape type
  92240. SHAPE_NULL: 0,
  92241. SHAPE_SPHERE: 1,
  92242. SHAPE_BOX: 2,
  92243. SHAPE_CYLINDER: 3,
  92244. SHAPE_TETRA: 4,
  92245. // joint type
  92246. JOINT_NULL: 0,
  92247. JOINT_DISTANCE: 1,
  92248. JOINT_BALL_AND_SOCKET: 2,
  92249. JOINT_HINGE: 3,
  92250. JOINT_WHEEL: 4,
  92251. JOINT_SLIDER: 5,
  92252. JOINT_PRISMATIC: 6,
  92253. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  92254. // scale all by 100 so object is between 10 to 10000 three unit.
  92255. WORLD_SCALE: 100,
  92256. INV_SCALE: 0.01,
  92257. // AABB aproximation
  92258. AABB_PROX: 0.005,
  92259. // Math function
  92260. sqrt: Math.sqrt,
  92261. abs: Math.abs,
  92262. floor: Math.floor,
  92263. cos: Math.cos,
  92264. sin: Math.sin,
  92265. acos: Math.acos,
  92266. asin: Math.asin,
  92267. atan2: Math.atan2,
  92268. round: Math.round,
  92269. pow: Math.pow,
  92270. max: Math.max,
  92271. min: Math.min,
  92272. random: Math.random,
  92273. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  92274. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  92275. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  92276. int: function (x) { return ~~x; },
  92277. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  92278. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  92279. degtorad: 0.0174532925199432957,
  92280. radtodeg: 57.295779513082320876,
  92281. PI: 3.141592653589793,
  92282. TwoPI: 6.283185307179586,
  92283. PI90: 1.570796326794896,
  92284. PI270: 4.712388980384689,
  92285. CustomError: null,
  92286. Error: function (Class, Msg) {
  92287. if (OIMO.CustomError == null) console.error(Class, Msg);
  92288. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  92289. }
  92290. };
  92291. var OIMO_ARRAY_TYPE;
  92292. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  92293. try {
  92294. (function (w) {
  92295. var perfNow;
  92296. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  92297. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  92298. var n = perfNowNames[i];
  92299. if (!!w['performance'][n]) {
  92300. perfNow = function () { return w['performance'][n]() };
  92301. break;
  92302. }
  92303. }
  92304. if (!perfNow) perfNow = Date.now;
  92305. //w.perfNow = perfNow;
  92306. OIMO.now = perfNow;
  92307. })(window);
  92308. } catch (e) { OIMO.now = function () { return 0; }; }
  92309. /**
  92310. * The class of physical computing world.
  92311. * You must be added to the world physical all computing objects
  92312. * @author saharan
  92313. * @author lo-th
  92314. */
  92315. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  92316. // The time between each step
  92317. this.timeStep = TimeStep || 0.01666; // 1/60;
  92318. // The number of iterations for constraint solvers.
  92319. this.numIterations = Iterations || 8;
  92320. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  92321. switch (BroadPhaseType || 2) {
  92322. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  92323. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  92324. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  92325. }
  92326. // This is the detailed information of the performance.
  92327. this.performance = null;
  92328. this.isNoStat = NoStat || false;
  92329. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  92330. // Whether the constraints randomizer is enabled or not.
  92331. this.enableRandomizer = true;
  92332. // The rigid body list
  92333. this.rigidBodies = null;
  92334. // number of rigid body
  92335. this.numRigidBodies = 0;
  92336. // The contact list
  92337. this.contacts = null;
  92338. this.unusedContacts = null;
  92339. // The number of contact
  92340. this.numContacts = 0;
  92341. // The number of contact points
  92342. this.numContactPoints = 0;
  92343. // The joint list
  92344. this.joints = null;
  92345. // The number of joints.
  92346. this.numJoints = 0;
  92347. // The number of simulation islands.
  92348. this.numIslands = 0;
  92349. // The gravity in the world.
  92350. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  92351. var numShapeTypes = 5;//4;//3;
  92352. this.detectors = [];
  92353. this.detectors.length = numShapeTypes;
  92354. var i = numShapeTypes;
  92355. while (i--) {
  92356. this.detectors[i] = [];
  92357. this.detectors[i].length = numShapeTypes;
  92358. }
  92359. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  92360. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  92361. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  92362. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  92363. // CYLINDER add
  92364. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  92365. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  92366. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  92367. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  92368. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  92369. // TETRA add
  92370. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  92371. this.randX = 65535;
  92372. this.randA = 98765;
  92373. this.randB = 123456789;
  92374. //this.maxIslandRigidBodies = 64;
  92375. this.islandRigidBodies = [];
  92376. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  92377. this.islandStack = [];
  92378. //this.islandStack.length = this.maxIslandRigidBodies;
  92379. //this.maxIslandConstraints = 128;
  92380. this.islandConstraints = [];
  92381. //this.islandConstraints.length = this.maxIslandConstraints;
  92382. };
  92383. OIMO.World.prototype = {
  92384. constructor: OIMO.World,
  92385. /**
  92386. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  92387. */
  92388. clear: function () {
  92389. this.randX = 65535;
  92390. while (this.joints !== null) {
  92391. this.removeJoint(this.joints);
  92392. }
  92393. while (this.contacts !== null) {
  92394. this.removeContact(this.contacts);
  92395. }
  92396. while (this.rigidBodies !== null) {
  92397. this.removeRigidBody(this.rigidBodies);
  92398. }
  92399. OIMO.nextID = 0;
  92400. OIMO.proxyID = 0;
  92401. },
  92402. /**
  92403. * I'll add a rigid body to the world.
  92404. * Rigid body that has been added will be the operands of each step.
  92405. * @param rigidBody Rigid body that you want to add
  92406. */
  92407. addRigidBody: function (rigidBody) {
  92408. if (rigidBody.parent) {
  92409. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  92410. }
  92411. rigidBody.parent = this;
  92412. rigidBody.awake();
  92413. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  92414. this.addShape(shape);
  92415. }
  92416. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  92417. this.rigidBodies = rigidBody;
  92418. this.numRigidBodies++;
  92419. },
  92420. /**
  92421. * I will remove the rigid body from the world.
  92422. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  92423. * @param rigidBody Rigid body to be removed
  92424. */
  92425. removeRigidBody: function (rigidBody) {
  92426. var remove = rigidBody;
  92427. if (remove.parent !== this) return;
  92428. remove.awake();
  92429. var js = remove.jointLink;
  92430. while (js != null) {
  92431. var joint = js.joint;
  92432. js = js.next;
  92433. this.removeJoint(joint);
  92434. }
  92435. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  92436. this.removeShape(shape);
  92437. }
  92438. var prev = remove.prev;
  92439. var next = remove.next;
  92440. if (prev !== null) prev.next = next;
  92441. if (next !== null) next.prev = prev;
  92442. if (this.rigidBodies == remove) this.rigidBodies = next;
  92443. remove.prev = null;
  92444. remove.next = null;
  92445. remove.parent = null;
  92446. this.numRigidBodies--;
  92447. },
  92448. getByName: function (name) {
  92449. var result = null;
  92450. var body = this.rigidBodies;
  92451. while (body !== null) {
  92452. if (body.name !== " " && body.name === name) result = body;
  92453. body = body.next;
  92454. }
  92455. var joint = this.joints;
  92456. while (joint !== null) {
  92457. if (joint.name !== "" && joint.name === name) result = joint;
  92458. joint = joint.next;
  92459. }
  92460. return result;
  92461. },
  92462. /**
  92463. * I'll add a shape to the world..
  92464. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  92465. * Shape will be added to the world automatically, please do not call from outside this method.
  92466. * @param shape Shape you want to add
  92467. */
  92468. addShape: function (shape) {
  92469. if (!shape.parent || !shape.parent.parent) {
  92470. OIMO.Error("World", "It is not possible to be added alone to shape world");
  92471. }
  92472. shape.proxy = this.broadPhase.createProxy(shape);
  92473. shape.updateProxy();
  92474. this.broadPhase.addProxy(shape.proxy);
  92475. },
  92476. /**
  92477. * I will remove the shape from the world.
  92478. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  92479. * Shape will be added to the world automatically, please do not call from outside this method.
  92480. * @param shape Shape you want to delete
  92481. */
  92482. removeShape: function (shape) {
  92483. this.broadPhase.removeProxy(shape.proxy);
  92484. shape.proxy = null;
  92485. },
  92486. /**
  92487. * I'll add a joint to the world.
  92488. * Joint that has been added will be the operands of each step.
  92489. * @param shape Joint to be added
  92490. */
  92491. addJoint: function (joint) {
  92492. if (joint.parent) {
  92493. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  92494. }
  92495. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  92496. this.joints = joint;
  92497. joint.parent = this;
  92498. this.numJoints++;
  92499. joint.awake();
  92500. joint.attach();
  92501. },
  92502. /**
  92503. * I will remove the joint from the world.
  92504. * Joint that has been added will be the operands of each step.
  92505. * @param shape Joint to be deleted
  92506. */
  92507. removeJoint: function (joint) {
  92508. var remove = joint;
  92509. var prev = remove.prev;
  92510. var next = remove.next;
  92511. if (prev !== null) prev.next = next;
  92512. if (next !== null) next.prev = prev;
  92513. if (this.joints == remove) this.joints = next;
  92514. remove.prev = null;
  92515. remove.next = null;
  92516. this.numJoints--;
  92517. remove.awake();
  92518. remove.detach();
  92519. remove.parent = null;
  92520. },
  92521. worldscale: function (scale) {
  92522. OIMO.WORLD_SCALE = scale || 100;
  92523. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  92524. },
  92525. addContact: function (s1, s2) {
  92526. var newContact;
  92527. if (this.unusedContacts !== null) {
  92528. newContact = this.unusedContacts;
  92529. this.unusedContacts = this.unusedContacts.next;
  92530. } else {
  92531. newContact = new OIMO.Contact();
  92532. }
  92533. newContact.attach(s1, s2);
  92534. newContact.detector = this.detectors[s1.type][s2.type];
  92535. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  92536. this.contacts = newContact;
  92537. this.numContacts++;
  92538. },
  92539. removeContact: function (contact) {
  92540. var prev = contact.prev;
  92541. var next = contact.next;
  92542. if (next) next.prev = prev;
  92543. if (prev) prev.next = next;
  92544. if (this.contacts == contact) this.contacts = next;
  92545. contact.prev = null;
  92546. contact.next = null;
  92547. contact.detach();
  92548. contact.next = this.unusedContacts;
  92549. this.unusedContacts = contact;
  92550. this.numContacts--;
  92551. },
  92552. checkContact: function (name1, name2) {
  92553. var n1, n2;
  92554. var contact = this.contacts;
  92555. while (contact !== null) {
  92556. n1 = contact.body1.name || ' ';
  92557. n2 = contact.body2.name || ' ';
  92558. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  92559. else contact = contact.next;
  92560. }
  92561. return false;
  92562. },
  92563. callSleep: function (body) {
  92564. if (!body.allowSleep) return false;
  92565. if (body.linearVelocity.lengthSq() > 0.04) return false;
  92566. if (body.angularVelocity.lengthSq() > 0.25) return false;
  92567. return true;
  92568. },
  92569. /**
  92570. * I will proceed only time step seconds time of World.
  92571. */
  92572. step: function () {
  92573. var time0, time1, time2, time3;
  92574. var stat = !this.isNoStat ? true : false;
  92575. if (stat) time0 = OIMO.now();
  92576. var body = this.rigidBodies;
  92577. while (body !== null) {
  92578. body.addedToIsland = false;
  92579. if (body.sleeping) {
  92580. if (
  92581. body.linearVelocity.testZero() ||
  92582. body.angularVelocity.testZero() ||
  92583. body.position.testDiff(body.sleepPosition) ||
  92584. body.orientation.testDiff(body.sleepOrientation)
  92585. ) body.awake(); // awake the body
  92586. }
  92587. body = body.next;
  92588. }
  92589. //------------------------------------------------------
  92590. // UPDATE CONTACT
  92591. //------------------------------------------------------
  92592. // broad phase
  92593. if (stat) time1 = OIMO.now();
  92594. this.broadPhase.detectPairs();
  92595. var pairs = this.broadPhase.pairs;
  92596. var i = this.broadPhase.numPairs;
  92597. //do{
  92598. while (i--) {
  92599. //for(var i=0, l=numPairs; i<l; i++){
  92600. var pair = pairs[i];
  92601. var s1;
  92602. var s2;
  92603. if (pair.shape1.id < pair.shape2.id) {
  92604. s1 = pair.shape1;
  92605. s2 = pair.shape2;
  92606. } else {
  92607. s1 = pair.shape2;
  92608. s2 = pair.shape1;
  92609. }
  92610. var link;
  92611. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  92612. else link = s2.contactLink;
  92613. var exists = false;
  92614. while (link) {
  92615. var contact = link.contact;
  92616. if (contact.shape1 == s1 && contact.shape2 == s2) {
  92617. contact.persisting = true;
  92618. exists = true;// contact already exists
  92619. break;
  92620. }
  92621. link = link.next;
  92622. }
  92623. if (!exists) {
  92624. this.addContact(s1, s2);
  92625. }
  92626. }// while(i-- >0);
  92627. if (stat) {
  92628. time2 = OIMO.now();
  92629. this.performance.broadPhaseTime = time2 - time1;
  92630. }
  92631. // update & narrow phase
  92632. this.numContactPoints = 0;
  92633. contact = this.contacts;
  92634. while (contact !== null) {
  92635. if (!contact.persisting) {
  92636. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  92637. /*var aabb1=contact.shape1.aabb;
  92638. var aabb2=contact.shape2.aabb;
  92639. if(
  92640. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  92641. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  92642. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  92643. ){*/
  92644. var next = contact.next;
  92645. this.removeContact(contact);
  92646. contact = next;
  92647. continue;
  92648. }
  92649. }
  92650. var b1 = contact.body1;
  92651. var b2 = contact.body2;
  92652. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  92653. contact.updateManifold();
  92654. }
  92655. this.numContactPoints += contact.manifold.numPoints;
  92656. contact.persisting = false;
  92657. contact.constraint.addedToIsland = false;
  92658. contact = contact.next;
  92659. }
  92660. if (stat) {
  92661. time3 = OIMO.now();
  92662. this.performance.narrowPhaseTime = time3 - time2;
  92663. }
  92664. //------------------------------------------------------
  92665. // SOLVE ISLANDS
  92666. //------------------------------------------------------
  92667. var invTimeStep = 1 / this.timeStep;
  92668. //var body;
  92669. var joint;
  92670. var constraint;
  92671. //var num;
  92672. for (joint = this.joints; joint !== null; joint = joint.next) {
  92673. joint.addedToIsland = false;
  92674. }
  92675. // clear old island array
  92676. this.islandRigidBodies = [];
  92677. this.islandConstraints = [];
  92678. this.islandStack = [];
  92679. // expand island buffers
  92680. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  92681. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  92682. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  92683. this.islandRigidBodies=[];
  92684. this.islandStack=[];
  92685. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  92686. this.islandStack.length = this.maxIslandRigidBodies;
  92687. }
  92688. var numConstraints=this.numJoints+this.numContacts;
  92689. if(this.maxIslandConstraints<numConstraints){
  92690. this.maxIslandConstraints=numConstraints<<1;
  92691. //this.maxIslandConstraints=numConstraints*2;
  92692. this.islandConstraints=[];
  92693. this.islandConstraints.length = this.maxIslandConstraints;
  92694. }*/
  92695. time1 = OIMO.now();
  92696. this.numIslands = 0;
  92697. // build and solve simulation islands
  92698. for (var base = this.rigidBodies; base !== null; base = base.next) {
  92699. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  92700. if (base.isLonely()) {// update single body
  92701. if (base.isDynamic) {
  92702. base.linearVelocity.addTime(this.gravity, this.timeStep);
  92703. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  92704. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  92705. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  92706. }
  92707. if (this.callSleep(base)) {
  92708. base.sleepTime += this.timeStep;
  92709. if (base.sleepTime > 0.5) base.sleep();
  92710. else base.updatePosition(this.timeStep);
  92711. } else {
  92712. base.sleepTime = 0;
  92713. base.updatePosition(this.timeStep);
  92714. }
  92715. this.numIslands++;
  92716. continue;
  92717. }
  92718. var islandNumRigidBodies = 0;
  92719. var islandNumConstraints = 0;
  92720. var stackCount = 1;
  92721. // add rigid body to stack
  92722. this.islandStack[0] = base;
  92723. base.addedToIsland = true;
  92724. // build an island
  92725. do {
  92726. // get rigid body from stack
  92727. body = this.islandStack[--stackCount];
  92728. this.islandStack[stackCount] = null;
  92729. body.sleeping = false;
  92730. // add rigid body to the island
  92731. this.islandRigidBodies[islandNumRigidBodies++] = body;
  92732. if (body.isStatic) continue;
  92733. // search connections
  92734. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  92735. var contact = cs.contact;
  92736. constraint = contact.constraint;
  92737. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  92738. // add constraint to the island
  92739. this.islandConstraints[islandNumConstraints++] = constraint;
  92740. constraint.addedToIsland = true;
  92741. var next = cs.body;
  92742. if (next.addedToIsland) continue;
  92743. // add rigid body to stack
  92744. this.islandStack[stackCount++] = next;
  92745. next.addedToIsland = true;
  92746. }
  92747. for (var js = body.jointLink; js !== null; js = js.next) {
  92748. constraint = js.joint;
  92749. if (constraint.addedToIsland) continue;// ignore
  92750. // add constraint to the island
  92751. this.islandConstraints[islandNumConstraints++] = constraint;
  92752. constraint.addedToIsland = true;
  92753. next = js.body;
  92754. if (next.addedToIsland || !next.isDynamic) continue;
  92755. // add rigid body to stack
  92756. this.islandStack[stackCount++] = next;
  92757. next.addedToIsland = true;
  92758. }
  92759. } while (stackCount != 0);
  92760. // update velocities
  92761. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  92762. /*var gx=this.gravity.x*this.timeStep;
  92763. var gy=this.gravity.y*this.timeStep;
  92764. var gz=this.gravity.z*this.timeStep;*/
  92765. var j = islandNumRigidBodies;
  92766. while (j--) {
  92767. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  92768. body = this.islandRigidBodies[j];
  92769. if (body.isDynamic) {
  92770. body.linearVelocity.addEqual(gVel);
  92771. /*body.linearVelocity.x+=gx;
  92772. body.linearVelocity.y+=gy;
  92773. body.linearVelocity.z+=gz;*/
  92774. }
  92775. }
  92776. // randomizing order
  92777. if (this.enableRandomizer) {
  92778. //for(var j=1, l=islandNumConstraints; j<l; j++){
  92779. j = islandNumConstraints;
  92780. while (j--) {
  92781. if (j !== 0) {
  92782. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  92783. constraint = this.islandConstraints[j];
  92784. this.islandConstraints[j] = this.islandConstraints[swap];
  92785. this.islandConstraints[swap] = constraint;
  92786. }
  92787. }
  92788. }
  92789. // solve contraints
  92790. j = islandNumConstraints;
  92791. while (j--) {
  92792. //for(j=0, l=islandNumConstraints; j<l; j++){
  92793. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  92794. }
  92795. var k = this.numIterations;
  92796. while (k--) {
  92797. //for(var k=0, l=this.numIterations; k<l; k++){
  92798. j = islandNumConstraints;
  92799. while (j--) {
  92800. //for(j=0, m=islandNumConstraints; j<m; j++){
  92801. this.islandConstraints[j].solve();// main-solve
  92802. }
  92803. }
  92804. j = islandNumConstraints;
  92805. while (j--) {
  92806. //for(j=0, l=islandNumConstraints; j<l; j++){
  92807. this.islandConstraints[j].postSolve();// post-solve
  92808. this.islandConstraints[j] = null;// gc
  92809. }
  92810. // sleeping check
  92811. var sleepTime = 10;
  92812. j = islandNumRigidBodies;
  92813. while (j--) {
  92814. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  92815. body = this.islandRigidBodies[j];
  92816. if (this.callSleep(body)) {
  92817. body.sleepTime += this.timeStep;
  92818. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  92819. } else {
  92820. body.sleepTime = 0;
  92821. sleepTime = 0;
  92822. continue;
  92823. }
  92824. }
  92825. if (sleepTime > 0.5) {
  92826. // sleep the island
  92827. j = islandNumRigidBodies;
  92828. while (j--) {
  92829. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  92830. this.islandRigidBodies[j].sleep();
  92831. this.islandRigidBodies[j] = null;// gc
  92832. }
  92833. } else {
  92834. // update positions
  92835. j = islandNumRigidBodies;
  92836. while (j--) {
  92837. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  92838. this.islandRigidBodies[j].updatePosition(this.timeStep);
  92839. this.islandRigidBodies[j] = null;// gc
  92840. }
  92841. }
  92842. this.numIslands++;
  92843. }
  92844. if (stat) {
  92845. time2 = OIMO.now();
  92846. this.performance.solvingTime = time2 - time1;
  92847. //------------------------------------------------------
  92848. // END SIMULATION
  92849. //------------------------------------------------------
  92850. time2 = OIMO.now();
  92851. // fps update
  92852. this.performance.upfps();
  92853. this.performance.totalTime = time2 - time0;
  92854. }
  92855. }
  92856. }
  92857. /**
  92858. * The class of rigid body.
  92859. * Rigid body has the shape of a single or multiple collision processing,
  92860. * I can set the parameters individually.
  92861. * @author saharan
  92862. */
  92863. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  92864. this.name = " ";
  92865. // The maximum number of shapes that can be added to a one rigid.
  92866. this.MAX_SHAPES = 64;//64;
  92867. this.prev = null;
  92868. this.next = null;
  92869. // I represent the kind of rigid body.
  92870. // Please do not change from the outside this variable.
  92871. // If you want to change the type of rigid body, always
  92872. // Please specify the type you want to set the arguments of setupMass method.
  92873. this.type = OIMO.BODY_NULL;
  92874. this.massInfo = new OIMO.MassInfo();
  92875. // It is the world coordinate of the center of gravity.
  92876. this.position = new OIMO.Vec3(x, y, z);
  92877. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  92878. this.newPosition = new OIMO.Vec3();
  92879. this.controlPos = false;
  92880. this.newOrientation = new OIMO.Quat();
  92881. this.newRotation = new OIMO.Vec3();
  92882. this.currentRotation = new OIMO.Vec3();
  92883. this.controlRot = false;
  92884. this.controlRotInTime = false;
  92885. // Is the translational velocity.
  92886. this.linearVelocity = new OIMO.Vec3();
  92887. // Is the angular velocity.
  92888. this.angularVelocity = new OIMO.Vec3();
  92889. // return matrix for three.js
  92890. this.matrix = new OIMO.Mat44();
  92891. //--------------------------------------------
  92892. // Please do not change from the outside this variables.
  92893. //--------------------------------------------
  92894. // It is a world that rigid body has been added.
  92895. this.parent = null;
  92896. this.contactLink = null;
  92897. this.numContacts = 0;
  92898. // An array of shapes that are included in the rigid body.
  92899. this.shapes = null;
  92900. // The number of shapes that are included in the rigid body.
  92901. this.numShapes = 0;
  92902. // It is the link array of joint that is connected to the rigid body.
  92903. this.jointLink = null;
  92904. // The number of joints that are connected to the rigid body.
  92905. this.numJoints = 0;
  92906. // It is the world coordinate of the center of gravity in the sleep just before.
  92907. this.sleepPosition = new OIMO.Vec3();
  92908. // It is a quaternion that represents the attitude of sleep just before.
  92909. this.sleepOrientation = new OIMO.Quat();
  92910. // I will show this rigid body to determine whether it is a rigid body static.
  92911. this.isStatic = false;
  92912. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  92913. this.isDynamic = false;
  92914. // It is a rotation matrix representing the orientation.
  92915. this.rotation = new OIMO.Mat33();
  92916. //--------------------------------------------
  92917. // It will be recalculated automatically from the shape, which is included.
  92918. //--------------------------------------------
  92919. // This is the weight.
  92920. this.mass = NaN;
  92921. // It is the reciprocal of the mass.
  92922. this.inverseMass = NaN;
  92923. // It is the inverse of the inertia tensor in the world system.
  92924. this.inverseInertia = new OIMO.Mat33();
  92925. // It is the inertia tensor in the initial state.
  92926. this.localInertia = new OIMO.Mat33();
  92927. // It is the inverse of the inertia tensor in the initial state.
  92928. this.inverseLocalInertia = new OIMO.Mat33();
  92929. // I indicates rigid body whether it has been added to the simulation Island.
  92930. this.addedToIsland = false;
  92931. // It shows how to sleep rigid body.
  92932. this.allowSleep = true;
  92933. // This is the time from when the rigid body at rest.
  92934. this.sleepTime = 0;
  92935. // I shows rigid body to determine whether it is a sleep state.
  92936. this.sleeping = false;
  92937. };
  92938. OIMO.RigidBody.prototype = {
  92939. constructor: OIMO.RigidBody,
  92940. /**
  92941. * I'll add a shape to rigid body.
  92942. * If you add a shape, please call the setupMass method to step up to the start of the next.
  92943. * @param shape shape to Add
  92944. */
  92945. addShape: function (shape) {
  92946. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  92947. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  92948. this.shapes = shape;
  92949. shape.parent = this;
  92950. if (this.parent) this.parent.addShape(shape);
  92951. this.numShapes++;
  92952. },
  92953. /**
  92954. * I will delete the shape from the rigid body.
  92955. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  92956. * @param shape shape to Delete
  92957. */
  92958. removeShape: function (shape) {
  92959. var remove = shape;
  92960. if (remove.parent != this) return;
  92961. var prev = remove.prev;
  92962. var next = remove.next;
  92963. if (prev != null) prev.next = next;
  92964. if (next != null) next.prev = prev;
  92965. if (this.shapes == remove) this.shapes = next;
  92966. remove.prev = null;
  92967. remove.next = null;
  92968. remove.parent = null;
  92969. if (this.parent) this.parent.removeShape(remove);
  92970. this.numShapes--;
  92971. },
  92972. remove: function () {
  92973. this.dispose();
  92974. },
  92975. dispose: function () {
  92976. this.parent.removeRigidBody(this);
  92977. },
  92978. checkContact: function (name) {
  92979. this.parent.checkContact(this.name, name);
  92980. },
  92981. /**
  92982. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  92983. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  92984. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  92985. * the rigid body's position will be adjusted to the center of gravity.
  92986. * @param type
  92987. * @param adjustPosition
  92988. */
  92989. setupMass: function (type, AdjustPosition) {
  92990. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  92991. this.type = type || OIMO.BODY_DYNAMIC;
  92992. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  92993. this.isStatic = this.type == OIMO.BODY_STATIC;
  92994. this.mass = 0;
  92995. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  92996. var te = this.localInertia.elements;
  92997. //
  92998. var tmpM = new OIMO.Mat33();
  92999. var tmpV = new OIMO.Vec3();
  93000. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93001. shape.calculateMassInfo(this.massInfo);
  93002. var shapeMass = this.massInfo.mass;
  93003. var relX = shape.relativePosition.x;
  93004. var relY = shape.relativePosition.y;
  93005. var relZ = shape.relativePosition.z;
  93006. /*tmpV.x+=relX*shapeMass;
  93007. tmpV.y+=relY*shapeMass;
  93008. tmpV.z+=relZ*shapeMass;*/
  93009. tmpV.addScale(shape.relativePosition, shapeMass);
  93010. this.mass += shapeMass;
  93011. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  93012. this.localInertia.addEqual(tmpM);
  93013. // add offset inertia
  93014. te[0] += shapeMass * (relY * relY + relZ * relZ);
  93015. te[4] += shapeMass * (relX * relX + relZ * relZ);
  93016. te[8] += shapeMass * (relX * relX + relY * relY);
  93017. var xy = shapeMass * relX * relY;
  93018. var yz = shapeMass * relY * relZ;
  93019. var zx = shapeMass * relZ * relX;
  93020. te[1] -= xy;
  93021. te[3] -= xy;
  93022. te[2] -= yz;
  93023. te[6] -= yz;
  93024. te[5] -= zx;
  93025. te[7] -= zx;
  93026. }
  93027. this.inverseMass = 1 / this.mass;
  93028. tmpV.scaleEqual(this.inverseMass);
  93029. if (adjustPosition) {
  93030. this.position.addEqual(tmpV);
  93031. for (shape = this.shapes; shape != null; shape = shape.next) {
  93032. shape.relativePosition.subEqual(tmpV);
  93033. }
  93034. // subtract offset inertia
  93035. relX = tmpV.x;
  93036. relY = tmpV.y;
  93037. relZ = tmpV.z;
  93038. //var te = this.localInertia.elements;
  93039. te[0] -= this.mass * (relY * relY + relZ * relZ);
  93040. te[4] -= this.mass * (relX * relX + relZ * relZ);
  93041. te[8] -= this.mass * (relX * relX + relY * relY);
  93042. xy = this.mass * relX * relY;
  93043. yz = this.mass * relY * relZ;
  93044. zx = this.mass * relZ * relX;
  93045. te[1] += xy;
  93046. te[3] += xy;
  93047. te[2] += yz;
  93048. te[6] += yz;
  93049. te[5] += zx;
  93050. te[7] += zx;
  93051. }
  93052. this.inverseLocalInertia.invert(this.localInertia);
  93053. if (this.type == OIMO.BODY_STATIC) {
  93054. this.inverseMass = 0;
  93055. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  93056. }
  93057. this.syncShapes();
  93058. this.awake();
  93059. },
  93060. /**
  93061. * Awake the rigid body.
  93062. */
  93063. awake: function () {
  93064. if (!this.allowSleep || !this.sleeping) return;
  93065. this.sleeping = false;
  93066. this.sleepTime = 0;
  93067. // awake connected constraints
  93068. var cs = this.contactLink;
  93069. while (cs != null) {
  93070. cs.body.sleepTime = 0;
  93071. cs.body.sleeping = false;
  93072. cs = cs.next;
  93073. }
  93074. var js = this.jointLink;
  93075. while (js != null) {
  93076. js.body.sleepTime = 0;
  93077. js.body.sleeping = false;
  93078. js = js.next;
  93079. }
  93080. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93081. shape.updateProxy();
  93082. }
  93083. },
  93084. /**
  93085. * Sleep the rigid body.
  93086. */
  93087. sleep: function () {
  93088. if (!this.allowSleep || this.sleeping) return;
  93089. this.linearVelocity.set(0, 0, 0);
  93090. this.angularVelocity.set(0, 0, 0);
  93091. this.sleepPosition.copy(this.position);
  93092. this.sleepOrientation.copy(this.orientation);
  93093. /*this.linearVelocity.x=0;
  93094. this.linearVelocity.y=0;
  93095. this.linearVelocity.z=0;
  93096. this.angularVelocity.x=0;
  93097. this.angularVelocity.y=0;
  93098. this.angularVelocity.z=0;
  93099. this.sleepPosition.x=this.position.x;
  93100. this.sleepPosition.y=this.position.y;
  93101. this.sleepPosition.z=this.position.z;*/
  93102. /*this.sleepOrientation.s=this.orientation.s;
  93103. this.sleepOrientation.x=this.orientation.x;
  93104. this.sleepOrientation.y=this.orientation.y;
  93105. this.sleepOrientation.z=this.orientation.z;*/
  93106. this.sleepTime = 0;
  93107. this.sleeping = true;
  93108. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93109. shape.updateProxy();
  93110. }
  93111. },
  93112. /**
  93113. * Get whether the rigid body has not any connection with others.
  93114. * @return
  93115. */
  93116. isLonely: function () {
  93117. return this.numJoints == 0 && this.numContacts == 0;
  93118. },
  93119. /**
  93120. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  93121. * This method is invoked automatically when calling the step of the World,
  93122. * There is no need to call from outside usually.
  93123. * @param timeStep time
  93124. */
  93125. updatePosition: function (timeStep) {
  93126. switch (this.type) {
  93127. case OIMO.BODY_STATIC:
  93128. this.linearVelocity.set(0, 0, 0);
  93129. this.angularVelocity.set(0, 0, 0);
  93130. // ONLY FOR TEST
  93131. if (this.controlPos) {
  93132. this.position.copy(this.newPosition);
  93133. this.controlPos = false;
  93134. }
  93135. if (this.controlRot) {
  93136. this.orientation.copy(this.newOrientation);
  93137. this.controlRot = false;
  93138. }
  93139. /*this.linearVelocity.x=0;
  93140. this.linearVelocity.y=0;
  93141. this.linearVelocity.z=0;
  93142. this.angularVelocity.x=0;
  93143. this.angularVelocity.y=0;
  93144. this.angularVelocity.z=0;*/
  93145. break;
  93146. case OIMO.BODY_DYNAMIC:
  93147. if (this.controlPos) {
  93148. this.angularVelocity.set(0, 0, 0);
  93149. this.linearVelocity.set(0, 0, 0);
  93150. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  93151. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  93152. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  93153. this.controlPos = false;
  93154. }
  93155. if (this.controlRot) {
  93156. this.angularVelocity.set(0, 0, 0);
  93157. this.orientation.copy(this.newOrientation);
  93158. //var t=timeStep//*0.5;
  93159. //var q = new OIMO.Quat();
  93160. //q.sub(this.newOrientation, this.orientation);
  93161. //q.normalize(q);
  93162. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  93163. q.x = (this.newOrientation.x - this.orientation.x)/t;
  93164. q.y = (this.newOrientation.y - this.orientation.y)/t;
  93165. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  93166. //this.angularVelocity.applyQuaternion(q);
  93167. //this.angularVelocity.x = this.angularVelocity.x/t;
  93168. //this.angularVelocity.y = this.angularVelocity.y/t;
  93169. //this.angularVelocity.z = this.angularVelocity.z/t;
  93170. this.controlRot = false;
  93171. }
  93172. this.position.addTime(this.linearVelocity, timeStep);
  93173. this.orientation.addTime(this.angularVelocity, timeStep);
  93174. break;
  93175. default: OIMO.Error("RigidBody", "Invalid type.");
  93176. }
  93177. this.syncShapes();
  93178. },
  93179. rotateInertia: function (rot, inertia, out) {
  93180. var tm1 = rot.elements;
  93181. var tm2 = inertia.elements;
  93182. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  93183. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  93184. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  93185. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  93186. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  93187. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  93188. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  93189. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  93190. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  93191. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  93192. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  93193. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  93194. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  93195. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  93196. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  93197. var oe = out.elements;
  93198. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  93199. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  93200. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  93201. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  93202. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  93203. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  93204. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  93205. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  93206. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  93207. },
  93208. syncShapes: function () {
  93209. var s = this.orientation.s;
  93210. var x = this.orientation.x;
  93211. var y = this.orientation.y;
  93212. var z = this.orientation.z;
  93213. var x2 = 2 * x;
  93214. var y2 = 2 * y;
  93215. var z2 = 2 * z;
  93216. var xx = x * x2;
  93217. var yy = y * y2;
  93218. var zz = z * z2;
  93219. var xy = x * y2;
  93220. var yz = y * z2;
  93221. var xz = x * z2;
  93222. var sx = s * x2;
  93223. var sy = s * y2;
  93224. var sz = s * z2;
  93225. var tr = this.rotation.elements;
  93226. tr[0] = 1 - yy - zz;
  93227. tr[1] = xy - sz;
  93228. tr[2] = xz + sy;
  93229. tr[3] = xy + sz;
  93230. tr[4] = 1 - xx - zz;
  93231. tr[5] = yz - sx;
  93232. tr[6] = xz - sy;
  93233. tr[7] = yz + sx;
  93234. tr[8] = 1 - xx - yy;
  93235. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  93236. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93237. //var relPos=shape.relativePosition;
  93238. //var relRot=shape.relativeRotation;
  93239. //var rot=shape.rotation;
  93240. /*var lx=relPos.x;
  93241. var ly=relPos.y;
  93242. var lz=relPos.z;
  93243. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  93244. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  93245. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  93246. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  93247. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  93248. // add by QuaziKb
  93249. shape.rotation.mul(this.rotation, shape.relativeRotation);
  93250. shape.updateProxy();
  93251. }
  93252. },
  93253. applyImpulse: function (position, force) {
  93254. this.linearVelocity.addScale(force, this.inverseMass);
  93255. /*this.linearVelocity.x+=force.x*this.inverseMass;
  93256. this.linearVelocity.y+=force.y*this.inverseMass;
  93257. this.linearVelocity.z+=force.z*this.inverseMass;*/
  93258. var rel = new OIMO.Vec3();
  93259. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  93260. this.angularVelocity.addEqual(rel);
  93261. /*this.angularVelocity.x+=rel.x;
  93262. this.angularVelocity.y+=rel.y;
  93263. this.angularVelocity.z+=rel.z;*/
  93264. },
  93265. //---------------------------------------------
  93266. //
  93267. // FOR THREE JS
  93268. //
  93269. //---------------------------------------------
  93270. rotationVectToQuad: function (rot) {
  93271. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  93272. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  93273. },
  93274. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  93275. var len = ax * ax + ay * ay + az * az;
  93276. if (len > 0) {
  93277. len = 1 / OIMO.sqrt(len);
  93278. ax *= len;
  93279. ay *= len;
  93280. az *= len;
  93281. }
  93282. var sin = OIMO.sin(rad * 0.5);
  93283. var cos = OIMO.cos(rad * 0.5);
  93284. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  93285. },
  93286. //---------------------------------------------
  93287. // SET DYNAMIQUE POSITION AND ROTATION
  93288. //---------------------------------------------
  93289. setPosition: function (pos) {
  93290. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  93291. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  93292. this.controlPos = true;
  93293. },
  93294. setQuaternion: function (q) {
  93295. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  93296. this.newOrientation.set(q.x, q.y, q.z, q.w);
  93297. this.controlRot = true;
  93298. },
  93299. setRotation: function (rot) {
  93300. this.newOrientation = this.rotationVectToQuad(rot);
  93301. this.controlRot = true;
  93302. },
  93303. //---------------------------------------------
  93304. // RESET DYNAMIQUE POSITION AND ROTATION
  93305. //---------------------------------------------
  93306. resetPosition: function (x, y, z) {
  93307. this.linearVelocity.set(0, 0, 0);
  93308. this.angularVelocity.set(0, 0, 0);
  93309. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  93310. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  93311. this.awake();
  93312. },
  93313. resetQuaternion: function (q) {
  93314. this.angularVelocity.set(0, 0, 0);
  93315. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  93316. this.awake();
  93317. },
  93318. resetRotation: function (x, y, z) {
  93319. this.angularVelocity.set(0, 0, 0);
  93320. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  93321. this.awake();
  93322. },
  93323. //---------------------------------------------
  93324. // GET POSITION AND ROTATION
  93325. //---------------------------------------------
  93326. getPosition: function () {
  93327. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  93328. },
  93329. getRotation: function () {
  93330. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  93331. },
  93332. getQuaternion: function () {
  93333. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  93334. },
  93335. getMatrix: function () {
  93336. var m = this.matrix.elements;
  93337. var r, p;
  93338. if (!this.sleeping) {
  93339. // rotation matrix
  93340. r = this.rotation.elements;
  93341. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  93342. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  93343. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  93344. // position matrix
  93345. p = this.position;
  93346. m[12] = p.x * OIMO.WORLD_SCALE;
  93347. m[13] = p.y * OIMO.WORLD_SCALE;
  93348. m[14] = p.z * OIMO.WORLD_SCALE;
  93349. // sleep or not ?
  93350. m[15] = 0;
  93351. } else {
  93352. m[15] = 1;
  93353. }
  93354. return m;
  93355. }
  93356. };
  93357. /**
  93358. * The main class of body.
  93359. * is for simplify creation process and data access of rigidRody
  93360. * Rigid body has the shape of a single or multiple collision processing,
  93361. * all setting in object
  93362. *
  93363. * @author loth
  93364. */
  93365. OIMO.Body = function (Obj) {
  93366. var obj = Obj || {};
  93367. if (!obj.world) return;
  93368. if (obj.type === undefined) obj.type = "box";
  93369. this.name = obj.name || '';
  93370. // obsolete use world.add(obj)
  93371. this.body = obj.world.add(obj);
  93372. /*
  93373. // the world where i am
  93374. this.parent = obj.world;
  93375. // Yep my name
  93376. this.name = obj.name || '';
  93377. // I'm dynamique or not
  93378. var move = obj.move || false;
  93379. // I can sleep or not
  93380. var noSleep = obj.noSleep || false;
  93381. // My start position
  93382. var p = obj.pos || [0,0,0];
  93383. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  93384. // My size
  93385. var s = obj.size || [1,1,1];
  93386. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  93387. // My rotation in degre
  93388. var rot = obj.rot || [0,0,0];
  93389. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  93390. var r = [];
  93391. for (var i=0; i<rot.length/3; i++){
  93392. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  93393. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  93394. }
  93395. // My physics setting
  93396. var sc = obj.sc || new OIMO.ShapeConfig();
  93397. if(obj.config){
  93398. // The density of the shape.
  93399. sc.density = obj.config[0] || 1;
  93400. // The coefficient of friction of the shape.
  93401. sc.friction = obj.config[1] || 0.4;
  93402. // The coefficient of restitution of the shape.
  93403. sc.restitution = obj.config[2] || 0.2;
  93404. // The bits of the collision groups to which the shape belongs.
  93405. sc.belongsTo = obj.config[3] || 1;
  93406. // The bits of the collision groups with which the shape collides.
  93407. sc.collidesWith = obj.config[4] || 0xffffffff;
  93408. }
  93409. if(obj.massPos){
  93410. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  93411. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  93412. }
  93413. if(obj.massRot){
  93414. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  93415. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  93416. }
  93417. // My rigidbody
  93418. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  93419. // My shapes
  93420. var shapes = [];
  93421. var type = obj.type || "box";
  93422. if( typeof type === 'string' ) type = [type];// single shape
  93423. var n, n2;
  93424. for(var i=0; i<type.length; i++){
  93425. n = i*3;
  93426. n2 = i*4;
  93427. switch(type[i]){
  93428. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  93429. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  93430. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  93431. }
  93432. this.body.addShape(shapes[i]);
  93433. if(i>0){
  93434. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  93435. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  93436. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  93437. }
  93438. }
  93439. // I'm static or i move
  93440. if(move){
  93441. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  93442. else this.body.setupMass(0x1, true);
  93443. if(noSleep) this.body.allowSleep = false;
  93444. else this.body.allowSleep = true;
  93445. } else {
  93446. this.body.setupMass(0x2);
  93447. }
  93448. this.body.name = this.name;
  93449. this.sleeping = this.body.sleeping;
  93450. // finaly add to physics world
  93451. this.parent.addRigidBody(this.body);*/
  93452. }
  93453. OIMO.Body.prototype = {
  93454. constructor: OIMO.Body,
  93455. // SET
  93456. setPosition: function (pos) {
  93457. this.body.setPosition(pos);
  93458. },
  93459. setQuaternion: function (q) {
  93460. this.body.setQuaternion(q);
  93461. },
  93462. setRotation: function (rot) {
  93463. this.body.setRotation(rot);
  93464. },
  93465. // GET
  93466. getPosition: function () {
  93467. return this.body.getPosition();
  93468. },
  93469. getRotation: function () {
  93470. return this.body.getRotation();
  93471. },
  93472. getQuaternion: function () {
  93473. return this.body.getQuaternion();
  93474. },
  93475. getMatrix: function () {
  93476. return this.body.getMatrix();
  93477. },
  93478. getSleep: function () {
  93479. return this.body.sleeping;
  93480. },
  93481. // RESET
  93482. resetPosition: function (x, y, z) {
  93483. this.body.resetPosition(x, y, z);
  93484. },
  93485. resetRotation: function (x, y, z) {
  93486. this.body.resetRotation(x, y, z);
  93487. },
  93488. // force wakeup
  93489. awake: function () {
  93490. this.body.awake();
  93491. },
  93492. // remove rigidbody
  93493. remove: function () {
  93494. this.body.dispose();
  93495. //this.parent.removeRigidBody(this.body);
  93496. },
  93497. // test if this object hit another
  93498. checkContact: function (name) {
  93499. this.body.checkContact(name);
  93500. //this.parent.checkContact(this.name, name);
  93501. }
  93502. }
  93503. /**
  93504. * The main class of link.
  93505. * is for simplify creation process and data access of Joint
  93506. * all setting in object
  93507. *
  93508. * @author loth
  93509. */
  93510. OIMO.Link = function (Obj) {
  93511. var obj = Obj || {};
  93512. if (!obj.world) return;
  93513. if (obj.type === undefined) obj.type = "jointHinge";
  93514. this.name = obj.name || '';
  93515. // obsolete use world.add(obj)
  93516. this.joint = obj.world.add(obj);
  93517. // the world where i am
  93518. /*this.parent = obj.world;
  93519. this.name = obj.name || '';
  93520. var type = obj.type || "jointHinge";
  93521. var axe1 = obj.axe1 || [1,0,0];
  93522. var axe2 = obj.axe2 || [1,0,0];
  93523. var pos1 = obj.pos1 || [0,0,0];
  93524. var pos2 = obj.pos2 || [0,0,0];
  93525. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  93526. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  93527. var min, max;
  93528. if(type==="jointDistance"){
  93529. min = obj.min || 0;
  93530. max = obj.max || 10;
  93531. min = min*OIMO.INV_SCALE;
  93532. max = max*OIMO.INV_SCALE;
  93533. }else{
  93534. min = obj.min || 57.29578;
  93535. max = obj.max || 0;
  93536. min = min*OIMO.TO_RAD;
  93537. max = max*OIMO.TO_RAD;
  93538. }
  93539. var limit = obj.limit || null;
  93540. var spring = obj.spring || null;
  93541. var motor = obj.motor || null;
  93542. // joint setting
  93543. var jc = new OIMO.JointConfig();
  93544. jc.allowCollision = obj.collision || false;;
  93545. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  93546. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  93547. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  93548. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  93549. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  93550. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  93551. jc.body1 = obj.body1;
  93552. jc.body2 = obj.body2;
  93553. switch(type){
  93554. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  93555. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  93556. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  93557. break;
  93558. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  93559. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  93560. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  93561. break;
  93562. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  93563. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  93564. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  93565. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  93566. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  93567. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  93568. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  93569. break;
  93570. }
  93571. this.joint.name = this.name;
  93572. // finaly add to physics world
  93573. this.parent.addJoint(this.joint);*/
  93574. }
  93575. OIMO.Link.prototype = {
  93576. constructor: OIMO.Link,
  93577. getPosition: function () {
  93578. // array of two vect3 [point1, point2]
  93579. return this.joint.getPosition();
  93580. },
  93581. getMatrix: function () {
  93582. return this.joint.getMatrix();
  93583. },
  93584. // remove joint
  93585. remove: function () {
  93586. this.joint.dispose();
  93587. //this.parent.removeJoint(this.joint);
  93588. },
  93589. // force wakeup linked body
  93590. awake: function () {
  93591. this.joint.awake();
  93592. }
  93593. }
  93594. /**
  93595. * The Dictionary class for testing
  93596. * @author lo-th
  93597. */
  93598. OIMO.Dictionary = function () {
  93599. this.data = {};
  93600. this.keys = [];
  93601. };
  93602. OIMO.Dictionary.prototype = {
  93603. constructor: OIMO.Dictionary,
  93604. set: function (value) {
  93605. var key = value.id;
  93606. if (!this.get[key]) this.keys.push(key);
  93607. this.data[key] = value;
  93608. },
  93609. get: function (id) {
  93610. return this.data[id];
  93611. },
  93612. del: function (value) {
  93613. var k = this.keys;
  93614. var n = k.indexOf(value.id);
  93615. if (n > -1) {
  93616. delete this.data[k[n]];
  93617. k.splice(n, 1);
  93618. }
  93619. },
  93620. reset: function () {
  93621. var data = this.data, keys = this.keys, key;
  93622. while (keys.length > 0) {
  93623. key = keys.pop();
  93624. delete data[key];
  93625. }
  93626. }
  93627. };
  93628. OIMO.Performance = function (world) {
  93629. this.parent = world;
  93630. this.infos = new OIMO_ARRAY_TYPE(13);
  93631. this.f = [0, 0, 0];
  93632. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  93633. this.broadPhase = this.types[this.parent.broadPhase.types];
  93634. this.version = OIMO.REVISION;
  93635. this.fps = 0;
  93636. this.broadPhaseTime = 0;
  93637. this.narrowPhaseTime = 0;
  93638. this.solvingTime = 0;
  93639. //this.updatingTime = 0;
  93640. this.totalTime = 0;
  93641. };
  93642. OIMO.Performance.prototype = {
  93643. upfps: function () {
  93644. this.f[1] = Date.now();
  93645. 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]++;
  93646. },
  93647. updatingTime: function () {
  93648. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  93649. },
  93650. show: function () {
  93651. var info = [
  93652. "Oimo.js " + this.version + "<br>",
  93653. this.broadPhase + "<br><br>",
  93654. "FPS: " + this.fps + " fps<br><br>",
  93655. "rigidbody " + this.parent.numRigidBodies + "<br>",
  93656. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  93657. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  93658. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  93659. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  93660. "Time in milliseconde<br><br>",
  93661. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  93662. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  93663. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  93664. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  93665. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  93666. ].join("\n");
  93667. return info;
  93668. },
  93669. toArray: function () {
  93670. this.infos[0] = this.parent.broadPhase.types;
  93671. this.infos[1] = this.parent.numRigidBodies;
  93672. this.infos[2] = this.parent.numContacts;
  93673. this.infos[3] = this.parent.broadPhase.numPairChecks;
  93674. this.infos[4] = this.parent.numContactPoints;
  93675. this.infos[5] = this.parent.numIslands;
  93676. this.infos[6] = this.broadPhaseTime;
  93677. this.infos[7] = this.narrowPhaseTime;
  93678. this.infos[8] = this.solvingTime;
  93679. this.infos[9] = this.updatingTime();
  93680. this.infos[10] = this.totalTime;
  93681. this.infos[11] = this.fps;
  93682. return this.infos;
  93683. }
  93684. };
  93685. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  93686. this.elements = new OIMO_ARRAY_TYPE(16);
  93687. var te = this.elements;
  93688. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  93689. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  93690. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  93691. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  93692. };
  93693. OIMO.Mat44.prototype = {
  93694. constructor: OIMO.Mat44,
  93695. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  93696. var te = this.elements;
  93697. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  93698. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  93699. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  93700. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  93701. return this;
  93702. }/*,
  93703. extractRotation: function () {
  93704. var v1 = new THREE.Vector3();
  93705. return function ( m ) {
  93706. var te = this.elements;
  93707. var me = m.elements;
  93708. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  93709. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  93710. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  93711. te[ 0 ] = me[ 0 ] * scaleX;
  93712. te[ 1 ] = me[ 1 ] * scaleX;
  93713. te[ 2 ] = me[ 2 ] * scaleX;
  93714. te[ 4 ] = me[ 4 ] * scaleY;
  93715. te[ 5 ] = me[ 5 ] * scaleY;
  93716. te[ 6 ] = me[ 6 ] * scaleY;
  93717. te[ 8 ] = me[ 8 ] * scaleZ;
  93718. te[ 9 ] = me[ 9 ] * scaleZ;
  93719. te[ 10 ] = me[ 10 ] * scaleZ;
  93720. return this;
  93721. };
  93722. }() */
  93723. }
  93724. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  93725. this.elements = new OIMO_ARRAY_TYPE(9);
  93726. var te = this.elements;
  93727. this.init(
  93728. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  93729. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  93730. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  93731. );
  93732. };
  93733. OIMO.Mat33.prototype = {
  93734. constructor: OIMO.Mat33,
  93735. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  93736. var te = this.elements;
  93737. te[0] = e00; te[1] = e01; te[2] = e02;
  93738. te[3] = e10; te[4] = e11; te[5] = e12;
  93739. te[6] = e20; te[7] = e21; te[8] = e22;
  93740. return this;
  93741. },
  93742. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  93743. var te = this.elements;
  93744. te[0] = e00; te[1] = e01; te[2] = e02;
  93745. te[3] = e10; te[4] = e11; te[5] = e12;
  93746. te[6] = e20; te[7] = e21; te[8] = e22;
  93747. return this;
  93748. },
  93749. multiply: function (s) {
  93750. var te = this.elements;
  93751. te[0] *= s; te[1] *= s; te[2] *= s;
  93752. te[3] *= s; te[4] *= s; te[5] *= s;
  93753. te[6] *= s; te[7] *= s; te[8] *= s;
  93754. return this;
  93755. },
  93756. add: function (m1, m2) {
  93757. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  93758. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  93759. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  93760. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  93761. return this;
  93762. },
  93763. addEqual: function (m) {
  93764. var te = this.elements, tem = m.elements;
  93765. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  93766. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  93767. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  93768. return this;
  93769. },
  93770. sub: function (m1, m2) {
  93771. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  93772. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  93773. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  93774. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  93775. return this;
  93776. },
  93777. subEqual: function (m) {
  93778. var te = this.elements, tem = m.elements;
  93779. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  93780. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  93781. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  93782. return this;
  93783. },
  93784. scale: function (m, s) {
  93785. var te = this.elements, tm = m.elements;
  93786. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  93787. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  93788. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  93789. return this;
  93790. },
  93791. scaleEqual: function (s) {
  93792. var te = this.elements;
  93793. te[0] *= s; te[1] *= s; te[2] *= s;
  93794. te[3] *= s; te[4] *= s; te[5] *= s;
  93795. te[6] *= s; te[7] *= s; te[8] *= s;
  93796. return this;
  93797. },
  93798. mul: function (m1, m2) {
  93799. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  93800. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  93801. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  93802. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  93803. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  93804. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  93805. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  93806. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  93807. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  93808. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  93809. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  93810. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  93811. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  93812. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  93813. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  93814. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  93815. return this;
  93816. },
  93817. mulScale: function (m, sx, sy, sz, Prepend) {
  93818. var prepend = Prepend || false;
  93819. var te = this.elements, tm = m.elements;
  93820. if (prepend) {
  93821. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  93822. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  93823. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  93824. } else {
  93825. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  93826. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  93827. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  93828. }
  93829. return this;
  93830. },
  93831. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  93832. var prepend = Prepend || false;
  93833. var s = OIMO.sin(rad);
  93834. var c = OIMO.cos(rad);
  93835. var c1 = 1 - c;
  93836. var r00 = ax * ax * c1 + c;
  93837. var r01 = ax * ay * c1 - az * s;
  93838. var r02 = ax * az * c1 + ay * s;
  93839. var r10 = ay * ax * c1 + az * s;
  93840. var r11 = ay * ay * c1 + c;
  93841. var r12 = ay * az * c1 - ax * s;
  93842. var r20 = az * ax * c1 - ay * s;
  93843. var r21 = az * ay * c1 + ax * s;
  93844. var r22 = az * az * c1 + c;
  93845. var tm = m.elements;
  93846. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  93847. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  93848. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  93849. var te = this.elements;
  93850. if (prepend) {
  93851. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  93852. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  93853. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  93854. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  93855. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  93856. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  93857. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  93858. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  93859. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  93860. } else {
  93861. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  93862. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  93863. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  93864. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  93865. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  93866. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  93867. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  93868. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  93869. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  93870. }
  93871. return this;
  93872. },
  93873. transpose: function (m) {
  93874. var te = this.elements, tm = m.elements;
  93875. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  93876. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  93877. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  93878. return this;
  93879. },
  93880. setQuat: function (q) {
  93881. var te = this.elements,
  93882. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  93883. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  93884. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  93885. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  93886. te[0] = 1 - yy - zz;
  93887. te[1] = xy - sz;
  93888. te[2] = xz + sy;
  93889. te[3] = xy + sz;
  93890. te[4] = 1 - xx - zz;
  93891. te[5] = yz - sx;
  93892. te[6] = xz - sy;
  93893. te[7] = yz + sx;
  93894. te[8] = 1 - xx - yy;
  93895. return this;
  93896. },
  93897. invert: function (m) {
  93898. var te = this.elements, tm = m.elements,
  93899. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  93900. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  93901. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  93902. b01 = a4 * a8 - a7 * a5,
  93903. b11 = a7 * a2 - a1 * a8,
  93904. b21 = a1 * a5 - a4 * a2,
  93905. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  93906. if (dt != 0) { dt = 1.0 / dt; }
  93907. te[0] = dt * b01;//(a4*a8 - a5*a7);
  93908. te[1] = dt * b11;//(a2*a7 - a1*a8);
  93909. te[2] = dt * b21;//(a1*a5 - a2*a4);
  93910. te[3] = dt * (a5 * a6 - a3 * a8);
  93911. te[4] = dt * (a0 * a8 - a2 * a6);
  93912. te[5] = dt * (a2 * a3 - a0 * a5);
  93913. te[6] = dt * (a3 * a7 - a4 * a6);
  93914. te[7] = dt * (a1 * a6 - a0 * a7);
  93915. te[8] = dt * (a0 * a4 - a1 * a3);
  93916. return this;
  93917. },
  93918. /*copy: function(m){
  93919. var te = this.elements, tem = m.elements;
  93920. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  93921. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  93922. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  93923. return this;
  93924. },*/
  93925. toEuler: function () { // not work !!
  93926. function clamp(x) {
  93927. return OIMO.min(OIMO.max(x, -1), 1);
  93928. }
  93929. var te = this.elements;
  93930. var m11 = te[0], m12 = te[3], m13 = te[6];
  93931. var m21 = te[1], m22 = te[4], m23 = te[7];
  93932. var m31 = te[2], m32 = te[5], m33 = te[8];
  93933. var p = new OIMO.Vec3();
  93934. var d = new OIMO.Quat();
  93935. var s;
  93936. p.y = OIMO.asin(clamp(m13));
  93937. if (OIMO.abs(m13) < 0.99999) {
  93938. p.x = OIMO.atan2(-m23, m33);
  93939. p.z = OIMO.atan2(-m12, m11);
  93940. } else {
  93941. p.x = OIMO.atan2(m32, m22);
  93942. p.z = 0;
  93943. }
  93944. return p;
  93945. },
  93946. /*clone: function(){
  93947. var te = this.elements;
  93948. return new OIMO.Mat33(
  93949. te[0], te[1], te[2],
  93950. te[3], te[4], te[5],
  93951. te[6], te[7], te[8]
  93952. );
  93953. },*/
  93954. toString: function () {
  93955. var te = this.elements;
  93956. var text =
  93957. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  93958. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  93959. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  93960. return text;
  93961. },
  93962. // OK
  93963. multiplyScalar: function (s) {
  93964. var te = this.elements;
  93965. te[0] *= s; te[3] *= s; te[6] *= s;
  93966. te[1] *= s; te[4] *= s; te[7] *= s;
  93967. te[2] *= s; te[5] *= s; te[8] *= s;
  93968. return this;
  93969. },
  93970. identity: function () {
  93971. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  93972. return this;
  93973. },
  93974. clone: function () {
  93975. return new this.constructor().fromArray(this.elements);
  93976. },
  93977. copy: function (m) {
  93978. var me = m.elements;
  93979. this.set(
  93980. me[0], me[3], me[6],
  93981. me[1], me[4], me[7],
  93982. me[2], me[5], me[8]
  93983. );
  93984. return this;
  93985. },
  93986. fromArray: function (array) {
  93987. this.elements.set(array);
  93988. return this;
  93989. },
  93990. toArray: function () {
  93991. var te = this.elements;
  93992. return [
  93993. te[0], te[1], te[2],
  93994. te[3], te[4], te[5],
  93995. te[6], te[7], te[8]
  93996. ];
  93997. }
  93998. };
  93999. OIMO.Quat = function (s, x, y, z) {
  94000. this.s = (s !== undefined) ? s : 1;
  94001. this.x = x || 0;
  94002. this.y = y || 0;
  94003. this.z = z || 0;
  94004. };
  94005. OIMO.Quat.prototype = {
  94006. constructor: OIMO.Quat,
  94007. set: function (x, y, z, w) {
  94008. this.x = x;
  94009. this.y = y;
  94010. this.z = z;
  94011. this.s = w;
  94012. return this;
  94013. },
  94014. init: function (s, x, y, z) {
  94015. this.s = (s !== undefined) ? s : 1;
  94016. this.x = x || 0;
  94017. this.y = y || 0;
  94018. this.z = z || 0;
  94019. return this;
  94020. },
  94021. add: function (q1, q2) {
  94022. this.s = q1.s + q2.s;
  94023. this.x = q1.x + q2.x;
  94024. this.y = q1.y + q2.y;
  94025. this.z = q1.z + q2.z;
  94026. return this;
  94027. },
  94028. addTime: function (v, t) {
  94029. var x = v.x;
  94030. var y = v.y;
  94031. var z = v.z;
  94032. var qs = this.s;
  94033. var qx = this.x;
  94034. var qy = this.y;
  94035. var qz = this.z;
  94036. t *= 0.5;
  94037. var ns = (-x * qx - y * qy - z * qz) * t;
  94038. var nx = (x * qs + y * qz - z * qy) * t;
  94039. var ny = (-x * qz + y * qs + z * qx) * t;
  94040. var nz = (x * qy - y * qx + z * qs) * t;
  94041. qs += ns;
  94042. qx += nx;
  94043. qy += ny;
  94044. qz += nz;
  94045. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  94046. this.s = qs * s;
  94047. this.x = qx * s;
  94048. this.y = qy * s;
  94049. this.z = qz * s;
  94050. return this;
  94051. },
  94052. sub: function (q1, q2) {
  94053. this.s = q1.s - q2.s;
  94054. this.x = q1.x - q2.x;
  94055. this.y = q1.y - q2.y;
  94056. this.z = q1.z - q2.z;
  94057. return this;
  94058. },
  94059. scale: function (q, s) {
  94060. this.s = q.s * s;
  94061. this.x = q.x * s;
  94062. this.y = q.y * s;
  94063. this.z = q.z * s;
  94064. return this;
  94065. },
  94066. mul: function (q1, q2) {
  94067. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  94068. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  94069. this.x = ax * bs + as * bx + ay * bz - az * by;
  94070. this.y = ay * bs + as * by + az * bx - ax * bz;
  94071. this.z = az * bs + as * bz + ax * by - ay * bx;
  94072. this.s = as * bs - ax * bx - ay * by - az * bz;
  94073. return this;
  94074. },
  94075. arc: function (v1, v2) {
  94076. var x1 = v1.x;
  94077. var y1 = v1.y;
  94078. var z1 = v1.z;
  94079. var x2 = v2.x;
  94080. var y2 = v2.y;
  94081. var z2 = v2.z;
  94082. var d = x1 * x2 + y1 * y2 + z1 * z2;
  94083. if (d == -1) {
  94084. x2 = y1 * x1 - z1 * z1;
  94085. y2 = -z1 * y1 - x1 * x1;
  94086. z2 = x1 * z1 + y1 * y1;
  94087. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  94088. this.s = 0;
  94089. this.x = x2 * d;
  94090. this.y = y2 * d;
  94091. this.z = z2 * d;
  94092. return this;
  94093. }
  94094. var cx = y1 * z2 - z1 * y2;
  94095. var cy = z1 * x2 - x1 * z2;
  94096. var cz = x1 * y2 - y1 * x2;
  94097. this.s = OIMO.sqrt((1 + d) * 0.5);
  94098. d = 0.5 / this.s;
  94099. this.x = cx * d;
  94100. this.y = cy * d;
  94101. this.z = cz * d;
  94102. return this;
  94103. },
  94104. normalize: function (q) {
  94105. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  94106. if (len > 0) { len = 1 / len; }
  94107. this.s = q.s * len;
  94108. this.x = q.x * len;
  94109. this.y = q.y * len;
  94110. this.z = q.z * len;
  94111. return this;
  94112. },
  94113. invert: function (q) {
  94114. this.s = q.s;
  94115. this.x = -q.x;
  94116. this.y = -q.y;
  94117. this.z = -q.z;
  94118. return this;
  94119. },
  94120. length: function () {
  94121. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  94122. },
  94123. copy: function (q) {
  94124. this.s = q.s;
  94125. this.x = q.x;
  94126. this.y = q.y;
  94127. this.z = q.z;
  94128. return this;
  94129. },
  94130. testDiff: function (q) {
  94131. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  94132. else return false;
  94133. },
  94134. clone: function (q) {
  94135. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  94136. },
  94137. toString: function () {
  94138. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  94139. }
  94140. }
  94141. // for three easy export
  94142. OIMO.Quaternion = function (x, y, z, w) {
  94143. this.x = x || 0;
  94144. this.y = y || 0;
  94145. this.z = z || 0;
  94146. this.w = (w !== undefined) ? w : 1;
  94147. };
  94148. OIMO.Quaternion.prototype = {
  94149. constructor: OIMO.Quaternion,
  94150. setFromRotationMatrix: function (m) {
  94151. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  94152. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  94153. var te = m.elements,
  94154. m11 = te[0], m12 = te[1], m13 = te[2],
  94155. m21 = te[3], m22 = te[4], m23 = te[5],
  94156. m31 = te[6], m32 = te[7], m33 = te[8],
  94157. trace = m11 + m22 + m33,
  94158. s;
  94159. if (trace > 0) {
  94160. s = 0.5 / OIMO.sqrt(trace + 1.0);
  94161. this.w = 0.25 / s;
  94162. this.x = (m32 - m23) * s;
  94163. this.y = (m13 - m31) * s;
  94164. this.z = (m21 - m12) * s;
  94165. } else if (m11 > m22 && m11 > m33) {
  94166. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  94167. this.w = (m32 - m23) / s;
  94168. this.x = 0.25 * s;
  94169. this.y = (m12 + m21) / s;
  94170. this.z = (m13 + m31) / s;
  94171. } else if (m22 > m33) {
  94172. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  94173. this.w = (m13 - m31) / s;
  94174. this.x = (m12 + m21) / s;
  94175. this.y = 0.25 * s;
  94176. this.z = (m23 + m32) / s;
  94177. } else {
  94178. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  94179. this.w = (m21 - m12) / s;
  94180. this.x = (m13 + m31) / s;
  94181. this.y = (m23 + m32) / s;
  94182. this.z = 0.25 * s;
  94183. }
  94184. //this.onChangeCallback();
  94185. return this;
  94186. }
  94187. }
  94188. OIMO.Vec3 = function (x, y, z) {
  94189. this.x = x || 0;
  94190. this.y = y || 0;
  94191. this.z = z || 0;
  94192. };
  94193. OIMO.Vec3.prototype = {
  94194. constructor: OIMO.Vec3,
  94195. init: function (x, y, z) {
  94196. this.x = x || 0;
  94197. this.y = y || 0;
  94198. this.z = z || 0;
  94199. return this;
  94200. },
  94201. set: function (x, y, z) {
  94202. this.x = x;
  94203. this.y = y;
  94204. this.z = z;
  94205. return this;
  94206. },
  94207. add: function (v1, v2) {
  94208. this.x = v1.x + v2.x;
  94209. this.y = v1.y + v2.y;
  94210. this.z = v1.z + v2.z;
  94211. return this;
  94212. },
  94213. addEqual: function (v) {
  94214. this.x += v.x;
  94215. this.y += v.y;
  94216. this.z += v.z;
  94217. return this;
  94218. },
  94219. addTime: function (v, t) {
  94220. this.x += v.x * t;
  94221. this.y += v.y * t;
  94222. this.z += v.z * t;
  94223. return this;
  94224. },
  94225. sub: function (v1, v2) {
  94226. this.x = v1.x - v2.x;
  94227. this.y = v1.y - v2.y;
  94228. this.z = v1.z - v2.z;
  94229. return this;
  94230. },
  94231. subEqual: function (v) {
  94232. this.x -= v.x;
  94233. this.y -= v.y;
  94234. this.z -= v.z;
  94235. return this;
  94236. },
  94237. addScale: function (v, s) {
  94238. this.x += v.x * s;
  94239. this.y += v.y * s;
  94240. this.z += v.z * s;
  94241. return this;
  94242. },
  94243. scale: function (v, s) {
  94244. this.x = v.x * s;
  94245. this.y = v.y * s;
  94246. this.z = v.z * s;
  94247. return this;
  94248. },
  94249. scaleEqual: function (s) {
  94250. this.x *= s;
  94251. this.y *= s;
  94252. this.z *= s;
  94253. return this;
  94254. },
  94255. /*dot: function(v){
  94256. return this.x*v.x+this.y*v.y+this.z*v.z;
  94257. },*/
  94258. cross: function (v1, v2) {
  94259. var ax = v1.x, ay = v1.y, az = v1.z,
  94260. bx = v2.x, by = v2.y, bz = v2.z;
  94261. this.x = ay * bz - az * by;
  94262. this.y = az * bx - ax * bz;
  94263. this.z = ax * by - ay * bx;
  94264. return this;
  94265. },
  94266. mul: function (o, v, m) {
  94267. var te = m.elements;
  94268. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  94269. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  94270. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  94271. return this;
  94272. },
  94273. mulMat: function (m, v) {
  94274. var te = m.elements;
  94275. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  94276. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  94277. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  94278. return this;
  94279. },
  94280. normalize: function (v) {
  94281. var x = v.x, y = v.y, z = v.z;
  94282. var l = x * x + y * y + z * z;
  94283. if (l > 0) {
  94284. l = 1 / OIMO.sqrt(l);
  94285. this.x = x * l;
  94286. this.y = y * l;
  94287. this.z = z * l;
  94288. }
  94289. return this;
  94290. },
  94291. /*norm: function(){
  94292. var x = this.x, y = this.y, z = this.z;
  94293. var l = x*x + y*y + z*z;
  94294. if (l > 0) {
  94295. l = 1 / OIMO.sqrt(l);
  94296. this.x = x*l;
  94297. this.y = y*l;
  94298. this.z = z*l;
  94299. }
  94300. return this;
  94301. },*/
  94302. invert: function (v) {
  94303. this.x = -v.x;
  94304. this.y = -v.y;
  94305. this.z = -v.z;
  94306. return this;
  94307. },
  94308. /*length: function(){
  94309. var x = this.x, y = this.y, z = this.z;
  94310. return OIMO.sqrt(x*x + y*y + z*z);
  94311. },*/
  94312. negate: function () {
  94313. this.x = -this.x;
  94314. this.y = -this.y;
  94315. this.z = -this.z;
  94316. return this;
  94317. },
  94318. dot: function (v) {
  94319. return this.x * v.x + this.y * v.y + this.z * v.z;
  94320. },
  94321. lengthSq: function () {
  94322. return this.x * this.x + this.y * this.y + this.z * this.z;
  94323. },
  94324. length: function () {
  94325. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  94326. },
  94327. /*len: function(){
  94328. var x = this.x, y = this.y, z = this.z;
  94329. return x*x + y*y + z*z;
  94330. },*/
  94331. copy: function (v) {
  94332. this.x = v.x;
  94333. this.y = v.y;
  94334. this.z = v.z;
  94335. return this;
  94336. },
  94337. applyQuaternion: function (q) {
  94338. var x = this.x;
  94339. var y = this.y;
  94340. var z = this.z;
  94341. var qx = q.x;
  94342. var qy = q.y;
  94343. var qz = q.z;
  94344. var qs = q.s;
  94345. // calculate quat * vector
  94346. var ix = qs * x + qy * z - qz * y;
  94347. var iy = qs * y + qz * x - qx * z;
  94348. var iz = qs * z + qx * y - qy * x;
  94349. var iw = -qx * x - qy * y - qz * z;
  94350. // calculate result * inverse quat
  94351. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  94352. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  94353. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  94354. return this;
  94355. },
  94356. testZero: function () {
  94357. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  94358. else return false;
  94359. },
  94360. testDiff: function (v) {
  94361. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  94362. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  94363. //else return false;
  94364. },
  94365. equals: function (v) {
  94366. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  94367. },
  94368. clone: function () {
  94369. return new this.constructor(this.x, this.y, this.z);
  94370. },
  94371. toString: function () {
  94372. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  94373. },
  94374. multiplyScalar: function (scalar) {
  94375. if (isFinite(scalar)) {
  94376. this.x *= scalar;
  94377. this.y *= scalar;
  94378. this.z *= scalar;
  94379. } else {
  94380. this.x = 0;
  94381. this.y = 0;
  94382. this.z = 0;
  94383. }
  94384. return this;
  94385. },
  94386. divideScalar: function (scalar) {
  94387. return this.multiplyScalar(1 / scalar);
  94388. },
  94389. // TODO rename to normalize
  94390. norm: function () {
  94391. return this.divideScalar(this.length());
  94392. },
  94393. }
  94394. OIMO.Euler = function (x, y, z, order) {
  94395. this._x = x || 0;
  94396. this._y = y || 0;
  94397. this._z = z || 0;
  94398. this._order = order || OIMO.Euler.DefaultOrder;
  94399. };
  94400. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  94401. OIMO.Euler.DefaultOrder = 'XYZ';
  94402. OIMO.clamp = function (x, a, b) {
  94403. return (x < a) ? a : ((x > b) ? b : x);
  94404. }
  94405. OIMO.Euler.prototype = {
  94406. constructor: OIMO.Euler,
  94407. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  94408. get x() {
  94409. return this._x;
  94410. },
  94411. set x(value) {
  94412. this._x = value;
  94413. this.onChangeCallback();
  94414. },
  94415. get y() {
  94416. return this._y;
  94417. },
  94418. set y(value) {
  94419. this._y = value;
  94420. this.onChangeCallback();
  94421. },
  94422. get z() {
  94423. return this._z;
  94424. },
  94425. set z(value) {
  94426. this._z = value;
  94427. this.onChangeCallback();
  94428. },
  94429. get order() {
  94430. return this._order;
  94431. },
  94432. set order(value) {
  94433. this._order = value;
  94434. this.onChangeCallback();
  94435. },
  94436. set: function (x, y, z, order) {
  94437. this._x = x;
  94438. this._y = y;
  94439. this._z = z;
  94440. this._order = order || this._order;
  94441. this.onChangeCallback();
  94442. return this;
  94443. },
  94444. copy: function (euler) {
  94445. this._x = euler._x;
  94446. this._y = euler._y;
  94447. this._z = euler._z;
  94448. this._order = euler._order;
  94449. this.onChangeCallback();
  94450. return this;
  94451. },
  94452. setFromRotationMatrix: function (m, order) {
  94453. var clamp = OIMO.clamp;
  94454. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  94455. var te = m.elements;
  94456. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  94457. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  94458. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  94459. var m11 = te[0], m12 = te[1], m13 = te[2],
  94460. m21 = te[3], m22 = te[4], m23 = te[5],
  94461. m31 = te[6], m32 = te[7], m33 = te[8];
  94462. order = order || this._order;
  94463. if (order === 'XYZ') {
  94464. this._y = OIMO.asin(clamp(m13, -1, 1));
  94465. if (OIMO.abs(m13) < 0.99999) {
  94466. this._x = OIMO.atan2(-m23, m33);
  94467. this._z = OIMO.atan2(-m12, m11);
  94468. } else {
  94469. this._x = OIMO.atan2(m32, m22);
  94470. this._z = 0;
  94471. }
  94472. } else if (order === 'YXZ') {
  94473. this._x = OIMO.asin(-clamp(m23, -1, 1));
  94474. if (OIMO.abs(m23) < 0.99999) {
  94475. this._y = OIMO.atan2(m13, m33);
  94476. this._z = OIMO.atan2(m21, m22);
  94477. } else {
  94478. this._y = OIMO.atan2(-m31, m11);
  94479. this._z = 0;
  94480. }
  94481. } else if (order === 'ZXY') {
  94482. this._x = OIMO.asin(clamp(m32, -1, 1));
  94483. if (OIMO.abs(m32) < 0.99999) {
  94484. this._y = OIMO.atan2(-m31, m33);
  94485. this._z = OIMO.atan2(-m12, m22);
  94486. } else {
  94487. this._y = 0;
  94488. this._z = OIMO.atan2(m21, m11);
  94489. }
  94490. } else if (order === 'ZYX') {
  94491. this._y = OIMO.asin(-clamp(m31, -1, 1));
  94492. if (OIMO.abs(m31) < 0.99999) {
  94493. this._x = OIMO.atan2(m32, m33);
  94494. this._z = OIMO.atan2(m21, m11);
  94495. } else {
  94496. this._x = 0;
  94497. this._z = OIMO.atan2(-m12, m22);
  94498. }
  94499. } else if (order === 'YZX') {
  94500. this._z = OIMO.asin(clamp(m21, -1, 1));
  94501. if (OIMO.abs(m21) < 0.99999) {
  94502. this._x = OIMO.atan2(-m23, m22);
  94503. this._y = OIMO.atan2(-m31, m11);
  94504. } else {
  94505. this._x = 0;
  94506. this._y = OIMO.atan2(m13, m33);
  94507. }
  94508. } else if (order === 'XZY') {
  94509. this._z = OIMO.asin(-clamp(m12, -1, 1));
  94510. if (OIMO.abs(m12) < 0.99999) {
  94511. this._x = OIMO.atan2(m32, m22);
  94512. this._y = OIMO.atan2(m13, m11);
  94513. } else {
  94514. this._x = OIMO.atan2(-m23, m33);
  94515. this._y = 0;
  94516. }
  94517. } else {
  94518. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  94519. }
  94520. this._order = order;
  94521. this.onChangeCallback();
  94522. return this;
  94523. },
  94524. setFromQuaternion: function (q, order, update) {
  94525. var clamp = OIMO.clamp;
  94526. // q is assumed to be normalized
  94527. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  94528. var sqx = q.x * q.x;
  94529. var sqy = q.y * q.y;
  94530. var sqz = q.z * q.z;
  94531. var sqw = q.s * q.s;
  94532. order = order || this._order;
  94533. if (order === 'XYZ') {
  94534. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  94535. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  94536. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  94537. } else if (order === 'YXZ') {
  94538. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  94539. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  94540. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  94541. } else if (order === 'ZXY') {
  94542. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  94543. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  94544. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  94545. } else if (order === 'ZYX') {
  94546. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  94547. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  94548. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  94549. } else if (order === 'YZX') {
  94550. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  94551. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  94552. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  94553. } else if (order === 'XZY') {
  94554. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  94555. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  94556. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  94557. } else {
  94558. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  94559. }
  94560. this._order = order;
  94561. if (update !== false) this.onChangeCallback();
  94562. return this;
  94563. },
  94564. reorder: function () {
  94565. // WARNING: this discards revolution information -bhouston
  94566. var q = new OIMO.Quat();
  94567. return function (newOrder) {
  94568. q.setFromEuler(this);
  94569. this.setFromQuaternion(q, newOrder);
  94570. };
  94571. }(),
  94572. equals: function (euler) {
  94573. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  94574. },
  94575. fromArray: function (array) {
  94576. this._x = array[0];
  94577. this._y = array[1];
  94578. this._z = array[2];
  94579. if (array[3] !== undefined) this._order = array[3];
  94580. this.onChangeCallback();
  94581. return this;
  94582. },
  94583. toArray: function () {
  94584. return [this._x, this._y, this._z, this._order];
  94585. },
  94586. onChange: function (callback) {
  94587. this.onChangeCallback = callback;
  94588. return this;
  94589. },
  94590. onChangeCallback: function () { },
  94591. clone: function () {
  94592. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  94593. }
  94594. };
  94595. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  94596. var c1 = OIMO.cos(oy * 0.5);//heading
  94597. var s1 = OIMO.sin(oy * 0.5);
  94598. var c2 = OIMO.cos(oz * 0.5);//altitude
  94599. var s2 = OIMO.sin(oz * 0.5);
  94600. var c3 = OIMO.cos(ox * 0.5);//bank
  94601. var s3 = OIMO.sin(ox * 0.5);
  94602. var c1c2 = c1 * c2;
  94603. var s1s2 = s1 * s2;
  94604. var w = c1c2 * c3 - s1s2 * s3;
  94605. var x = c1c2 * s3 + s1s2 * c3;
  94606. var y = s1 * c2 * c3 + c1 * s2 * s3;
  94607. var z = c1 * s2 * c3 - s1 * c2 * s3;
  94608. var angle = 2 * OIMO.acos(w);
  94609. var norm = x * x + y * y + z * z;
  94610. if (norm < 0.001) {
  94611. x = 1;
  94612. y = z = 0;
  94613. } else {
  94614. norm = OIMO.sqrt(norm);
  94615. x /= norm;
  94616. y /= norm;
  94617. z /= norm;
  94618. }
  94619. return [angle, x, y, z];
  94620. }
  94621. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  94622. var ch = OIMO.cos(oy);//heading
  94623. var sh = OIMO.sin(oy);
  94624. var ca = OIMO.cos(oz);//altitude
  94625. var sa = OIMO.sin(oz);
  94626. var cb = OIMO.cos(ox);//bank
  94627. var sb = OIMO.sin(ox);
  94628. var mtx = new OIMO.Mat33();
  94629. var te = mtx.elements;
  94630. te[0] = ch * ca;
  94631. te[1] = sh * sb - ch * sa * cb;
  94632. te[2] = ch * sa * sb + sh * cb;
  94633. te[3] = sa;
  94634. te[4] = ca * cb;
  94635. te[5] = -ca * sb;
  94636. te[6] = -sh * ca;
  94637. te[7] = sh * sa * cb + ch * sb;
  94638. te[8] = -sh * sa * sb + ch * cb;
  94639. return mtx;
  94640. }
  94641. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  94642. var te = mtx.elements;
  94643. var x, y, z;
  94644. if (te[3] > 0.998) { // singularity at north pole
  94645. y = OIMO.atan2(te[2], te[8]);
  94646. z = OIMO.PI / 2;
  94647. x = 0;
  94648. } else if (te[3] < -0.998) { // singularity at south pole
  94649. y = OIMO.atan2(te[2], te[8]);
  94650. z = -OIMO.PI / 2;
  94651. x = 0;
  94652. } else {
  94653. y = OIMO.atan2(-te[6], te[0]);
  94654. x = OIMO.atan2(-te[5], te[4]);
  94655. z = OIMO.asin(te[3]);
  94656. }
  94657. return [x, y, z];
  94658. }
  94659. OIMO.unwrapDegrees = function (r) {
  94660. r = r % 360;
  94661. if (r > 180) r -= 360;
  94662. if (r < -180) r += 360;
  94663. return r;
  94664. }
  94665. OIMO.unwrapRadian = function (r) {
  94666. r = r % OIMO.TwoPI;
  94667. if (r > OIMO.PI) r -= OIMO.TwoPI;
  94668. if (r < -OIMO.PI) r += OIMO.TwoPI;
  94669. return r;
  94670. }
  94671. OIMO.Distance3d = function (p1, p2) {
  94672. var xd = p2[0] - p1[0];
  94673. var yd = p2[1] - p1[1];
  94674. var zd = p2[2] - p1[2];
  94675. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  94676. }
  94677. /**
  94678. * The base class of all type of the constraints.
  94679. * @author saharan
  94680. */
  94681. OIMO.Constraint = function () {
  94682. // The parent world of the constraint.
  94683. this.parent = null;
  94684. // The first body of the constraint.
  94685. this.body1 = null;
  94686. // The second body of the constraint.
  94687. this.body2 = null;
  94688. // Internal
  94689. this.addedToIsland = false;
  94690. }
  94691. OIMO.Constraint.prototype = {
  94692. constructor: OIMO.Constraint,
  94693. /**
  94694. * Prepare for solving the constraint.
  94695. * @param timeStep
  94696. * @param invTimeStep
  94697. */
  94698. preSolve: function (timeStep, invTimeStep) {
  94699. OIMO.Error("Constraint", "Inheritance error.");
  94700. },
  94701. /**
  94702. * Solve the constraint.
  94703. * This is usually called iteratively.
  94704. */
  94705. solve: function () {
  94706. OIMO.Error("Constraint", "Inheritance error.");
  94707. },
  94708. /**
  94709. * Do the post-processing.
  94710. */
  94711. postSolve: function () {
  94712. OIMO.Error("Constraint", "Inheritance error.");
  94713. }
  94714. }
  94715. /**
  94716. * Joints are used to constrain the motion between two rigid bodies.
  94717. * @author saharan
  94718. * @author lo-th
  94719. */
  94720. OIMO.Joint = function (config) {
  94721. OIMO.Constraint.call(this);
  94722. // joint name
  94723. this.name = "";
  94724. // The type of the joint.
  94725. this.type = OIMO.JOINT_NULL;
  94726. // The previous joint in the world.
  94727. this.prev = null;
  94728. // The next joint in the world.
  94729. this.next = null;
  94730. this.body1 = config.body1;
  94731. this.body2 = config.body2;
  94732. // The anchor point on the first rigid body in local coordinate system.
  94733. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  94734. // The anchor point on the second rigid body in local coordinate system.
  94735. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  94736. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  94737. this.relativeAnchorPoint1 = new OIMO.Vec3();
  94738. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  94739. this.relativeAnchorPoint2 = new OIMO.Vec3();
  94740. // The anchor point on the first rigid body in world coordinate system.
  94741. this.anchorPoint1 = new OIMO.Vec3();
  94742. // The anchor point on the second rigid body in world coordinate system.
  94743. this.anchorPoint2 = new OIMO.Vec3();
  94744. // Whether allow collision between connected rigid bodies or not.
  94745. this.allowCollision = config.allowCollision;
  94746. this.b1Link = new OIMO.JointLink(this);
  94747. this.b2Link = new OIMO.JointLink(this);
  94748. this.matrix = new OIMO.Mat44();
  94749. };
  94750. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  94751. OIMO.Joint.prototype.constructor = OIMO.Joint;
  94752. // Update all the anchor points.
  94753. OIMO.Joint.prototype.updateAnchorPoints = function () {
  94754. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  94755. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  94756. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  94757. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  94758. };
  94759. // Attach the joint from the bodies.
  94760. OIMO.Joint.prototype.attach = function () {
  94761. this.b1Link.body = this.body2;
  94762. this.b2Link.body = this.body1;
  94763. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  94764. else this.b1Link.next = null;
  94765. this.body1.jointLink = this.b1Link;
  94766. this.body1.numJoints++;
  94767. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  94768. else this.b2Link.next = null;
  94769. this.body2.jointLink = this.b2Link;
  94770. this.body2.numJoints++;
  94771. };
  94772. // Detach the joint from the bodies.
  94773. OIMO.Joint.prototype.detach = function () {
  94774. var prev = this.b1Link.prev;
  94775. var next = this.b1Link.next;
  94776. if (prev != null) prev.next = next;
  94777. if (next != null) next.prev = prev;
  94778. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  94779. this.b1Link.prev = null;
  94780. this.b1Link.next = null;
  94781. this.b1Link.body = null;
  94782. this.body1.numJoints--;
  94783. prev = this.b2Link.prev;
  94784. next = this.b2Link.next;
  94785. if (prev != null) prev.next = next;
  94786. if (next != null) next.prev = prev;
  94787. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  94788. this.b2Link.prev = null;
  94789. this.b2Link.next = null;
  94790. this.b2Link.body = null;
  94791. this.body2.numJoints--;
  94792. this.b1Link.body = null;
  94793. this.b2Link.body = null;
  94794. };
  94795. // Awake the bodies.
  94796. OIMO.Joint.prototype.awake = function () {
  94797. this.body1.awake();
  94798. this.body2.awake();
  94799. };
  94800. // calculation function
  94801. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  94802. };
  94803. OIMO.Joint.prototype.solve = function () {
  94804. };
  94805. OIMO.Joint.prototype.postSolve = function () {
  94806. };
  94807. // Delete process
  94808. OIMO.Joint.prototype.remove = function () {
  94809. this.dispose();
  94810. };
  94811. OIMO.Joint.prototype.dispose = function () {
  94812. this.parent.removeJoint(this);
  94813. };
  94814. // Three js add
  94815. OIMO.Joint.prototype.getPosition = function () {
  94816. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  94817. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  94818. return [p1, p2];
  94819. };
  94820. OIMO.Joint.prototype.getMatrix = function () {
  94821. var m = this.matrix.elements;
  94822. var p1 = this.anchorPoint1;
  94823. var p2 = this.anchorPoint2;
  94824. m[0] = p1.x * OIMO.WORLD_SCALE;
  94825. m[1] = p1.y * OIMO.WORLD_SCALE;
  94826. m[2] = p1.z * OIMO.WORLD_SCALE;
  94827. m[3] = 0;
  94828. m[4] = p2.x * OIMO.WORLD_SCALE;
  94829. m[5] = p2.y * OIMO.WORLD_SCALE;
  94830. m[6] = p2.z * OIMO.WORLD_SCALE;
  94831. m[7] = 0;
  94832. return m;
  94833. };
  94834. /**
  94835. * A joint configuration holds all configuration data for constructing a joint.
  94836. * Joint configurations can be reused safely.
  94837. * @author saharan
  94838. */
  94839. OIMO.JointConfig = function () {
  94840. // The first rigid body of the joint.
  94841. this.body1 = null;
  94842. // The second rigid body of the joint.
  94843. this.body2 = null;
  94844. // The anchor point on the first rigid body in local coordinate system.
  94845. this.localAnchorPoint1 = new OIMO.Vec3();
  94846. // The anchor point on the second rigid body in local coordinate system.
  94847. this.localAnchorPoint2 = new OIMO.Vec3();
  94848. // The axis in the first body's coordinate system.
  94849. // his property is available in some joints.
  94850. this.localAxis1 = new OIMO.Vec3();
  94851. // The axis in the second body's coordinate system.
  94852. // This property is available in some joints.
  94853. this.localAxis2 = new OIMO.Vec3();
  94854. // Whether allow collision between connected rigid bodies or not.
  94855. this.allowCollision = false;
  94856. };
  94857. /**
  94858. * A link list of joints.
  94859. * @author saharan
  94860. */
  94861. OIMO.JointLink = function (joint) {
  94862. // The previous joint link.
  94863. this.prev = null;
  94864. // The next joint link.
  94865. this.next = null;
  94866. // The other rigid body connected to the joint.
  94867. this.body = null;
  94868. // The joint of the link.
  94869. this.joint = joint;
  94870. };
  94871. /**
  94872. * An information of limit and motor.
  94873. * @author saharan
  94874. */
  94875. OIMO.LimitMotor = function (axis, fixed) {
  94876. fixed = fixed || false;
  94877. // The axis of the constraint.
  94878. this.axis = axis;
  94879. // The current angle for rotational constraints.
  94880. this.angle = 0;
  94881. // The lower limit. Set lower > upper to disable
  94882. this.lowerLimit = fixed ? 0 : 1;
  94883. //if(fixed)this.lowerLimit = 0;
  94884. //else this.lowerLimit = 1;
  94885. // The upper limit. Set lower > upper to disable.
  94886. this.upperLimit = 0;
  94887. // The target motor speed.
  94888. this.motorSpeed = 0;
  94889. // The maximum motor force or torque. Set 0 to disable.
  94890. this.maxMotorForce = 0;
  94891. // The frequency of the spring. Set 0 to disable.
  94892. this.frequency = 0;
  94893. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  94894. this.dampingRatio = 0;
  94895. };
  94896. OIMO.LimitMotor.prototype = {
  94897. constructor: OIMO.LimitMotor,
  94898. /**
  94899. * Set limit data into this constraint.
  94900. * @param lowerLimit
  94901. * @param upperLimit
  94902. */
  94903. setLimit: function (lowerLimit, upperLimit) {
  94904. this.lowerLimit = lowerLimit;
  94905. this.upperLimit = upperLimit;
  94906. },
  94907. /**
  94908. * Set motor data into this constraint.
  94909. * @param motorSpeed
  94910. * @param maxMotorForce
  94911. */
  94912. setMotor: function (motorSpeed, maxMotorForce) {
  94913. this.motorSpeed = motorSpeed;
  94914. this.maxMotorForce = maxMotorForce;
  94915. },
  94916. /**
  94917. * Set spring data into this constraint.
  94918. * @param frequency
  94919. * @param dampingRatio
  94920. */
  94921. setSpring: function (frequency, dampingRatio) {
  94922. this.frequency = frequency;
  94923. this.dampingRatio = dampingRatio;
  94924. }
  94925. };
  94926. /**
  94927. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  94928. * @author saharan
  94929. * @author lo-th
  94930. */
  94931. OIMO.BallAndSocketJoint = function (config) {
  94932. OIMO.Joint.call(this, config);
  94933. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  94934. this.lc = new OIMO.LinearConstraint(this);
  94935. };
  94936. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  94937. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  94938. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94939. this.updateAnchorPoints();
  94940. this.lc.preSolve(timeStep, invTimeStep);
  94941. };
  94942. OIMO.BallAndSocketJoint.prototype.solve = function () {
  94943. this.lc.solve();
  94944. };
  94945. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  94946. };
  94947. /**
  94948. * A distance joint limits the distance between two anchor points on rigid bodies.
  94949. * @author saharan
  94950. * @author lo-th
  94951. */
  94952. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  94953. OIMO.Joint.call(this, config);
  94954. this.type = OIMO.JOINT_DISTANCE;
  94955. this.normal = new OIMO.Vec3();
  94956. this.nr = new OIMO.Vec3();
  94957. // The limit and motor information of the joint.
  94958. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  94959. this.limitMotor.lowerLimit = minDistance;
  94960. this.limitMotor.upperLimit = maxDistance;
  94961. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  94962. };
  94963. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  94964. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  94965. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  94966. this.updateAnchorPoints();
  94967. //var nr = this.nr;
  94968. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  94969. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  94970. //if(len>0) len = 1/len;
  94971. //this.normal.scale( nr, len );
  94972. this.normal.normalize(this.nr);
  94973. this.t.preSolve(timeStep, invTimeStep);
  94974. };
  94975. OIMO.DistanceJoint.prototype.solve = function () {
  94976. this.t.solve();
  94977. };
  94978. OIMO.DistanceJoint.prototype.postSolve = function () {
  94979. };
  94980. /**
  94981. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  94982. * @author saharan
  94983. * @author lo-th
  94984. */
  94985. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  94986. OIMO.Joint.call(this, config);
  94987. this.type = OIMO.JOINT_HINGE;
  94988. // The axis in the first body's coordinate system.
  94989. this.localAxis1 = config.localAxis1.clone().norm();
  94990. // The axis in the second body's coordinate system.
  94991. this.localAxis2 = config.localAxis2.clone().norm();
  94992. // make angle axis 1
  94993. this.localAngle1 = new OIMO.Vec3(
  94994. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  94995. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  94996. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  94997. ).norm();
  94998. // make angle axis 2
  94999. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95000. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  95001. this.nor = new OIMO.Vec3();
  95002. this.tan = new OIMO.Vec3();
  95003. this.bin = new OIMO.Vec3();
  95004. this.ax1 = new OIMO.Vec3();
  95005. this.ax2 = new OIMO.Vec3();
  95006. this.an1 = new OIMO.Vec3();
  95007. this.an2 = new OIMO.Vec3();
  95008. // The rotational limit and motor information of the joint.
  95009. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  95010. this.limitMotor.lowerLimit = lowerAngleLimit;
  95011. this.limitMotor.upperLimit = upperAngleLimit;
  95012. this.lc = new OIMO.LinearConstraint(this);
  95013. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95014. };
  95015. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  95016. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  95017. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95018. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  95019. this.updateAnchorPoints();
  95020. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  95021. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  95022. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  95023. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  95024. this.nor.set(
  95025. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  95026. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  95027. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  95028. ).norm();
  95029. this.tan.set(
  95030. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  95031. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  95032. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  95033. ).norm();
  95034. this.bin.set(
  95035. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  95036. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  95037. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  95038. );
  95039. // calculate hinge angle
  95040. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  95041. if (
  95042. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  95043. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  95044. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  95045. ) {
  95046. this.limitMotor.angle = -limite;
  95047. } else {
  95048. this.limitMotor.angle = limite;
  95049. }
  95050. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  95051. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  95052. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  95053. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  95054. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  95055. this.r3.preSolve(timeStep, invTimeStep);
  95056. this.lc.preSolve(timeStep, invTimeStep);
  95057. };
  95058. OIMO.HingeJoint.prototype.solve = function () {
  95059. this.r3.solve();
  95060. this.lc.solve();
  95061. };
  95062. OIMO.HingeJoint.prototype.postSolve = function () {
  95063. };
  95064. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  95065. if (cos > 1) return 0;
  95066. else if (cos < -1) return OIMO.PI;
  95067. else return OIMO.acos(cos);
  95068. };
  95069. /**
  95070. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  95071. * @author saharan
  95072. * @author lo-th
  95073. */
  95074. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  95075. OIMO.Joint.call(this, config);
  95076. this.type = OIMO.JOINT_PRISMATIC;
  95077. // The axis in the first body's coordinate system.
  95078. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95079. // The axis in the second body's coordinate system.
  95080. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95081. this.localAxis1X = this.localAxis1.x;
  95082. this.localAxis1Y = this.localAxis1.y;
  95083. this.localAxis1Z = this.localAxis1.z;
  95084. this.localAxis2X = this.localAxis2.x;
  95085. this.localAxis2Y = this.localAxis2.y;
  95086. this.localAxis2Z = this.localAxis2.z;
  95087. this.nor = new OIMO.Vec3();
  95088. this.tan = new OIMO.Vec3();
  95089. this.bin = new OIMO.Vec3();
  95090. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95091. // The translational limit and motor information of the joint.
  95092. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  95093. this.limitMotor.lowerLimit = lowerTranslation;
  95094. this.limitMotor.upperLimit = upperTranslation;
  95095. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95096. };
  95097. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  95098. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  95099. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95100. var tmpM;
  95101. var tmp1X;
  95102. var tmp1Y;
  95103. var tmp1Z;
  95104. this.updateAnchorPoints();
  95105. tmpM = this.body1.rotation.elements;
  95106. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95107. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95108. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95109. tmpM = this.body2.rotation.elements;
  95110. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95111. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95112. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95113. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  95114. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  95115. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  95116. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95117. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95118. nx *= tmp1X;
  95119. ny *= tmp1X;
  95120. nz *= tmp1X;
  95121. var tx = ny * nx - nz * nz;
  95122. var ty = -nz * ny - nx * nx;
  95123. var tz = nx * nz + ny * ny;
  95124. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95125. tx *= tmp1X;
  95126. ty *= tmp1X;
  95127. tz *= tmp1X;
  95128. var bx = ny * tz - nz * ty;
  95129. var by = nz * tx - nx * tz;
  95130. var bz = nx * ty - ny * tx;
  95131. this.nor.init(nx, ny, nz);
  95132. this.tan.init(tx, ty, tz);
  95133. this.bin.init(bx, by, bz);
  95134. this.ac.preSolve(timeStep, invTimeStep);
  95135. this.t3.preSolve(timeStep, invTimeStep);
  95136. };
  95137. OIMO.PrismaticJoint.prototype.solve = function () {
  95138. this.ac.solve();
  95139. this.t3.solve();
  95140. };
  95141. OIMO.PrismaticJoint.prototype.postSolve = function () {
  95142. };
  95143. /**
  95144. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  95145. * @author saharan
  95146. * @author lo-th
  95147. */
  95148. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  95149. OIMO.Joint.call(this, config);
  95150. this.type = OIMO.JOINT_SLIDER;
  95151. // The first axis in local coordinate system.
  95152. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95153. // The second axis in local coordinate system.
  95154. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95155. var len;
  95156. this.localAxis1X = this.localAxis1.x;
  95157. this.localAxis1Y = this.localAxis1.y;
  95158. this.localAxis1Z = this.localAxis1.z;
  95159. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  95160. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  95161. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  95162. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95163. this.localAngAxis1X *= len;
  95164. this.localAngAxis1Y *= len;
  95165. this.localAngAxis1Z *= len;
  95166. this.localAxis2X = this.localAxis2.x;
  95167. this.localAxis2Y = this.localAxis2.y;
  95168. this.localAxis2Z = this.localAxis2.z;
  95169. // make angle axis 2
  95170. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95171. var tarc = arc.elements;
  95172. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  95173. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  95174. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  95175. this.nor = new OIMO.Vec3();
  95176. this.tan = new OIMO.Vec3();
  95177. this.bin = new OIMO.Vec3();
  95178. // The limit and motor for the rotation
  95179. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  95180. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95181. // The limit and motor for the translation.
  95182. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  95183. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  95184. this.translationalLimitMotor.upperLimit = upperTranslation;
  95185. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95186. };
  95187. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  95188. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  95189. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95190. var tmpM;
  95191. var tmp1X;
  95192. var tmp1Y;
  95193. var tmp1Z;
  95194. this.updateAnchorPoints();
  95195. tmpM = this.body1.rotation.elements;
  95196. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95197. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95198. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95199. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  95200. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  95201. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  95202. tmpM = this.body2.rotation.elements;
  95203. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95204. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95205. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95206. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  95207. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  95208. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  95209. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  95210. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  95211. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  95212. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95213. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95214. nx *= tmp1X;
  95215. ny *= tmp1X;
  95216. nz *= tmp1X;
  95217. var tx = ny * nx - nz * nz;
  95218. var ty = -nz * ny - nx * nx;
  95219. var tz = nx * nz + ny * ny;
  95220. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95221. tx *= tmp1X;
  95222. ty *= tmp1X;
  95223. tz *= tmp1X;
  95224. var bx = ny * tz - nz * ty;
  95225. var by = nz * tx - nx * tz;
  95226. var bz = nx * ty - ny * tx;
  95227. this.nor.init(nx, ny, nz);
  95228. this.tan.init(tx, ty, tz);
  95229. this.bin.init(bx, by, bz);
  95230. // ----------------------------------------------
  95231. // calculate hinge angle
  95232. // ----------------------------------------------
  95233. if (
  95234. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  95235. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  95236. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  95237. ) {
  95238. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  95239. } else {
  95240. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  95241. }
  95242. // angular error
  95243. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  95244. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  95245. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  95246. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  95247. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  95248. this.r3.preSolve(timeStep, invTimeStep);
  95249. this.t3.preSolve(timeStep, invTimeStep);
  95250. };
  95251. OIMO.SliderJoint.prototype.solve = function () {
  95252. this.r3.solve();
  95253. this.t3.solve();
  95254. };
  95255. OIMO.SliderJoint.prototype.postSolve = function () {
  95256. };
  95257. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  95258. if (cos > 1) return 0;
  95259. else if (cos < -1) return OIMO.PI;
  95260. else return OIMO.acos(cos);
  95261. };
  95262. /**
  95263. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  95264. * The wheel joint also allows for relative translation for the suspension.
  95265. * @author saharan
  95266. * @author lo-th
  95267. */
  95268. OIMO.WheelJoint = function (config) {
  95269. OIMO.Joint.call(this, config);
  95270. this.type = OIMO.JOINT_WHEEL;
  95271. // The first axis in local coordinate system.
  95272. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95273. // The second axis in local coordinate system.
  95274. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95275. var len;
  95276. this.localAxis1X = this.localAxis1.x;
  95277. this.localAxis1Y = this.localAxis1.y;
  95278. this.localAxis1Z = this.localAxis1.z;
  95279. this.localAxis2X = this.localAxis2.x;
  95280. this.localAxis2Y = this.localAxis2.y;
  95281. this.localAxis2Z = this.localAxis2.z;
  95282. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  95283. if (dot > -1 && dot < 1) {
  95284. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  95285. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  95286. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  95287. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  95288. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  95289. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  95290. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95291. this.localAngAxis1X *= len;
  95292. this.localAngAxis1Y *= len;
  95293. this.localAngAxis1Z *= len;
  95294. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  95295. this.localAngAxis2X *= len;
  95296. this.localAngAxis2Y *= len;
  95297. this.localAngAxis2Z *= len;
  95298. } else {
  95299. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  95300. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  95301. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  95302. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95303. this.localAngAxis1X *= len;
  95304. this.localAngAxis1Y *= len;
  95305. this.localAngAxis1Z *= len;
  95306. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95307. var tarc = arc.elements;
  95308. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  95309. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  95310. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  95311. }
  95312. this.nor = new OIMO.Vec3();
  95313. this.tan = new OIMO.Vec3();
  95314. this.bin = new OIMO.Vec3();
  95315. // The translational limit and motor information of the joint.
  95316. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  95317. this.translationalLimitMotor.frequency = 8;
  95318. this.translationalLimitMotor.dampingRatio = 1;
  95319. // The first rotational limit and motor information of the joint.
  95320. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  95321. // The second rotational limit and motor information of the joint.
  95322. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  95323. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  95324. this.t3.weight = 1;
  95325. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  95326. };
  95327. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  95328. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  95329. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95330. var tmpM;
  95331. var tmp1X;
  95332. var tmp1Y;
  95333. var tmp1Z;
  95334. this.updateAnchorPoints();
  95335. tmpM = this.body1.rotation.elements;
  95336. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95337. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95338. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95339. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  95340. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  95341. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  95342. tmpM = this.body2.rotation.elements;
  95343. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95344. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95345. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95346. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  95347. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  95348. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  95349. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  95350. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  95351. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  95352. } else {
  95353. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  95354. }
  95355. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  95356. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  95357. } else {
  95358. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  95359. }
  95360. var nx = y2 * z1 - z2 * y1;
  95361. var ny = z2 * x1 - x2 * z1;
  95362. var nz = x2 * y1 - y2 * x1;
  95363. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95364. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95365. nx *= tmp1X;
  95366. ny *= tmp1X;
  95367. nz *= tmp1X;
  95368. var tx = ny * z2 - nz * y2;
  95369. var ty = nz * x2 - nx * z2;
  95370. var tz = nx * y2 - ny * x2;
  95371. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95372. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95373. tx *= tmp1X;
  95374. ty *= tmp1X;
  95375. tz *= tmp1X;
  95376. var bx = y1 * nz - z1 * ny;
  95377. var by = z1 * nx - x1 * nz;
  95378. var bz = x1 * ny - y1 * nx;
  95379. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  95380. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95381. bx *= tmp1X;
  95382. by *= tmp1X;
  95383. bz *= tmp1X;
  95384. this.nor.init(nx, ny, nz);
  95385. this.tan.init(tx, ty, tz);
  95386. this.bin.init(bx, by, bz);
  95387. this.r3.preSolve(timeStep, invTimeStep);
  95388. this.t3.preSolve(timeStep, invTimeStep);
  95389. };
  95390. OIMO.WheelJoint.prototype.solve = function () {
  95391. this.r3.solve();
  95392. this.t3.solve();
  95393. };
  95394. OIMO.WheelJoint.prototype.postSolve = function () {
  95395. };
  95396. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  95397. if (cos > 1) return 0;
  95398. else if (cos < -1) return OIMO.PI;
  95399. else return OIMO.acos(cos);
  95400. };
  95401. /**
  95402. * An angular constraint for all axes for various joints.
  95403. * @author saharan
  95404. */
  95405. OIMO.AngularConstraint = function (joint, targetOrientation) {
  95406. this.joint = joint;
  95407. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  95408. this.relativeOrientation = new OIMO.Quat();
  95409. this.ii1 = null;
  95410. this.ii2 = null;
  95411. this.dd = null;
  95412. this.vel = new OIMO.Vec3();
  95413. this.imp = new OIMO.Vec3();
  95414. this.rn0 = new OIMO.Vec3();
  95415. this.rn1 = new OIMO.Vec3();
  95416. this.rn2 = new OIMO.Vec3();
  95417. this.b1 = joint.body1;
  95418. this.b2 = joint.body2;
  95419. this.a1 = this.b1.angularVelocity;
  95420. this.a2 = this.b2.angularVelocity;
  95421. this.i1 = this.b1.inverseInertia;
  95422. this.i2 = this.b2.inverseInertia;
  95423. };
  95424. OIMO.AngularConstraint.prototype = {
  95425. constructor: OIMO.AngularConstraint,
  95426. preSolve: function (timeStep, invTimeStep) {
  95427. var inv, len, v, vv;
  95428. this.ii1 = this.i1.clone();
  95429. this.ii2 = this.i2.clone();
  95430. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  95431. 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]));
  95432. this.dd = new OIMO.Mat33(
  95433. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  95434. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  95435. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  95436. ).multiply(inv);
  95437. this.relativeOrientation.invert(this.b1.orientation);
  95438. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  95439. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  95440. inv = this.relativeOrientation.s * 2;
  95441. this.vel.scale(this.relativeOrientation, inv);
  95442. len = this.vel.length();
  95443. if (len > 0.02) {
  95444. len = (0.02 - len) / len * invTimeStep * 0.05;
  95445. this.vel.scaleEqual(len);
  95446. } else {
  95447. this.vel.init();
  95448. }
  95449. this.rn1.mulMat(this.ii1, this.imp);
  95450. this.rn2.mulMat(this.ii2, this.imp);
  95451. this.a1.addEqual(this.rn1);
  95452. this.a2.subEqual(this.rn2);
  95453. },
  95454. solve: function () {
  95455. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  95456. this.rn0.mulMat(this.dd, r);
  95457. this.rn1.mulMat(this.ii1, this.rn0);
  95458. this.rn2.mulMat(this.ii2, this.rn0);
  95459. this.imp.addEqual(this.rn0);
  95460. this.a1.addEqual(this.rn1);
  95461. this.a2.subEqual(this.rn2);
  95462. }
  95463. };
  95464. /**
  95465. * A linear constraint for all axes for various joints.
  95466. * @author saharan
  95467. */
  95468. OIMO.LinearConstraint = function (joint) {
  95469. this.m1 = NaN;
  95470. this.m2 = NaN;
  95471. this.ii1 = null;
  95472. this.ii2 = null;
  95473. this.dd = null;
  95474. this.r1x = NaN;
  95475. this.r1y = NaN;
  95476. this.r1z = NaN;
  95477. this.r2x = NaN;
  95478. this.r2y = NaN;
  95479. this.r2z = NaN;
  95480. this.ax1x = NaN;
  95481. this.ax1y = NaN;
  95482. this.ax1z = NaN;
  95483. this.ay1x = NaN;
  95484. this.ay1y = NaN;
  95485. this.ay1z = NaN;
  95486. this.az1x = NaN;
  95487. this.az1y = NaN;
  95488. this.az1z = NaN;
  95489. this.ax2x = NaN;
  95490. this.ax2y = NaN;
  95491. this.ax2z = NaN;
  95492. this.ay2x = NaN;
  95493. this.ay2y = NaN;
  95494. this.ay2z = NaN;
  95495. this.az2x = NaN;
  95496. this.az2y = NaN;
  95497. this.az2z = NaN;
  95498. this.vel = NaN;
  95499. this.velx = NaN;
  95500. this.vely = NaN;
  95501. this.velz = NaN;
  95502. this.joint = joint;
  95503. this.r1 = joint.relativeAnchorPoint1;
  95504. this.r2 = joint.relativeAnchorPoint2;
  95505. this.p1 = joint.anchorPoint1;
  95506. this.p2 = joint.anchorPoint2;
  95507. this.b1 = joint.body1;
  95508. this.b2 = joint.body2;
  95509. this.l1 = this.b1.linearVelocity;
  95510. this.l2 = this.b2.linearVelocity;
  95511. this.a1 = this.b1.angularVelocity;
  95512. this.a2 = this.b2.angularVelocity;
  95513. this.i1 = this.b1.inverseInertia;
  95514. this.i2 = this.b2.inverseInertia;
  95515. this.impx = 0;
  95516. this.impy = 0;
  95517. this.impz = 0;
  95518. }
  95519. OIMO.LinearConstraint.prototype = {
  95520. constructor: OIMO.LinearConstraint,
  95521. preSolve: function (timeStep, invTimeStep) {
  95522. this.r1x = this.r1.x;
  95523. this.r1y = this.r1.y;
  95524. this.r1z = this.r1.z;
  95525. this.r2x = this.r2.x;
  95526. this.r2y = this.r2.y;
  95527. this.r2z = this.r2.z;
  95528. this.m1 = this.b1.inverseMass;
  95529. this.m2 = this.b2.inverseMass;
  95530. this.ii1 = this.i1.clone();
  95531. this.ii2 = this.i2.clone();
  95532. var ii1 = this.ii1.elements;
  95533. var ii2 = this.ii2.elements;
  95534. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  95535. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  95536. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  95537. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  95538. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  95539. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  95540. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  95541. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  95542. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  95543. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  95544. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  95545. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  95546. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  95547. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  95548. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  95549. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  95550. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  95551. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  95552. // calculate point-to-point mass matrix
  95553. // from impulse equation
  95554. //
  95555. // M = ([/m] - [r^][/I][r^]) ^ -1
  95556. //
  95557. // where
  95558. //
  95559. // [/m] = |1/m, 0, 0|
  95560. // |0, 1/m, 0|
  95561. // |0, 0, 1/m|
  95562. //
  95563. // [r^] = |0, -rz, ry|
  95564. // |rz, 0, -rx|
  95565. // |-ry, rx, 0|
  95566. //
  95567. // [/I] = Inverted moment inertia
  95568. var rxx = this.m1 + this.m2;
  95569. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  95570. var k = kk.elements;
  95571. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  95572. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  95573. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  95574. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  95575. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  95576. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  95577. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  95578. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  95579. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  95580. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  95581. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  95582. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  95583. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  95584. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  95585. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  95586. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  95587. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  95588. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  95589. 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]));
  95590. this.dd = new OIMO.Mat33(
  95591. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  95592. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  95593. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  95594. ).multiply(inv);
  95595. this.velx = this.p2.x - this.p1.x;
  95596. this.vely = this.p2.y - this.p1.y;
  95597. this.velz = this.p2.z - this.p1.z;
  95598. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  95599. if (len > 0.005) {
  95600. len = (0.005 - len) / len * invTimeStep * 0.05;
  95601. this.velx *= len;
  95602. this.vely *= len;
  95603. this.velz *= len;
  95604. } else {
  95605. this.velx = 0;
  95606. this.vely = 0;
  95607. this.velz = 0;
  95608. }
  95609. this.impx *= 0.95;
  95610. this.impy *= 0.95;
  95611. this.impz *= 0.95;
  95612. this.l1.x += this.impx * this.m1;
  95613. this.l1.y += this.impy * this.m1;
  95614. this.l1.z += this.impz * this.m1;
  95615. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  95616. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  95617. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  95618. this.l2.x -= this.impx * this.m2;
  95619. this.l2.y -= this.impy * this.m2;
  95620. this.l2.z -= this.impz * this.m2;
  95621. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  95622. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  95623. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  95624. },
  95625. solve: function () {
  95626. var d = this.dd.elements;
  95627. 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;
  95628. 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;
  95629. 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;
  95630. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  95631. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  95632. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  95633. this.impx += nimpx;
  95634. this.impy += nimpy;
  95635. this.impz += nimpz;
  95636. this.l1.x += nimpx * this.m1;
  95637. this.l1.y += nimpy * this.m1;
  95638. this.l1.z += nimpz * this.m1;
  95639. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  95640. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  95641. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  95642. this.l2.x -= nimpx * this.m2;
  95643. this.l2.y -= nimpy * this.m2;
  95644. this.l2.z -= nimpz * this.m2;
  95645. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  95646. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  95647. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  95648. }
  95649. }
  95650. /**
  95651. * A three-axis rotational constraint for various joints.
  95652. * @author saharan
  95653. */
  95654. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  95655. this.cfm1 = NaN;
  95656. this.cfm2 = NaN;
  95657. this.cfm3 = NaN;
  95658. this.i1e00 = NaN;
  95659. this.i1e01 = NaN;
  95660. this.i1e02 = NaN;
  95661. this.i1e10 = NaN;
  95662. this.i1e11 = NaN;
  95663. this.i1e12 = NaN;
  95664. this.i1e20 = NaN;
  95665. this.i1e21 = NaN;
  95666. this.i1e22 = NaN;
  95667. this.i2e00 = NaN;
  95668. this.i2e01 = NaN;
  95669. this.i2e02 = NaN;
  95670. this.i2e10 = NaN;
  95671. this.i2e11 = NaN;
  95672. this.i2e12 = NaN;
  95673. this.i2e20 = NaN;
  95674. this.i2e21 = NaN;
  95675. this.i2e22 = NaN;
  95676. this.ax1 = NaN;
  95677. this.ay1 = NaN;
  95678. this.az1 = NaN;
  95679. this.ax2 = NaN;
  95680. this.ay2 = NaN;
  95681. this.az2 = NaN;
  95682. this.ax3 = NaN;
  95683. this.ay3 = NaN;
  95684. this.az3 = NaN;
  95685. this.a1x1 = NaN; // jacoians
  95686. this.a1y1 = NaN;
  95687. this.a1z1 = NaN;
  95688. this.a2x1 = NaN;
  95689. this.a2y1 = NaN;
  95690. this.a2z1 = NaN;
  95691. this.a1x2 = NaN;
  95692. this.a1y2 = NaN;
  95693. this.a1z2 = NaN;
  95694. this.a2x2 = NaN;
  95695. this.a2y2 = NaN;
  95696. this.a2z2 = NaN;
  95697. this.a1x3 = NaN;
  95698. this.a1y3 = NaN;
  95699. this.a1z3 = NaN;
  95700. this.a2x3 = NaN;
  95701. this.a2y3 = NaN;
  95702. this.a2z3 = NaN;
  95703. this.lowerLimit1 = NaN;
  95704. this.upperLimit1 = NaN;
  95705. this.limitVelocity1 = NaN;
  95706. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95707. this.enableMotor1 = false;
  95708. this.motorSpeed1 = NaN;
  95709. this.maxMotorForce1 = NaN;
  95710. this.maxMotorImpulse1 = NaN;
  95711. this.lowerLimit2 = NaN;
  95712. this.upperLimit2 = NaN;
  95713. this.limitVelocity2 = NaN;
  95714. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95715. this.enableMotor2 = false;
  95716. this.motorSpeed2 = NaN;
  95717. this.maxMotorForce2 = NaN;
  95718. this.maxMotorImpulse2 = NaN;
  95719. this.lowerLimit3 = NaN;
  95720. this.upperLimit3 = NaN;
  95721. this.limitVelocity3 = NaN;
  95722. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95723. this.enableMotor3 = false;
  95724. this.motorSpeed3 = NaN;
  95725. this.maxMotorForce3 = NaN;
  95726. this.maxMotorImpulse3 = NaN;
  95727. this.k00 = NaN; // K = J*M*JT
  95728. this.k01 = NaN;
  95729. this.k02 = NaN;
  95730. this.k10 = NaN;
  95731. this.k11 = NaN;
  95732. this.k12 = NaN;
  95733. this.k20 = NaN;
  95734. this.k21 = NaN;
  95735. this.k22 = NaN;
  95736. this.kv00 = NaN; // diagonals without CFMs
  95737. this.kv11 = NaN;
  95738. this.kv22 = NaN;
  95739. this.dv00 = NaN; // ...inverted
  95740. this.dv11 = NaN;
  95741. this.dv22 = NaN;
  95742. this.d00 = NaN; // K^-1
  95743. this.d01 = NaN;
  95744. this.d02 = NaN;
  95745. this.d10 = NaN;
  95746. this.d11 = NaN;
  95747. this.d12 = NaN;
  95748. this.d20 = NaN;
  95749. this.d21 = NaN;
  95750. this.d22 = NaN;
  95751. this.limitMotor1 = limitMotor1;
  95752. this.limitMotor2 = limitMotor2;
  95753. this.limitMotor3 = limitMotor3;
  95754. this.b1 = joint.body1;
  95755. this.b2 = joint.body2;
  95756. this.a1 = this.b1.angularVelocity;
  95757. this.a2 = this.b2.angularVelocity;
  95758. this.i1 = this.b1.inverseInertia;
  95759. this.i2 = this.b2.inverseInertia;
  95760. this.limitImpulse1 = 0;
  95761. this.motorImpulse1 = 0;
  95762. this.limitImpulse2 = 0;
  95763. this.motorImpulse2 = 0;
  95764. this.limitImpulse3 = 0;
  95765. this.motorImpulse3 = 0;
  95766. }
  95767. OIMO.Rotational3Constraint.prototype = {
  95768. constructor: OIMO.Rotational3Constraint,
  95769. preSolve: function (timeStep, invTimeStep) {
  95770. this.ax1 = this.limitMotor1.axis.x;
  95771. this.ay1 = this.limitMotor1.axis.y;
  95772. this.az1 = this.limitMotor1.axis.z;
  95773. this.ax2 = this.limitMotor2.axis.x;
  95774. this.ay2 = this.limitMotor2.axis.y;
  95775. this.az2 = this.limitMotor2.axis.z;
  95776. this.ax3 = this.limitMotor3.axis.x;
  95777. this.ay3 = this.limitMotor3.axis.y;
  95778. this.az3 = this.limitMotor3.axis.z;
  95779. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  95780. this.upperLimit1 = this.limitMotor1.upperLimit;
  95781. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  95782. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  95783. this.enableMotor1 = this.maxMotorForce1 > 0;
  95784. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  95785. this.upperLimit2 = this.limitMotor2.upperLimit;
  95786. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  95787. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  95788. this.enableMotor2 = this.maxMotorForce2 > 0;
  95789. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  95790. this.upperLimit3 = this.limitMotor3.upperLimit;
  95791. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  95792. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  95793. this.enableMotor3 = this.maxMotorForce3 > 0;
  95794. var ti1 = this.i1.elements;
  95795. var ti2 = this.i2.elements;
  95796. this.i1e00 = ti1[0];
  95797. this.i1e01 = ti1[1];
  95798. this.i1e02 = ti1[2];
  95799. this.i1e10 = ti1[3];
  95800. this.i1e11 = ti1[4];
  95801. this.i1e12 = ti1[5];
  95802. this.i1e20 = ti1[6];
  95803. this.i1e21 = ti1[7];
  95804. this.i1e22 = ti1[8];
  95805. this.i2e00 = ti2[0];
  95806. this.i2e01 = ti2[1];
  95807. this.i2e02 = ti2[2];
  95808. this.i2e10 = ti2[3];
  95809. this.i2e11 = ti2[4];
  95810. this.i2e12 = ti2[5];
  95811. this.i2e20 = ti2[6];
  95812. this.i2e21 = ti2[7];
  95813. this.i2e22 = ti2[8];
  95814. var frequency1 = this.limitMotor1.frequency;
  95815. var frequency2 = this.limitMotor2.frequency;
  95816. var frequency3 = this.limitMotor3.frequency;
  95817. var enableSpring1 = frequency1 > 0;
  95818. var enableSpring2 = frequency2 > 0;
  95819. var enableSpring3 = frequency3 > 0;
  95820. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  95821. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  95822. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  95823. var angle1 = this.limitMotor1.angle;
  95824. if (enableLimit1) {
  95825. if (this.lowerLimit1 == this.upperLimit1) {
  95826. if (this.limitState1 != 0) {
  95827. this.limitState1 = 0;
  95828. this.limitImpulse1 = 0;
  95829. }
  95830. this.limitVelocity1 = this.lowerLimit1 - angle1;
  95831. } else if (angle1 < this.lowerLimit1) {
  95832. if (this.limitState1 != -1) {
  95833. this.limitState1 = -1;
  95834. this.limitImpulse1 = 0;
  95835. }
  95836. this.limitVelocity1 = this.lowerLimit1 - angle1;
  95837. } else if (angle1 > this.upperLimit1) {
  95838. if (this.limitState1 != 1) {
  95839. this.limitState1 = 1;
  95840. this.limitImpulse1 = 0;
  95841. }
  95842. this.limitVelocity1 = this.upperLimit1 - angle1;
  95843. } else {
  95844. this.limitState1 = 2;
  95845. this.limitImpulse1 = 0;
  95846. this.limitVelocity1 = 0;
  95847. }
  95848. if (!enableSpring1) {
  95849. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  95850. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  95851. else this.limitVelocity1 = 0;
  95852. }
  95853. } else {
  95854. this.limitState1 = 2;
  95855. this.limitImpulse1 = 0;
  95856. }
  95857. var angle2 = this.limitMotor2.angle;
  95858. if (enableLimit2) {
  95859. if (this.lowerLimit2 == this.upperLimit2) {
  95860. if (this.limitState2 != 0) {
  95861. this.limitState2 = 0;
  95862. this.limitImpulse2 = 0;
  95863. }
  95864. this.limitVelocity2 = this.lowerLimit2 - angle2;
  95865. } else if (angle2 < this.lowerLimit2) {
  95866. if (this.limitState2 != -1) {
  95867. this.limitState2 = -1;
  95868. this.limitImpulse2 = 0;
  95869. }
  95870. this.limitVelocity2 = this.lowerLimit2 - angle2;
  95871. } else if (angle2 > this.upperLimit2) {
  95872. if (this.limitState2 != 1) {
  95873. this.limitState2 = 1;
  95874. this.limitImpulse2 = 0;
  95875. }
  95876. this.limitVelocity2 = this.upperLimit2 - angle2;
  95877. } else {
  95878. this.limitState2 = 2;
  95879. this.limitImpulse2 = 0;
  95880. this.limitVelocity2 = 0;
  95881. }
  95882. if (!enableSpring2) {
  95883. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  95884. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  95885. else this.limitVelocity2 = 0;
  95886. }
  95887. } else {
  95888. this.limitState2 = 2;
  95889. this.limitImpulse2 = 0;
  95890. }
  95891. var angle3 = this.limitMotor3.angle;
  95892. if (enableLimit3) {
  95893. if (this.lowerLimit3 == this.upperLimit3) {
  95894. if (this.limitState3 != 0) {
  95895. this.limitState3 = 0;
  95896. this.limitImpulse3 = 0;
  95897. }
  95898. this.limitVelocity3 = this.lowerLimit3 - angle3;
  95899. } else if (angle3 < this.lowerLimit3) {
  95900. if (this.limitState3 != -1) {
  95901. this.limitState3 = -1;
  95902. this.limitImpulse3 = 0;
  95903. }
  95904. this.limitVelocity3 = this.lowerLimit3 - angle3;
  95905. } else if (angle3 > this.upperLimit3) {
  95906. if (this.limitState3 != 1) {
  95907. this.limitState3 = 1;
  95908. this.limitImpulse3 = 0;
  95909. }
  95910. this.limitVelocity3 = this.upperLimit3 - angle3;
  95911. } else {
  95912. this.limitState3 = 2;
  95913. this.limitImpulse3 = 0;
  95914. this.limitVelocity3 = 0;
  95915. }
  95916. if (!enableSpring3) {
  95917. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  95918. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  95919. else this.limitVelocity3 = 0;
  95920. }
  95921. } else {
  95922. this.limitState3 = 2;
  95923. this.limitImpulse3 = 0;
  95924. }
  95925. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  95926. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  95927. } else {
  95928. this.motorImpulse1 = 0;
  95929. this.maxMotorImpulse1 = 0;
  95930. }
  95931. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  95932. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  95933. } else {
  95934. this.motorImpulse2 = 0;
  95935. this.maxMotorImpulse2 = 0;
  95936. }
  95937. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  95938. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  95939. } else {
  95940. this.motorImpulse3 = 0;
  95941. this.maxMotorImpulse3 = 0;
  95942. }
  95943. // build jacobians
  95944. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  95945. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  95946. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  95947. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  95948. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  95949. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  95950. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  95951. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  95952. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  95953. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  95954. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  95955. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  95956. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  95957. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  95958. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  95959. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  95960. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  95961. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  95962. // build an impulse matrix
  95963. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  95964. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  95965. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  95966. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  95967. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  95968. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  95969. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  95970. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  95971. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  95972. this.kv00 = this.k00;
  95973. this.kv11 = this.k11;
  95974. this.kv22 = this.k22;
  95975. this.dv00 = 1 / this.kv00;
  95976. this.dv11 = 1 / this.kv11;
  95977. this.dv22 = 1 / this.kv22;
  95978. if (enableSpring1 && this.limitState1 != 2) {
  95979. var omega = 6.2831853 * frequency1;
  95980. var k = omega * omega * timeStep;
  95981. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  95982. this.cfm1 = this.kv00 * dmp;
  95983. this.limitVelocity1 *= k * dmp;
  95984. } else {
  95985. this.cfm1 = 0;
  95986. this.limitVelocity1 *= invTimeStep * 0.05;
  95987. }
  95988. if (enableSpring2 && this.limitState2 != 2) {
  95989. omega = 6.2831853 * frequency2;
  95990. k = omega * omega * timeStep;
  95991. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  95992. this.cfm2 = this.kv11 * dmp;
  95993. this.limitVelocity2 *= k * dmp;
  95994. } else {
  95995. this.cfm2 = 0;
  95996. this.limitVelocity2 *= invTimeStep * 0.05;
  95997. }
  95998. if (enableSpring3 && this.limitState3 != 2) {
  95999. omega = 6.2831853 * frequency3;
  96000. k = omega * omega * timeStep;
  96001. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  96002. this.cfm3 = this.kv22 * dmp;
  96003. this.limitVelocity3 *= k * dmp;
  96004. } else {
  96005. this.cfm3 = 0;
  96006. this.limitVelocity3 *= invTimeStep * 0.05;
  96007. }
  96008. this.k00 += this.cfm1;
  96009. this.k11 += this.cfm2;
  96010. this.k22 += this.cfm3;
  96011. var inv = 1 / (
  96012. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  96013. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  96014. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  96015. );
  96016. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  96017. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  96018. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  96019. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  96020. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  96021. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  96022. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  96023. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  96024. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  96025. this.limitImpulse1 *= 0.95;
  96026. this.motorImpulse1 *= 0.95;
  96027. this.limitImpulse2 *= 0.95;
  96028. this.motorImpulse2 *= 0.95;
  96029. this.limitImpulse3 *= 0.95;
  96030. this.motorImpulse3 *= 0.95;
  96031. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  96032. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  96033. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  96034. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  96035. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  96036. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  96037. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  96038. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  96039. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  96040. },
  96041. solve_: function () {
  96042. var rvx = this.a2.x - this.a1.x;
  96043. var rvy = this.a2.y - this.a1.y;
  96044. var rvz = this.a2.z - this.a1.z;
  96045. this.limitVelocity3 = 30;
  96046. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  96047. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  96048. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  96049. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96050. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96051. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96052. this.limitImpulse1 += dLimitImpulse1;
  96053. this.limitImpulse2 += dLimitImpulse2;
  96054. this.limitImpulse3 += dLimitImpulse3;
  96055. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  96056. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  96057. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  96058. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  96059. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  96060. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  96061. },
  96062. solve: function () {
  96063. var rvx = this.a2.x - this.a1.x;
  96064. var rvy = this.a2.y - this.a1.y;
  96065. var rvz = this.a2.z - this.a1.z;
  96066. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  96067. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96068. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  96069. var oldMotorImpulse1 = this.motorImpulse1;
  96070. var oldMotorImpulse2 = this.motorImpulse2;
  96071. var oldMotorImpulse3 = this.motorImpulse3;
  96072. var dMotorImpulse1 = 0;
  96073. var dMotorImpulse2 = 0;
  96074. var dMotorImpulse3 = 0;
  96075. if (this.enableMotor1) {
  96076. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  96077. this.motorImpulse1 += dMotorImpulse1;
  96078. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  96079. this.motorImpulse1 = this.maxMotorImpulse1;
  96080. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  96081. this.motorImpulse1 = -this.maxMotorImpulse1;
  96082. }
  96083. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  96084. }
  96085. if (this.enableMotor2) {
  96086. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  96087. this.motorImpulse2 += dMotorImpulse2;
  96088. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  96089. this.motorImpulse2 = this.maxMotorImpulse2;
  96090. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  96091. this.motorImpulse2 = -this.maxMotorImpulse2;
  96092. }
  96093. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  96094. }
  96095. if (this.enableMotor3) {
  96096. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  96097. this.motorImpulse3 += dMotorImpulse3;
  96098. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  96099. this.motorImpulse3 = this.maxMotorImpulse3;
  96100. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  96101. this.motorImpulse3 = -this.maxMotorImpulse3;
  96102. }
  96103. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  96104. }
  96105. // apply motor impulse to relative velocity
  96106. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  96107. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  96108. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  96109. // subtract target velocity and applied impulse
  96110. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  96111. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  96112. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  96113. var oldLimitImpulse1 = this.limitImpulse1;
  96114. var oldLimitImpulse2 = this.limitImpulse2;
  96115. var oldLimitImpulse3 = this.limitImpulse3;
  96116. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96117. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96118. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96119. this.limitImpulse1 += dLimitImpulse1;
  96120. this.limitImpulse2 += dLimitImpulse2;
  96121. this.limitImpulse3 += dLimitImpulse3;
  96122. // clamp
  96123. var clampState = 0;
  96124. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  96125. dLimitImpulse1 = -oldLimitImpulse1;
  96126. rvn2 += dLimitImpulse1 * this.k10;
  96127. rvn3 += dLimitImpulse1 * this.k20;
  96128. clampState |= 1;
  96129. }
  96130. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  96131. dLimitImpulse2 = -oldLimitImpulse2;
  96132. rvn1 += dLimitImpulse2 * this.k01;
  96133. rvn3 += dLimitImpulse2 * this.k21;
  96134. clampState |= 2;
  96135. }
  96136. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  96137. dLimitImpulse3 = -oldLimitImpulse3;
  96138. rvn1 += dLimitImpulse3 * this.k02;
  96139. rvn2 += dLimitImpulse3 * this.k12;
  96140. clampState |= 4;
  96141. }
  96142. // update un-clamped impulse
  96143. // TODO: isolate division
  96144. var det;
  96145. switch (clampState) {
  96146. case 1: // update 2 3
  96147. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  96148. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  96149. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  96150. break;
  96151. case 2: // update 1 3
  96152. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  96153. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  96154. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  96155. break;
  96156. case 3: // update 3
  96157. dLimitImpulse3 = rvn3 / this.k22;
  96158. break;
  96159. case 4: // update 1 2
  96160. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  96161. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  96162. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  96163. break;
  96164. case 5: // update 2
  96165. dLimitImpulse2 = rvn2 / this.k11;
  96166. break;
  96167. case 6: // update 1
  96168. dLimitImpulse1 = rvn1 / this.k00;
  96169. break;
  96170. }
  96171. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  96172. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  96173. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  96174. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  96175. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  96176. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  96177. // apply impulse
  96178. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  96179. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  96180. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  96181. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  96182. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  96183. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  96184. rvx = this.a2.x - this.a1.x;
  96185. rvy = this.a2.y - this.a1.y;
  96186. rvz = this.a2.z - this.a1.z;
  96187. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96188. }
  96189. }
  96190. /**
  96191. * A rotational constraint for various joints.
  96192. * @author saharan
  96193. */
  96194. OIMO.RotationalConstraint = function (joint, limitMotor) {
  96195. this.cfm = NaN;
  96196. this.i1e00 = NaN;
  96197. this.i1e01 = NaN;
  96198. this.i1e02 = NaN;
  96199. this.i1e10 = NaN;
  96200. this.i1e11 = NaN;
  96201. this.i1e12 = NaN;
  96202. this.i1e20 = NaN;
  96203. this.i1e21 = NaN;
  96204. this.i1e22 = NaN;
  96205. this.i2e00 = NaN;
  96206. this.i2e01 = NaN;
  96207. this.i2e02 = NaN;
  96208. this.i2e10 = NaN;
  96209. this.i2e11 = NaN;
  96210. this.i2e12 = NaN;
  96211. this.i2e20 = NaN;
  96212. this.i2e21 = NaN;
  96213. this.i2e22 = NaN;
  96214. this.motorDenom = NaN;
  96215. this.invMotorDenom = NaN;
  96216. this.invDenom = NaN;
  96217. this.ax = NaN;
  96218. this.ay = NaN;
  96219. this.az = NaN;
  96220. this.a1x = NaN;
  96221. this.a1y = NaN;
  96222. this.a1z = NaN;
  96223. this.a2x = NaN;
  96224. this.a2y = NaN;
  96225. this.a2z = NaN;
  96226. this.enableLimit = false;
  96227. this.lowerLimit = NaN;
  96228. this.upperLimit = NaN;
  96229. this.limitVelocity = NaN;
  96230. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96231. this.enableMotor = false;
  96232. this.motorSpeed = NaN;
  96233. this.maxMotorForce = NaN;
  96234. this.maxMotorImpulse = NaN;
  96235. this.limitMotor = limitMotor;
  96236. this.b1 = joint.body1;
  96237. this.b2 = joint.body2;
  96238. this.a1 = this.b1.angularVelocity;
  96239. this.a2 = this.b2.angularVelocity;
  96240. this.i1 = this.b1.inverseInertia;
  96241. this.i2 = this.b2.inverseInertia;
  96242. this.limitImpulse = 0;
  96243. this.motorImpulse = 0;
  96244. }
  96245. OIMO.RotationalConstraint.prototype = {
  96246. constructor: OIMO.RotationalConstraint,
  96247. preSolve: function (timeStep, invTimeStep) {
  96248. this.ax = this.limitMotor.axis.x;
  96249. this.ay = this.limitMotor.axis.y;
  96250. this.az = this.limitMotor.axis.z;
  96251. this.lowerLimit = this.limitMotor.lowerLimit;
  96252. this.upperLimit = this.limitMotor.upperLimit;
  96253. this.motorSpeed = this.limitMotor.motorSpeed;
  96254. this.maxMotorForce = this.limitMotor.maxMotorForce;
  96255. this.enableMotor = this.maxMotorForce > 0;
  96256. var ti1 = this.i1.elements;
  96257. var ti2 = this.i2.elements;
  96258. this.i1e00 = ti1[0];
  96259. this.i1e01 = ti1[1];
  96260. this.i1e02 = ti1[2];
  96261. this.i1e10 = ti1[3];
  96262. this.i1e11 = ti1[4];
  96263. this.i1e12 = ti1[5];
  96264. this.i1e20 = ti1[6];
  96265. this.i1e21 = ti1[7];
  96266. this.i1e22 = ti1[8];
  96267. this.i2e00 = ti2[0];
  96268. this.i2e01 = ti2[1];
  96269. this.i2e02 = ti2[2];
  96270. this.i2e10 = ti2[3];
  96271. this.i2e11 = ti2[4];
  96272. this.i2e12 = ti2[5];
  96273. this.i2e20 = ti2[6];
  96274. this.i2e21 = ti2[7];
  96275. this.i2e22 = ti2[8];
  96276. var frequency = this.limitMotor.frequency;
  96277. var enableSpring = frequency > 0;
  96278. var enableLimit = this.lowerLimit <= this.upperLimit;
  96279. var angle = this.limitMotor.angle;
  96280. if (enableLimit) {
  96281. if (this.lowerLimit == this.upperLimit) {
  96282. if (this.limitState != 0) {
  96283. this.limitState = 0;
  96284. this.limitImpulse = 0;
  96285. }
  96286. this.limitVelocity = this.lowerLimit - angle;
  96287. } else if (angle < this.lowerLimit) {
  96288. if (this.limitState != -1) {
  96289. this.limitState = -1;
  96290. this.limitImpulse = 0;
  96291. }
  96292. this.limitVelocity = this.lowerLimit - angle;
  96293. } else if (angle > this.upperLimit) {
  96294. if (this.limitState != 1) {
  96295. this.limitState = 1;
  96296. this.limitImpulse = 0;
  96297. }
  96298. this.limitVelocity = this.upperLimit - angle;
  96299. } else {
  96300. this.limitState = 2;
  96301. this.limitImpulse = 0;
  96302. this.limitVelocity = 0;
  96303. }
  96304. if (!enableSpring) {
  96305. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  96306. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  96307. else this.limitVelocity = 0;
  96308. }
  96309. } else {
  96310. this.limitState = 2;
  96311. this.limitImpulse = 0;
  96312. }
  96313. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  96314. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  96315. } else {
  96316. this.motorImpulse = 0;
  96317. this.maxMotorImpulse = 0;
  96318. }
  96319. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  96320. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  96321. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  96322. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  96323. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  96324. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  96325. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  96326. this.invMotorDenom = 1 / this.motorDenom;
  96327. if (enableSpring && this.limitState != 2) {
  96328. var omega = 6.2831853 * frequency;
  96329. var k = omega * omega * timeStep;
  96330. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  96331. this.cfm = this.motorDenom * dmp;
  96332. this.limitVelocity *= k * dmp;
  96333. } else {
  96334. this.cfm = 0;
  96335. this.limitVelocity *= invTimeStep * 0.05;
  96336. }
  96337. this.invDenom = 1 / (this.motorDenom + this.cfm);
  96338. this.limitImpulse *= 0.95;
  96339. this.motorImpulse *= 0.95;
  96340. var totalImpulse = this.limitImpulse + this.motorImpulse;
  96341. this.a1.x += totalImpulse * this.a1x;
  96342. this.a1.y += totalImpulse * this.a1y;
  96343. this.a1.z += totalImpulse * this.a1z;
  96344. this.a2.x -= totalImpulse * this.a2x;
  96345. this.a2.y -= totalImpulse * this.a2y;
  96346. this.a2.z -= totalImpulse * this.a2z;
  96347. },
  96348. solve: function () {
  96349. 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);
  96350. // motor part
  96351. var newMotorImpulse;
  96352. if (this.enableMotor) {
  96353. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  96354. var oldMotorImpulse = this.motorImpulse;
  96355. this.motorImpulse += newMotorImpulse;
  96356. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  96357. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  96358. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  96359. rvn -= newMotorImpulse * this.motorDenom;
  96360. } else newMotorImpulse = 0;
  96361. // limit part
  96362. var newLimitImpulse;
  96363. if (this.limitState != 2) {
  96364. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  96365. var oldLimitImpulse = this.limitImpulse;
  96366. this.limitImpulse += newLimitImpulse;
  96367. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  96368. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  96369. } else newLimitImpulse = 0;
  96370. var totalImpulse = newLimitImpulse + newMotorImpulse;
  96371. this.a1.x += totalImpulse * this.a1x;
  96372. this.a1.y += totalImpulse * this.a1y;
  96373. this.a1.z += totalImpulse * this.a1z;
  96374. this.a2.x -= totalImpulse * this.a2x;
  96375. this.a2.y -= totalImpulse * this.a2y;
  96376. this.a2.z -= totalImpulse * this.a2z;
  96377. }
  96378. }
  96379. /**
  96380. * A three-axis translational constraint for various joints.
  96381. * @author saharan
  96382. */
  96383. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  96384. this.m1 = NaN;
  96385. this.m2 = NaN;
  96386. this.i1e00 = NaN;
  96387. this.i1e01 = NaN;
  96388. this.i1e02 = NaN;
  96389. this.i1e10 = NaN;
  96390. this.i1e11 = NaN;
  96391. this.i1e12 = NaN;
  96392. this.i1e20 = NaN;
  96393. this.i1e21 = NaN;
  96394. this.i1e22 = NaN;
  96395. this.i2e00 = NaN;
  96396. this.i2e01 = NaN;
  96397. this.i2e02 = NaN;
  96398. this.i2e10 = NaN;
  96399. this.i2e11 = NaN;
  96400. this.i2e12 = NaN;
  96401. this.i2e20 = NaN;
  96402. this.i2e21 = NaN;
  96403. this.i2e22 = NaN;
  96404. this.ax1 = NaN;
  96405. this.ay1 = NaN;
  96406. this.az1 = NaN;
  96407. this.ax2 = NaN;
  96408. this.ay2 = NaN;
  96409. this.az2 = NaN;
  96410. this.ax3 = NaN;
  96411. this.ay3 = NaN;
  96412. this.az3 = NaN;
  96413. this.r1x = NaN;
  96414. this.r1y = NaN;
  96415. this.r1z = NaN;
  96416. this.r2x = NaN;
  96417. this.r2y = NaN;
  96418. this.r2z = NaN;
  96419. this.t1x1 = NaN;// jacobians
  96420. this.t1y1 = NaN;
  96421. this.t1z1 = NaN;
  96422. this.t2x1 = NaN;
  96423. this.t2y1 = NaN;
  96424. this.t2z1 = NaN;
  96425. this.l1x1 = NaN;
  96426. this.l1y1 = NaN;
  96427. this.l1z1 = NaN;
  96428. this.l2x1 = NaN;
  96429. this.l2y1 = NaN;
  96430. this.l2z1 = NaN;
  96431. this.a1x1 = NaN;
  96432. this.a1y1 = NaN;
  96433. this.a1z1 = NaN;
  96434. this.a2x1 = NaN;
  96435. this.a2y1 = NaN;
  96436. this.a2z1 = NaN;
  96437. this.t1x2 = NaN;
  96438. this.t1y2 = NaN;
  96439. this.t1z2 = NaN;
  96440. this.t2x2 = NaN;
  96441. this.t2y2 = NaN;
  96442. this.t2z2 = NaN;
  96443. this.l1x2 = NaN;
  96444. this.l1y2 = NaN;
  96445. this.l1z2 = NaN;
  96446. this.l2x2 = NaN;
  96447. this.l2y2 = NaN;
  96448. this.l2z2 = NaN;
  96449. this.a1x2 = NaN;
  96450. this.a1y2 = NaN;
  96451. this.a1z2 = NaN;
  96452. this.a2x2 = NaN;
  96453. this.a2y2 = NaN;
  96454. this.a2z2 = NaN;
  96455. this.t1x3 = NaN;
  96456. this.t1y3 = NaN;
  96457. this.t1z3 = NaN;
  96458. this.t2x3 = NaN;
  96459. this.t2y3 = NaN;
  96460. this.t2z3 = NaN;
  96461. this.l1x3 = NaN;
  96462. this.l1y3 = NaN;
  96463. this.l1z3 = NaN;
  96464. this.l2x3 = NaN;
  96465. this.l2y3 = NaN;
  96466. this.l2z3 = NaN;
  96467. this.a1x3 = NaN;
  96468. this.a1y3 = NaN;
  96469. this.a1z3 = NaN;
  96470. this.a2x3 = NaN;
  96471. this.a2y3 = NaN;
  96472. this.a2z3 = NaN;
  96473. this.lowerLimit1 = NaN;
  96474. this.upperLimit1 = NaN;
  96475. this.limitVelocity1 = NaN;
  96476. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96477. this.enableMotor1 = false;
  96478. this.motorSpeed1 = NaN;
  96479. this.maxMotorForce1 = NaN;
  96480. this.maxMotorImpulse1 = NaN;
  96481. this.lowerLimit2 = NaN;
  96482. this.upperLimit2 = NaN;
  96483. this.limitVelocity2 = NaN;
  96484. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96485. this.enableMotor2 = false;
  96486. this.motorSpeed2 = NaN;
  96487. this.maxMotorForce2 = NaN;
  96488. this.maxMotorImpulse2 = NaN;
  96489. this.lowerLimit3 = NaN;
  96490. this.upperLimit3 = NaN;
  96491. this.limitVelocity3 = NaN;
  96492. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96493. this.enableMotor3 = false;
  96494. this.motorSpeed3 = NaN;
  96495. this.maxMotorForce3 = NaN;
  96496. this.maxMotorImpulse3 = NaN;
  96497. this.k00 = NaN; // K = J*M*JT
  96498. this.k01 = NaN;
  96499. this.k02 = NaN;
  96500. this.k10 = NaN;
  96501. this.k11 = NaN;
  96502. this.k12 = NaN;
  96503. this.k20 = NaN;
  96504. this.k21 = NaN;
  96505. this.k22 = NaN;
  96506. this.kv00 = NaN; // diagonals without CFMs
  96507. this.kv11 = NaN;
  96508. this.kv22 = NaN;
  96509. this.dv00 = NaN; // ...inverted
  96510. this.dv11 = NaN;
  96511. this.dv22 = NaN;
  96512. this.d00 = NaN; // K^-1
  96513. this.d01 = NaN;
  96514. this.d02 = NaN;
  96515. this.d10 = NaN;
  96516. this.d11 = NaN;
  96517. this.d12 = NaN;
  96518. this.d20 = NaN;
  96519. this.d21 = NaN;
  96520. this.d22 = NaN;
  96521. this.limitMotor1 = limitMotor1;
  96522. this.limitMotor2 = limitMotor2;
  96523. this.limitMotor3 = limitMotor3;
  96524. this.b1 = joint.body1;
  96525. this.b2 = joint.body2;
  96526. this.p1 = joint.anchorPoint1;
  96527. this.p2 = joint.anchorPoint2;
  96528. this.r1 = joint.relativeAnchorPoint1;
  96529. this.r2 = joint.relativeAnchorPoint2;
  96530. this.l1 = this.b1.linearVelocity;
  96531. this.l2 = this.b2.linearVelocity;
  96532. this.a1 = this.b1.angularVelocity;
  96533. this.a2 = this.b2.angularVelocity;
  96534. this.i1 = this.b1.inverseInertia;
  96535. this.i2 = this.b2.inverseInertia;
  96536. this.limitImpulse1 = 0;
  96537. this.motorImpulse1 = 0;
  96538. this.limitImpulse2 = 0;
  96539. this.motorImpulse2 = 0;
  96540. this.limitImpulse3 = 0;
  96541. this.motorImpulse3 = 0;
  96542. this.cfm1 = 0;// Constraint Force Mixing
  96543. this.cfm2 = 0;
  96544. this.cfm3 = 0;
  96545. this.weight = -1;
  96546. }
  96547. OIMO.Translational3Constraint.prototype = {
  96548. constructor: OIMO.Translational3Constraint,
  96549. preSolve: function (timeStep, invTimeStep) {
  96550. this.ax1 = this.limitMotor1.axis.x;
  96551. this.ay1 = this.limitMotor1.axis.y;
  96552. this.az1 = this.limitMotor1.axis.z;
  96553. this.ax2 = this.limitMotor2.axis.x;
  96554. this.ay2 = this.limitMotor2.axis.y;
  96555. this.az2 = this.limitMotor2.axis.z;
  96556. this.ax3 = this.limitMotor3.axis.x;
  96557. this.ay3 = this.limitMotor3.axis.y;
  96558. this.az3 = this.limitMotor3.axis.z;
  96559. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  96560. this.upperLimit1 = this.limitMotor1.upperLimit;
  96561. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  96562. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  96563. this.enableMotor1 = this.maxMotorForce1 > 0;
  96564. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  96565. this.upperLimit2 = this.limitMotor2.upperLimit;
  96566. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  96567. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  96568. this.enableMotor2 = this.maxMotorForce2 > 0;
  96569. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  96570. this.upperLimit3 = this.limitMotor3.upperLimit;
  96571. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  96572. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  96573. this.enableMotor3 = this.maxMotorForce3 > 0;
  96574. this.m1 = this.b1.inverseMass;
  96575. this.m2 = this.b2.inverseMass;
  96576. var ti1 = this.i1.elements;
  96577. var ti2 = this.i2.elements;
  96578. this.i1e00 = ti1[0];
  96579. this.i1e01 = ti1[1];
  96580. this.i1e02 = ti1[2];
  96581. this.i1e10 = ti1[3];
  96582. this.i1e11 = ti1[4];
  96583. this.i1e12 = ti1[5];
  96584. this.i1e20 = ti1[6];
  96585. this.i1e21 = ti1[7];
  96586. this.i1e22 = ti1[8];
  96587. this.i2e00 = ti2[0];
  96588. this.i2e01 = ti2[1];
  96589. this.i2e02 = ti2[2];
  96590. this.i2e10 = ti2[3];
  96591. this.i2e11 = ti2[4];
  96592. this.i2e12 = ti2[5];
  96593. this.i2e20 = ti2[6];
  96594. this.i2e21 = ti2[7];
  96595. this.i2e22 = ti2[8];
  96596. var dx = this.p2.x - this.p1.x;
  96597. var dy = this.p2.y - this.p1.y;
  96598. var dz = this.p2.z - this.p1.z;
  96599. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  96600. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  96601. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  96602. var frequency1 = this.limitMotor1.frequency;
  96603. var frequency2 = this.limitMotor2.frequency;
  96604. var frequency3 = this.limitMotor3.frequency;
  96605. var enableSpring1 = frequency1 > 0;
  96606. var enableSpring2 = frequency2 > 0;
  96607. var enableSpring3 = frequency3 > 0;
  96608. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  96609. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  96610. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  96611. // for stability
  96612. if (enableSpring1 && d1 > 20 || d1 < -20) {
  96613. enableSpring1 = false;
  96614. }
  96615. if (enableSpring2 && d2 > 20 || d2 < -20) {
  96616. enableSpring2 = false;
  96617. }
  96618. if (enableSpring3 && d3 > 20 || d3 < -20) {
  96619. enableSpring3 = false;
  96620. }
  96621. if (enableLimit1) {
  96622. if (this.lowerLimit1 == this.upperLimit1) {
  96623. if (this.limitState1 != 0) {
  96624. this.limitState1 = 0;
  96625. this.limitImpulse1 = 0;
  96626. }
  96627. this.limitVelocity1 = this.lowerLimit1 - d1;
  96628. if (!enableSpring1) d1 = this.lowerLimit1;
  96629. } else if (d1 < this.lowerLimit1) {
  96630. if (this.limitState1 != -1) {
  96631. this.limitState1 = -1;
  96632. this.limitImpulse1 = 0;
  96633. }
  96634. this.limitVelocity1 = this.lowerLimit1 - d1;
  96635. if (!enableSpring1) d1 = this.lowerLimit1;
  96636. } else if (d1 > this.upperLimit1) {
  96637. if (this.limitState1 != 1) {
  96638. this.limitState1 = 1;
  96639. this.limitImpulse1 = 0;
  96640. }
  96641. this.limitVelocity1 = this.upperLimit1 - d1;
  96642. if (!enableSpring1) d1 = this.upperLimit1;
  96643. } else {
  96644. this.limitState1 = 2;
  96645. this.limitImpulse1 = 0;
  96646. this.limitVelocity1 = 0;
  96647. }
  96648. if (!enableSpring1) {
  96649. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  96650. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  96651. else this.limitVelocity1 = 0;
  96652. }
  96653. } else {
  96654. this.limitState1 = 2;
  96655. this.limitImpulse1 = 0;
  96656. }
  96657. if (enableLimit2) {
  96658. if (this.lowerLimit2 == this.upperLimit2) {
  96659. if (this.limitState2 != 0) {
  96660. this.limitState2 = 0;
  96661. this.limitImpulse2 = 0;
  96662. }
  96663. this.limitVelocity2 = this.lowerLimit2 - d2;
  96664. if (!enableSpring2) d2 = this.lowerLimit2;
  96665. } else if (d2 < this.lowerLimit2) {
  96666. if (this.limitState2 != -1) {
  96667. this.limitState2 = -1;
  96668. this.limitImpulse2 = 0;
  96669. }
  96670. this.limitVelocity2 = this.lowerLimit2 - d2;
  96671. if (!enableSpring2) d2 = this.lowerLimit2;
  96672. } else if (d2 > this.upperLimit2) {
  96673. if (this.limitState2 != 1) {
  96674. this.limitState2 = 1;
  96675. this.limitImpulse2 = 0;
  96676. }
  96677. this.limitVelocity2 = this.upperLimit2 - d2;
  96678. if (!enableSpring2) d2 = this.upperLimit2;
  96679. } else {
  96680. this.limitState2 = 2;
  96681. this.limitImpulse2 = 0;
  96682. this.limitVelocity2 = 0;
  96683. }
  96684. if (!enableSpring2) {
  96685. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  96686. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  96687. else this.limitVelocity2 = 0;
  96688. }
  96689. } else {
  96690. this.limitState2 = 2;
  96691. this.limitImpulse2 = 0;
  96692. }
  96693. if (enableLimit3) {
  96694. if (this.lowerLimit3 == this.upperLimit3) {
  96695. if (this.limitState3 != 0) {
  96696. this.limitState3 = 0;
  96697. this.limitImpulse3 = 0;
  96698. }
  96699. this.limitVelocity3 = this.lowerLimit3 - d3;
  96700. if (!enableSpring3) d3 = this.lowerLimit3;
  96701. } else if (d3 < this.lowerLimit3) {
  96702. if (this.limitState3 != -1) {
  96703. this.limitState3 = -1;
  96704. this.limitImpulse3 = 0;
  96705. }
  96706. this.limitVelocity3 = this.lowerLimit3 - d3;
  96707. if (!enableSpring3) d3 = this.lowerLimit3;
  96708. } else if (d3 > this.upperLimit3) {
  96709. if (this.limitState3 != 1) {
  96710. this.limitState3 = 1;
  96711. this.limitImpulse3 = 0;
  96712. }
  96713. this.limitVelocity3 = this.upperLimit3 - d3;
  96714. if (!enableSpring3) d3 = this.upperLimit3;
  96715. } else {
  96716. this.limitState3 = 2;
  96717. this.limitImpulse3 = 0;
  96718. this.limitVelocity3 = 0;
  96719. }
  96720. if (!enableSpring3) {
  96721. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  96722. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  96723. else this.limitVelocity3 = 0;
  96724. }
  96725. } else {
  96726. this.limitState3 = 2;
  96727. this.limitImpulse3 = 0;
  96728. }
  96729. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  96730. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  96731. } else {
  96732. this.motorImpulse1 = 0;
  96733. this.maxMotorImpulse1 = 0;
  96734. }
  96735. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  96736. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  96737. } else {
  96738. this.motorImpulse2 = 0;
  96739. this.maxMotorImpulse2 = 0;
  96740. }
  96741. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  96742. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  96743. } else {
  96744. this.motorImpulse3 = 0;
  96745. this.maxMotorImpulse3 = 0;
  96746. }
  96747. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  96748. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  96749. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  96750. var w1 = this.m2 / (this.m1 + this.m2);
  96751. if (this.weight >= 0) w1 = this.weight; // use given weight
  96752. var w2 = 1 - w1;
  96753. this.r1x = this.r1.x + rdx * w1;
  96754. this.r1y = this.r1.y + rdy * w1;
  96755. this.r1z = this.r1.z + rdz * w1;
  96756. this.r2x = this.r2.x - rdx * w2;
  96757. this.r2y = this.r2.y - rdy * w2;
  96758. this.r2z = this.r2.z - rdz * w2;
  96759. // build jacobians
  96760. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  96761. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  96762. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  96763. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  96764. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  96765. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  96766. this.l1x1 = this.ax1 * this.m1;
  96767. this.l1y1 = this.ay1 * this.m1;
  96768. this.l1z1 = this.az1 * this.m1;
  96769. this.l2x1 = this.ax1 * this.m2;
  96770. this.l2y1 = this.ay1 * this.m2;
  96771. this.l2z1 = this.az1 * this.m2;
  96772. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  96773. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  96774. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  96775. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  96776. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  96777. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  96778. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  96779. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  96780. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  96781. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  96782. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  96783. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  96784. this.l1x2 = this.ax2 * this.m1;
  96785. this.l1y2 = this.ay2 * this.m1;
  96786. this.l1z2 = this.az2 * this.m1;
  96787. this.l2x2 = this.ax2 * this.m2;
  96788. this.l2y2 = this.ay2 * this.m2;
  96789. this.l2z2 = this.az2 * this.m2;
  96790. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  96791. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  96792. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  96793. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  96794. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  96795. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  96796. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  96797. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  96798. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  96799. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  96800. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  96801. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  96802. this.l1x3 = this.ax3 * this.m1;
  96803. this.l1y3 = this.ay3 * this.m1;
  96804. this.l1z3 = this.az3 * this.m1;
  96805. this.l2x3 = this.ax3 * this.m2;
  96806. this.l2y3 = this.ay3 * this.m2;
  96807. this.l2z3 = this.az3 * this.m2;
  96808. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  96809. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  96810. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  96811. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  96812. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  96813. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  96814. // build an impulse matrix
  96815. var m12 = this.m1 + this.m2;
  96816. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  96817. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  96818. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  96819. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  96820. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  96821. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  96822. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  96823. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  96824. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  96825. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  96826. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  96827. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  96828. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  96829. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  96830. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  96831. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  96832. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  96833. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  96834. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  96835. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  96836. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  96837. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  96838. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  96839. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  96840. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  96841. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  96842. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  96843. this.kv00 = this.k00;
  96844. this.kv11 = this.k11;
  96845. this.kv22 = this.k22;
  96846. this.dv00 = 1 / this.kv00;
  96847. this.dv11 = 1 / this.kv11;
  96848. this.dv22 = 1 / this.kv22;
  96849. if (enableSpring1 && this.limitState1 != 2) {
  96850. var omega = 6.2831853 * frequency1;
  96851. var k = omega * omega * timeStep;
  96852. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  96853. this.cfm1 = this.kv00 * dmp;
  96854. this.limitVelocity1 *= k * dmp;
  96855. } else {
  96856. this.cfm1 = 0;
  96857. this.limitVelocity1 *= invTimeStep * 0.05;
  96858. }
  96859. if (enableSpring2 && this.limitState2 != 2) {
  96860. omega = 6.2831853 * frequency2;
  96861. k = omega * omega * timeStep;
  96862. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  96863. this.cfm2 = this.kv11 * dmp;
  96864. this.limitVelocity2 *= k * dmp;
  96865. } else {
  96866. this.cfm2 = 0;
  96867. this.limitVelocity2 *= invTimeStep * 0.05;
  96868. }
  96869. if (enableSpring3 && this.limitState3 != 2) {
  96870. omega = 6.2831853 * frequency3;
  96871. k = omega * omega * timeStep;
  96872. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  96873. this.cfm3 = this.kv22 * dmp;
  96874. this.limitVelocity3 *= k * dmp;
  96875. } else {
  96876. this.cfm3 = 0;
  96877. this.limitVelocity3 *= invTimeStep * 0.05;
  96878. }
  96879. this.k00 += this.cfm1;
  96880. this.k11 += this.cfm2;
  96881. this.k22 += this.cfm3;
  96882. var inv = 1 / (
  96883. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  96884. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  96885. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  96886. );
  96887. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  96888. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  96889. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  96890. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  96891. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  96892. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  96893. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  96894. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  96895. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  96896. // warm starting
  96897. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  96898. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  96899. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  96900. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  96901. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  96902. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  96903. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  96904. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  96905. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  96906. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  96907. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  96908. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  96909. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  96910. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  96911. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  96912. },
  96913. solve: function () {
  96914. 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;
  96915. 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;
  96916. 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;
  96917. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  96918. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96919. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  96920. var oldMotorImpulse1 = this.motorImpulse1;
  96921. var oldMotorImpulse2 = this.motorImpulse2;
  96922. var oldMotorImpulse3 = this.motorImpulse3;
  96923. var dMotorImpulse1 = 0;
  96924. var dMotorImpulse2 = 0;
  96925. var dMotorImpulse3 = 0;
  96926. if (this.enableMotor1) {
  96927. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  96928. this.motorImpulse1 += dMotorImpulse1;
  96929. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  96930. this.motorImpulse1 = this.maxMotorImpulse1;
  96931. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  96932. this.motorImpulse1 = -this.maxMotorImpulse1;
  96933. }
  96934. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  96935. }
  96936. if (this.enableMotor2) {
  96937. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  96938. this.motorImpulse2 += dMotorImpulse2;
  96939. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  96940. this.motorImpulse2 = this.maxMotorImpulse2;
  96941. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  96942. this.motorImpulse2 = -this.maxMotorImpulse2;
  96943. }
  96944. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  96945. }
  96946. if (this.enableMotor3) {
  96947. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  96948. this.motorImpulse3 += dMotorImpulse3;
  96949. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  96950. this.motorImpulse3 = this.maxMotorImpulse3;
  96951. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  96952. this.motorImpulse3 = -this.maxMotorImpulse3;
  96953. }
  96954. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  96955. }
  96956. // apply motor impulse to relative velocity
  96957. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  96958. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  96959. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  96960. // subtract target velocity and applied impulse
  96961. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  96962. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  96963. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  96964. var oldLimitImpulse1 = this.limitImpulse1;
  96965. var oldLimitImpulse2 = this.limitImpulse2;
  96966. var oldLimitImpulse3 = this.limitImpulse3;
  96967. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96968. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96969. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96970. this.limitImpulse1 += dLimitImpulse1;
  96971. this.limitImpulse2 += dLimitImpulse2;
  96972. this.limitImpulse3 += dLimitImpulse3;
  96973. // clamp
  96974. var clampState = 0;
  96975. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  96976. dLimitImpulse1 = -oldLimitImpulse1;
  96977. rvn2 += dLimitImpulse1 * this.k10;
  96978. rvn3 += dLimitImpulse1 * this.k20;
  96979. clampState |= 1;
  96980. }
  96981. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  96982. dLimitImpulse2 = -oldLimitImpulse2;
  96983. rvn1 += dLimitImpulse2 * this.k01;
  96984. rvn3 += dLimitImpulse2 * this.k21;
  96985. clampState |= 2;
  96986. }
  96987. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  96988. dLimitImpulse3 = -oldLimitImpulse3;
  96989. rvn1 += dLimitImpulse3 * this.k02;
  96990. rvn2 += dLimitImpulse3 * this.k12;
  96991. clampState |= 4;
  96992. }
  96993. // update un-clamped impulse
  96994. // TODO: isolate division
  96995. var det;
  96996. switch (clampState) {
  96997. case 1:// update 2 3
  96998. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  96999. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  97000. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  97001. break;
  97002. case 2:// update 1 3
  97003. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  97004. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  97005. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  97006. break;
  97007. case 3:// update 3
  97008. dLimitImpulse3 = rvn3 / this.k22;
  97009. break;
  97010. case 4:// update 1 2
  97011. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  97012. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  97013. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  97014. break;
  97015. case 5:// update 2
  97016. dLimitImpulse2 = rvn2 / this.k11;
  97017. break;
  97018. case 6:// update 1
  97019. dLimitImpulse1 = rvn1 / this.k00;
  97020. break;
  97021. }
  97022. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  97023. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  97024. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  97025. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  97026. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  97027. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  97028. // apply impulse
  97029. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  97030. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  97031. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  97032. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  97033. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  97034. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  97035. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  97036. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  97037. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  97038. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  97039. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  97040. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  97041. }
  97042. }
  97043. /**
  97044. * A translational constraint for various joints.
  97045. * @author saharan
  97046. */
  97047. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  97048. this.cfm = NaN;
  97049. this.m1 = NaN;
  97050. this.m2 = NaN;
  97051. this.i1e00 = NaN;
  97052. this.i1e01 = NaN;
  97053. this.i1e02 = NaN;
  97054. this.i1e10 = NaN;
  97055. this.i1e11 = NaN;
  97056. this.i1e12 = NaN;
  97057. this.i1e20 = NaN;
  97058. this.i1e21 = NaN;
  97059. this.i1e22 = NaN;
  97060. this.i2e00 = NaN;
  97061. this.i2e01 = NaN;
  97062. this.i2e02 = NaN;
  97063. this.i2e10 = NaN;
  97064. this.i2e11 = NaN;
  97065. this.i2e12 = NaN;
  97066. this.i2e20 = NaN;
  97067. this.i2e21 = NaN;
  97068. this.i2e22 = NaN;
  97069. this.motorDenom = NaN;
  97070. this.invMotorDenom = NaN;
  97071. this.invDenom = NaN;
  97072. this.ax = NaN;
  97073. this.ay = NaN;
  97074. this.az = NaN;
  97075. this.r1x = NaN;
  97076. this.r1y = NaN;
  97077. this.r1z = NaN;
  97078. this.r2x = NaN;
  97079. this.r2y = NaN;
  97080. this.r2z = NaN;
  97081. this.t1x = NaN;
  97082. this.t1y = NaN;
  97083. this.t1z = NaN;
  97084. this.t2x = NaN;
  97085. this.t2y = NaN;
  97086. this.t2z = NaN;
  97087. this.l1x = NaN;
  97088. this.l1y = NaN;
  97089. this.l1z = NaN;
  97090. this.l2x = NaN;
  97091. this.l2y = NaN;
  97092. this.l2z = NaN;
  97093. this.a1x = NaN;
  97094. this.a1y = NaN;
  97095. this.a1z = NaN;
  97096. this.a2x = NaN;
  97097. this.a2y = NaN;
  97098. this.a2z = NaN;
  97099. this.lowerLimit = NaN;
  97100. this.upperLimit = NaN;
  97101. this.limitVelocity = NaN;
  97102. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97103. this.enableMotor = false;
  97104. this.motorSpeed = NaN;
  97105. this.maxMotorForce = NaN;
  97106. this.maxMotorImpulse = NaN;
  97107. this.limitMotor = limitMotor;
  97108. this.b1 = joint.body1;
  97109. this.b2 = joint.body2;
  97110. this.p1 = joint.anchorPoint1;
  97111. this.p2 = joint.anchorPoint2;
  97112. this.r1 = joint.relativeAnchorPoint1;
  97113. this.r2 = joint.relativeAnchorPoint2;
  97114. this.l1 = this.b1.linearVelocity;
  97115. this.l2 = this.b2.linearVelocity;
  97116. this.a1 = this.b1.angularVelocity;
  97117. this.a2 = this.b2.angularVelocity;
  97118. this.i1 = this.b1.inverseInertia;
  97119. this.i2 = this.b2.inverseInertia;
  97120. this.limitImpulse = 0;
  97121. this.motorImpulse = 0;
  97122. }
  97123. OIMO.TranslationalConstraint.prototype = {
  97124. constructor: OIMO.TranslationalConstraint,
  97125. preSolve: function (timeStep, invTimeStep) {
  97126. this.ax = this.limitMotor.axis.x;
  97127. this.ay = this.limitMotor.axis.y;
  97128. this.az = this.limitMotor.axis.z;
  97129. this.lowerLimit = this.limitMotor.lowerLimit;
  97130. this.upperLimit = this.limitMotor.upperLimit;
  97131. this.motorSpeed = this.limitMotor.motorSpeed;
  97132. this.maxMotorForce = this.limitMotor.maxMotorForce;
  97133. this.enableMotor = this.maxMotorForce > 0;
  97134. this.m1 = this.b1.inverseMass;
  97135. this.m2 = this.b2.inverseMass;
  97136. var ti1 = this.i1.elements;
  97137. var ti2 = this.i2.elements;
  97138. this.i1e00 = ti1[0];
  97139. this.i1e01 = ti1[1];
  97140. this.i1e02 = ti1[2];
  97141. this.i1e10 = ti1[3];
  97142. this.i1e11 = ti1[4];
  97143. this.i1e12 = ti1[5];
  97144. this.i1e20 = ti1[6];
  97145. this.i1e21 = ti1[7];
  97146. this.i1e22 = ti1[8];
  97147. this.i2e00 = ti2[0];
  97148. this.i2e01 = ti2[1];
  97149. this.i2e02 = ti2[2];
  97150. this.i2e10 = ti2[3];
  97151. this.i2e11 = ti2[4];
  97152. this.i2e12 = ti2[5];
  97153. this.i2e20 = ti2[6];
  97154. this.i2e21 = ti2[7];
  97155. this.i2e22 = ti2[8];
  97156. var dx = this.p2.x - this.p1.x;
  97157. var dy = this.p2.y - this.p1.y;
  97158. var dz = this.p2.z - this.p1.z;
  97159. var d = dx * this.ax + dy * this.ay + dz * this.az;
  97160. var frequency = this.limitMotor.frequency;
  97161. var enableSpring = frequency > 0;
  97162. var enableLimit = this.lowerLimit <= this.upperLimit;
  97163. if (enableSpring && d > 20 || d < -20) {
  97164. enableSpring = false;
  97165. }
  97166. if (enableLimit) {
  97167. if (this.lowerLimit == this.upperLimit) {
  97168. if (this.limitState != 0) {
  97169. this.limitState = 0;
  97170. this.limitImpulse = 0;
  97171. }
  97172. this.limitVelocity = this.lowerLimit - d;
  97173. if (!enableSpring) d = this.lowerLimit;
  97174. } else if (d < this.lowerLimit) {
  97175. if (this.limitState != -1) {
  97176. this.limitState = -1;
  97177. this.limitImpulse = 0;
  97178. }
  97179. this.limitVelocity = this.lowerLimit - d;
  97180. if (!enableSpring) d = this.lowerLimit;
  97181. } else if (d > this.upperLimit) {
  97182. if (this.limitState != 1) {
  97183. this.limitState = 1;
  97184. this.limitImpulse = 0;
  97185. }
  97186. this.limitVelocity = this.upperLimit - d;
  97187. if (!enableSpring) d = this.upperLimit;
  97188. } else {
  97189. this.limitState = 2;
  97190. this.limitImpulse = 0;
  97191. this.limitVelocity = 0;
  97192. }
  97193. if (!enableSpring) {
  97194. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  97195. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  97196. else this.limitVelocity = 0;
  97197. }
  97198. } else {
  97199. this.limitState = 2;
  97200. this.limitImpulse = 0;
  97201. }
  97202. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  97203. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  97204. } else {
  97205. this.motorImpulse = 0;
  97206. this.maxMotorImpulse = 0;
  97207. }
  97208. var rdx = d * this.ax;
  97209. var rdy = d * this.ay;
  97210. var rdz = d * this.az;
  97211. var w1 = this.m1 / (this.m1 + this.m2);
  97212. var w2 = 1 - w1;
  97213. this.r1x = this.r1.x + rdx * w1;
  97214. this.r1y = this.r1.y + rdy * w1;
  97215. this.r1z = this.r1.z + rdz * w1;
  97216. this.r2x = this.r2.x - rdx * w2;
  97217. this.r2y = this.r2.y - rdy * w2;
  97218. this.r2z = this.r2.z - rdz * w2;
  97219. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  97220. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  97221. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  97222. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  97223. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  97224. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  97225. this.l1x = this.ax * this.m1;
  97226. this.l1y = this.ay * this.m1;
  97227. this.l1z = this.az * this.m1;
  97228. this.l2x = this.ax * this.m2;
  97229. this.l2y = this.ay * this.m2;
  97230. this.l2z = this.az * this.m2;
  97231. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  97232. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  97233. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  97234. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  97235. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  97236. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  97237. this.motorDenom =
  97238. this.m1 + this.m2 +
  97239. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  97240. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  97241. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  97242. this.invMotorDenom = 1 / this.motorDenom;
  97243. if (enableSpring && this.limitState != 2) {
  97244. var omega = 6.2831853 * frequency;
  97245. var k = omega * omega * timeStep;
  97246. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  97247. this.cfm = this.motorDenom * dmp;
  97248. this.limitVelocity *= k * dmp;
  97249. } else {
  97250. this.cfm = 0;
  97251. this.limitVelocity *= invTimeStep * 0.05;
  97252. }
  97253. this.invDenom = 1 / (this.motorDenom + this.cfm);
  97254. var totalImpulse = this.limitImpulse + this.motorImpulse;
  97255. this.l1.x += totalImpulse * this.l1x;
  97256. this.l1.y += totalImpulse * this.l1y;
  97257. this.l1.z += totalImpulse * this.l1z;
  97258. this.a1.x += totalImpulse * this.a1x;
  97259. this.a1.y += totalImpulse * this.a1y;
  97260. this.a1.z += totalImpulse * this.a1z;
  97261. this.l2.x -= totalImpulse * this.l2x;
  97262. this.l2.y -= totalImpulse * this.l2y;
  97263. this.l2.z -= totalImpulse * this.l2z;
  97264. this.a2.x -= totalImpulse * this.a2x;
  97265. this.a2.y -= totalImpulse * this.a2y;
  97266. this.a2.z -= totalImpulse * this.a2z;
  97267. },
  97268. solve: function () {
  97269. var rvn =
  97270. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  97271. 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;
  97272. // motor part
  97273. var newMotorImpulse;
  97274. if (this.enableMotor) {
  97275. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  97276. var oldMotorImpulse = this.motorImpulse;
  97277. this.motorImpulse += newMotorImpulse;
  97278. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  97279. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  97280. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  97281. rvn -= newMotorImpulse * this.motorDenom;
  97282. } else newMotorImpulse = 0;
  97283. // limit part
  97284. var newLimitImpulse;
  97285. if (this.limitState != 2) {
  97286. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  97287. var oldLimitImpulse = this.limitImpulse;
  97288. this.limitImpulse += newLimitImpulse;
  97289. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  97290. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  97291. } else newLimitImpulse = 0;
  97292. var totalImpulse = newLimitImpulse + newMotorImpulse;
  97293. this.l1.x += totalImpulse * this.l1x;
  97294. this.l1.y += totalImpulse * this.l1y;
  97295. this.l1.z += totalImpulse * this.l1z;
  97296. this.a1.x += totalImpulse * this.a1x;
  97297. this.a1.y += totalImpulse * this.a1y;
  97298. this.a1.z += totalImpulse * this.a1z;
  97299. this.l2.x -= totalImpulse * this.l2x;
  97300. this.l2.y -= totalImpulse * this.l2y;
  97301. this.l2.z -= totalImpulse * this.l2z;
  97302. this.a2.x -= totalImpulse * this.a2x;
  97303. this.a2.y -= totalImpulse * this.a2y;
  97304. this.a2.z -= totalImpulse * this.a2z;
  97305. }
  97306. }
  97307. /**
  97308. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  97309. * @author saharan
  97310. */
  97311. OIMO.Contact = function () {
  97312. // The first shape.
  97313. this.shape1 = null;
  97314. // The second shape.
  97315. this.shape2 = null;
  97316. // The first rigid body.
  97317. this.body1 = null;
  97318. // The second rigid body.
  97319. this.body2 = null;
  97320. // The previous contact in the world.
  97321. this.prev = null;
  97322. // The next contact in the world.
  97323. this.next = null;
  97324. // Internal
  97325. this.persisting = false;
  97326. // Whether both the rigid bodies are sleeping or not.
  97327. this.sleeping = false;
  97328. // The collision detector between two shapes.
  97329. this.detector = null;
  97330. // The contact constraint of the contact.
  97331. this.constraint = null;
  97332. // Whether the shapes are touching or not.
  97333. this.touching = false;
  97334. this.b1Link = new OIMO.ContactLink(this);
  97335. this.b2Link = new OIMO.ContactLink(this);
  97336. this.s1Link = new OIMO.ContactLink(this);
  97337. this.s2Link = new OIMO.ContactLink(this);
  97338. // The contact manifold of the contact.
  97339. this.manifold = new OIMO.ContactManifold();
  97340. this.buffer = [];// vector 4
  97341. this.buffer.length = 4;
  97342. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  97343. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  97344. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  97345. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  97346. this.points = this.manifold.points;
  97347. this.constraint = new OIMO.ContactConstraint(this.manifold);
  97348. }
  97349. OIMO.Contact.prototype = {
  97350. constructor: OIMO.Contact,
  97351. mixRestitution: function (restitution1, restitution2) {
  97352. return OIMO.sqrt(restitution1 * restitution2);
  97353. },
  97354. mixFriction: function (friction1, friction2) {
  97355. return OIMO.sqrt(friction1 * friction2);
  97356. },
  97357. /**
  97358. * Update the contact manifold.
  97359. */
  97360. updateManifold: function () {
  97361. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  97362. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  97363. var numBuffers = this.manifold.numPoints;
  97364. var i = numBuffers;
  97365. while (i--) {
  97366. //for(var i=0;i<numBuffers;i++){
  97367. var b = this.buffer[i];
  97368. var p = this.points[i];
  97369. b.lp1X = p.localPoint1.x;
  97370. b.lp1Y = p.localPoint1.y;
  97371. b.lp1Z = p.localPoint1.z;
  97372. b.lp2X = p.localPoint2.x;
  97373. b.lp2Y = p.localPoint2.y;
  97374. b.lp2Z = p.localPoint2.z;
  97375. b.impulse = p.normalImpulse;
  97376. }
  97377. this.manifold.numPoints = 0;
  97378. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  97379. var num = this.manifold.numPoints;
  97380. if (num == 0) {
  97381. this.touching = false;
  97382. return;
  97383. }
  97384. this.touching = true;
  97385. i = num;
  97386. while (i--) {
  97387. //for(i=0; i<num; i++){
  97388. p = this.points[i];
  97389. var lp1x = p.localPoint1.x;
  97390. var lp1y = p.localPoint1.y;
  97391. var lp1z = p.localPoint1.z;
  97392. var lp2x = p.localPoint2.x;
  97393. var lp2y = p.localPoint2.y;
  97394. var lp2z = p.localPoint2.z;
  97395. var index = -1;
  97396. var minDistance = 0.0004;
  97397. var j = numBuffers;
  97398. while (j--) {
  97399. //for(var j=0;j<numBuffers;j++){
  97400. b = this.buffer[j];
  97401. var dx = b.lp1X - lp1x;
  97402. var dy = b.lp1Y - lp1y;
  97403. var dz = b.lp1Z - lp1z;
  97404. var distance1 = dx * dx + dy * dy + dz * dz;
  97405. dx = b.lp2X - lp2x;
  97406. dy = b.lp2Y - lp2y;
  97407. dz = b.lp2Z - lp2z;
  97408. var distance2 = dx * dx + dy * dy + dz * dz;
  97409. if (distance1 < distance2) {
  97410. if (distance1 < minDistance) {
  97411. minDistance = distance1;
  97412. index = j;
  97413. }
  97414. } else {
  97415. if (distance2 < minDistance) {
  97416. minDistance = distance2;
  97417. index = j;
  97418. }
  97419. }
  97420. }
  97421. if (index != -1) {
  97422. var tmp = this.buffer[index];
  97423. this.buffer[index] = this.buffer[--numBuffers];
  97424. this.buffer[numBuffers] = tmp;
  97425. p.normalImpulse = tmp.impulse;
  97426. p.warmStarted = true;
  97427. } else {
  97428. p.normalImpulse = 0;
  97429. p.warmStarted = false;
  97430. }
  97431. }
  97432. },
  97433. /**
  97434. * Attach the contact to the shapes.
  97435. * @param shape1
  97436. * @param shape2
  97437. */
  97438. attach: function (shape1, shape2) {
  97439. this.shape1 = shape1;
  97440. this.shape2 = shape2;
  97441. this.body1 = shape1.parent;
  97442. this.body2 = shape2.parent;
  97443. this.manifold.body1 = this.body1;
  97444. this.manifold.body2 = this.body2;
  97445. this.constraint.body1 = this.body1;
  97446. this.constraint.body2 = this.body2;
  97447. this.constraint.attach();
  97448. this.s1Link.shape = shape2;
  97449. this.s1Link.body = this.body2;
  97450. this.s2Link.shape = shape1;
  97451. this.s2Link.body = this.body1;
  97452. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  97453. else this.s1Link.next = null;
  97454. shape1.contactLink = this.s1Link;
  97455. shape1.numContacts++;
  97456. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  97457. else this.s2Link.next = null;
  97458. shape2.contactLink = this.s2Link;
  97459. shape2.numContacts++;
  97460. this.b1Link.shape = shape2;
  97461. this.b1Link.body = this.body2;
  97462. this.b2Link.shape = shape1;
  97463. this.b2Link.body = this.body1;
  97464. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  97465. else this.b1Link.next = null;
  97466. this.body1.contactLink = this.b1Link;
  97467. this.body1.numContacts++;
  97468. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  97469. else this.b2Link.next = null;
  97470. this.body2.contactLink = this.b2Link;
  97471. this.body2.numContacts++;
  97472. this.prev = null;
  97473. this.next = null;
  97474. this.persisting = true;
  97475. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  97476. this.manifold.numPoints = 0;
  97477. },
  97478. /**
  97479. * Detach the contact from the shapes.
  97480. */
  97481. detach: function () {
  97482. var prev = this.s1Link.prev;
  97483. var next = this.s1Link.next;
  97484. if (prev !== null) prev.next = next;
  97485. if (next !== null) next.prev = prev;
  97486. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  97487. this.s1Link.prev = null;
  97488. this.s1Link.next = null;
  97489. this.s1Link.shape = null;
  97490. this.s1Link.body = null;
  97491. this.shape1.numContacts--;
  97492. prev = this.s2Link.prev;
  97493. next = this.s2Link.next;
  97494. if (prev !== null) prev.next = next;
  97495. if (next !== null) next.prev = prev;
  97496. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  97497. this.s2Link.prev = null;
  97498. this.s2Link.next = null;
  97499. this.s2Link.shape = null;
  97500. this.s2Link.body = null;
  97501. this.shape2.numContacts--;
  97502. prev = this.b1Link.prev;
  97503. next = this.b1Link.next;
  97504. if (prev !== null) prev.next = next;
  97505. if (next !== null) next.prev = prev;
  97506. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  97507. this.b1Link.prev = null;
  97508. this.b1Link.next = null;
  97509. this.b1Link.shape = null;
  97510. this.b1Link.body = null;
  97511. this.body1.numContacts--;
  97512. prev = this.b2Link.prev;
  97513. next = this.b2Link.next;
  97514. if (prev !== null) prev.next = next;
  97515. if (next !== null) next.prev = prev;
  97516. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  97517. this.b2Link.prev = null;
  97518. this.b2Link.next = null;
  97519. this.b2Link.shape = null;
  97520. this.b2Link.body = null;
  97521. this.body2.numContacts--;
  97522. this.manifold.body1 = null;
  97523. this.manifold.body2 = null;
  97524. this.constraint.body1 = null;
  97525. this.constraint.body2 = null;
  97526. this.constraint.detach();
  97527. this.shape1 = null;
  97528. this.shape2 = null;
  97529. this.body1 = null;
  97530. this.body2 = null;
  97531. }
  97532. }
  97533. /**
  97534. * ...
  97535. * @author saharan
  97536. */
  97537. OIMO.ContactConstraint = function (manifold) {
  97538. OIMO.Constraint.call(this);
  97539. // The contact manifold of the constraint.
  97540. this.manifold = manifold;
  97541. // The coefficient of restitution of the constraint.
  97542. this.restitution = NaN;
  97543. // The coefficient of friction of the constraint.
  97544. this.friction = NaN;
  97545. this.p1 = null;
  97546. this.p2 = null;
  97547. this.lv1 = null;
  97548. this.lv2 = null;
  97549. this.av1 = null;
  97550. this.av2 = null;
  97551. this.i1 = null;
  97552. this.i2 = null;
  97553. this.ii1 = null;
  97554. this.ii2 = null;
  97555. this.m1 = NaN;
  97556. this.m2 = NaN;
  97557. this.num = 0;
  97558. this.ps = manifold.points;
  97559. this.cs = new OIMO.ContactPointDataBuffer();
  97560. this.cs.next = new OIMO.ContactPointDataBuffer();
  97561. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  97562. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  97563. }
  97564. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  97565. /**
  97566. * Attach the constraint to the bodies.
  97567. */
  97568. OIMO.ContactConstraint.prototype.attach = function () {
  97569. this.p1 = this.body1.position;
  97570. this.p2 = this.body2.position;
  97571. this.lv1 = this.body1.linearVelocity;
  97572. this.av1 = this.body1.angularVelocity;
  97573. this.lv2 = this.body2.linearVelocity;
  97574. this.av2 = this.body2.angularVelocity;
  97575. this.i1 = this.body1.inverseInertia;
  97576. this.i2 = this.body2.inverseInertia;
  97577. }
  97578. /**
  97579. * Detach the constraint from the bodies.
  97580. */
  97581. OIMO.ContactConstraint.prototype.detach = function () {
  97582. this.p1 = null;
  97583. this.p2 = null;
  97584. this.lv1 = null;
  97585. this.lv2 = null;
  97586. this.av1 = null;
  97587. this.av2 = null;
  97588. this.i1 = null;
  97589. this.i2 = null;
  97590. }
  97591. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  97592. this.m1 = this.body1.inverseMass;
  97593. this.m2 = this.body2.inverseMass;
  97594. this.ii1 = this.i1.clone();
  97595. this.ii2 = this.i2.clone();
  97596. var ii1 = this.ii1.elements;
  97597. var ii2 = this.ii2.elements;
  97598. var p1x = this.p1.x;
  97599. var p1y = this.p1.y;
  97600. var p1z = this.p1.z;
  97601. var p2x = this.p2.x;
  97602. var p2y = this.p2.y;
  97603. var p2z = this.p2.z;
  97604. var m1m2 = this.m1 + this.m2;
  97605. this.num = this.manifold.numPoints;
  97606. var c = this.cs;
  97607. for (var i = 0; i < this.num; i++) {
  97608. var p = this.ps[i];
  97609. var tmp1X;
  97610. var tmp1Y;
  97611. var tmp1Z;
  97612. var tmp2X;
  97613. var tmp2Y;
  97614. var tmp2Z;
  97615. tmp1X = p.position.x;
  97616. tmp1Y = p.position.y;
  97617. tmp1Z = p.position.z;
  97618. var rp1X = tmp1X - p1x;
  97619. var rp1Y = tmp1Y - p1y;
  97620. var rp1Z = tmp1Z - p1z;
  97621. var rp2X = tmp1X - p2x;
  97622. var rp2Y = tmp1Y - p2y;
  97623. var rp2Z = tmp1Z - p2z;
  97624. c.rp1X = rp1X;
  97625. c.rp1Y = rp1Y;
  97626. c.rp1Z = rp1Z;
  97627. c.rp2X = rp2X;
  97628. c.rp2Y = rp2Y;
  97629. c.rp2Z = rp2Z;
  97630. c.norImp = p.normalImpulse;
  97631. c.tanImp = p.tangentImpulse;
  97632. c.binImp = p.binormalImpulse;
  97633. var norX = p.normal.x;
  97634. var norY = p.normal.y;
  97635. var norZ = p.normal.z;
  97636. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  97637. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  97638. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  97639. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  97640. var tanX = rvX - rvn * norX;
  97641. var tanY = rvY - rvn * norY;
  97642. var tanZ = rvZ - rvn * norZ;
  97643. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  97644. if (len > 0.04) {
  97645. len = 1 / OIMO.sqrt(len);
  97646. } else {
  97647. tanX = norY * norX - norZ * norZ;
  97648. tanY = -norZ * norY - norX * norX;
  97649. tanZ = norX * norZ + norY * norY;
  97650. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  97651. }
  97652. tanX *= len;
  97653. tanY *= len;
  97654. tanZ *= len;
  97655. var binX = norY * tanZ - norZ * tanY;
  97656. var binY = norZ * tanX - norX * tanZ;
  97657. var binZ = norX * tanY - norY * tanX;
  97658. c.norX = norX;
  97659. c.norY = norY;
  97660. c.norZ = norZ;
  97661. c.tanX = tanX;
  97662. c.tanY = tanY;
  97663. c.tanZ = tanZ;
  97664. c.binX = binX;
  97665. c.binY = binY;
  97666. c.binZ = binZ;
  97667. c.norU1X = norX * this.m1;
  97668. c.norU1Y = norY * this.m1;
  97669. c.norU1Z = norZ * this.m1;
  97670. c.norU2X = norX * this.m2;
  97671. c.norU2Y = norY * this.m2;
  97672. c.norU2Z = norZ * this.m2;
  97673. c.tanU1X = tanX * this.m1;
  97674. c.tanU1Y = tanY * this.m1;
  97675. c.tanU1Z = tanZ * this.m1;
  97676. c.tanU2X = tanX * this.m2;
  97677. c.tanU2Y = tanY * this.m2;
  97678. c.tanU2Z = tanZ * this.m2;
  97679. c.binU1X = binX * this.m1;
  97680. c.binU1Y = binY * this.m1;
  97681. c.binU1Z = binZ * this.m1;
  97682. c.binU2X = binX * this.m2;
  97683. c.binU2Y = binY * this.m2;
  97684. c.binU2Z = binZ * this.m2;
  97685. var norT1X = rp1Y * norZ - rp1Z * norY;
  97686. var norT1Y = rp1Z * norX - rp1X * norZ;
  97687. var norT1Z = rp1X * norY - rp1Y * norX;
  97688. var norT2X = rp2Y * norZ - rp2Z * norY;
  97689. var norT2Y = rp2Z * norX - rp2X * norZ;
  97690. var norT2Z = rp2X * norY - rp2Y * norX;
  97691. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  97692. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  97693. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  97694. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  97695. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  97696. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  97697. var binT1X = rp1Y * binZ - rp1Z * binY;
  97698. var binT1Y = rp1Z * binX - rp1X * binZ;
  97699. var binT1Z = rp1X * binY - rp1Y * binX;
  97700. var binT2X = rp2Y * binZ - rp2Z * binY;
  97701. var binT2Y = rp2Z * binX - rp2X * binZ;
  97702. var binT2Z = rp2X * binY - rp2Y * binX;
  97703. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  97704. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  97705. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  97706. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  97707. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  97708. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  97709. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  97710. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  97711. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  97712. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  97713. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  97714. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  97715. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  97716. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  97717. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  97718. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  97719. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  97720. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  97721. c.norT1X = norT1X;
  97722. c.norT1Y = norT1Y;
  97723. c.norT1Z = norT1Z;
  97724. c.tanT1X = tanT1X;
  97725. c.tanT1Y = tanT1Y;
  97726. c.tanT1Z = tanT1Z;
  97727. c.binT1X = binT1X;
  97728. c.binT1Y = binT1Y;
  97729. c.binT1Z = binT1Z;
  97730. c.norT2X = norT2X;
  97731. c.norT2Y = norT2Y;
  97732. c.norT2Z = norT2Z;
  97733. c.tanT2X = tanT2X;
  97734. c.tanT2Y = tanT2Y;
  97735. c.tanT2Z = tanT2Z;
  97736. c.binT2X = binT2X;
  97737. c.binT2Y = binT2Y;
  97738. c.binT2Z = binT2Z;
  97739. c.norTU1X = norTU1X;
  97740. c.norTU1Y = norTU1Y;
  97741. c.norTU1Z = norTU1Z;
  97742. c.tanTU1X = tanTU1X;
  97743. c.tanTU1Y = tanTU1Y;
  97744. c.tanTU1Z = tanTU1Z;
  97745. c.binTU1X = binTU1X;
  97746. c.binTU1Y = binTU1Y;
  97747. c.binTU1Z = binTU1Z;
  97748. c.norTU2X = norTU2X;
  97749. c.norTU2Y = norTU2Y;
  97750. c.norTU2Z = norTU2Z;
  97751. c.tanTU2X = tanTU2X;
  97752. c.tanTU2Y = tanTU2Y;
  97753. c.tanTU2Z = tanTU2Z;
  97754. c.binTU2X = binTU2X;
  97755. c.binTU2Y = binTU2Y;
  97756. c.binTU2Z = binTU2Z;
  97757. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  97758. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  97759. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  97760. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  97761. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  97762. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  97763. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  97764. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  97765. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  97766. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  97767. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  97768. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  97769. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  97770. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  97771. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  97772. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  97773. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  97774. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  97775. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  97776. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  97777. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  97778. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  97779. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  97780. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  97781. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  97782. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  97783. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  97784. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  97785. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  97786. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  97787. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  97788. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  97789. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  97790. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  97791. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  97792. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  97793. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  97794. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  97795. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  97796. c.norDen = norDen;
  97797. c.tanDen = tanDen;
  97798. c.binDen = binDen;
  97799. if (p.warmStarted) {
  97800. var norImp = p.normalImpulse;
  97801. this.lv1.x += c.norU1X * norImp;
  97802. this.lv1.y += c.norU1Y * norImp;
  97803. this.lv1.z += c.norU1Z * norImp;
  97804. this.av1.x += norTU1X * norImp;
  97805. this.av1.y += norTU1Y * norImp;
  97806. this.av1.z += norTU1Z * norImp;
  97807. this.lv2.x -= c.norU2X * norImp;
  97808. this.lv2.y -= c.norU2Y * norImp;
  97809. this.lv2.z -= c.norU2Z * norImp;
  97810. this.av2.x -= norTU2X * norImp;
  97811. this.av2.y -= norTU2Y * norImp;
  97812. this.av2.z -= norTU2Z * norImp;
  97813. c.norImp = norImp;
  97814. c.tanImp = 0;
  97815. c.binImp = 0;
  97816. rvn = 0; // disable bouncing
  97817. } else {
  97818. c.norImp = 0;
  97819. c.tanImp = 0;
  97820. c.binImp = 0;
  97821. }
  97822. if (rvn > -1) {
  97823. rvn = 0; // disable bouncing
  97824. }
  97825. var norTar = this.restitution * -rvn;
  97826. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  97827. if (norTar < sepV) norTar = sepV;
  97828. c.norTar = norTar;
  97829. c.last = i == this.num - 1;
  97830. c = c.next;
  97831. }
  97832. }
  97833. OIMO.ContactConstraint.prototype.solve = function () {
  97834. var lv1x = this.lv1.x;
  97835. var lv1y = this.lv1.y;
  97836. var lv1z = this.lv1.z;
  97837. var lv2x = this.lv2.x;
  97838. var lv2y = this.lv2.y;
  97839. var lv2z = this.lv2.z;
  97840. var av1x = this.av1.x;
  97841. var av1y = this.av1.y;
  97842. var av1z = this.av1.z;
  97843. var av2x = this.av2.x;
  97844. var av2y = this.av2.y;
  97845. var av2z = this.av2.z;
  97846. var c = this.cs;
  97847. while (true) {
  97848. var oldImp1;
  97849. var newImp1;
  97850. var oldImp2;
  97851. var newImp2;
  97852. var rvn;
  97853. var norImp = c.norImp;
  97854. var tanImp = c.tanImp;
  97855. var binImp = c.binImp;
  97856. var max = -norImp * this.friction;
  97857. var rvX = lv2x - lv1x;
  97858. var rvY = lv2y - lv1y;
  97859. var rvZ = lv2z - lv1z;
  97860. rvn =
  97861. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  97862. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  97863. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  97864. ;
  97865. oldImp1 = tanImp;
  97866. newImp1 = rvn * c.tanDen;
  97867. tanImp += newImp1;
  97868. rvn =
  97869. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  97870. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  97871. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  97872. ;
  97873. oldImp2 = binImp;
  97874. newImp2 = rvn * c.binDen;
  97875. binImp += newImp2;
  97876. // cone friction clamp
  97877. var len = tanImp * tanImp + binImp * binImp;
  97878. if (len > max * max) {
  97879. len = max / OIMO.sqrt(len);
  97880. tanImp *= len;
  97881. binImp *= len;
  97882. }
  97883. newImp1 = tanImp - oldImp1;
  97884. newImp2 = binImp - oldImp2;
  97885. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  97886. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  97887. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  97888. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  97889. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  97890. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  97891. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  97892. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  97893. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  97894. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  97895. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  97896. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  97897. // restitution part
  97898. rvn =
  97899. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  97900. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  97901. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  97902. oldImp1 = norImp;
  97903. newImp1 = (rvn - c.norTar) * c.norDen;
  97904. norImp += newImp1;
  97905. if (norImp > 0) norImp = 0;
  97906. newImp1 = norImp - oldImp1;
  97907. lv1x += c.norU1X * newImp1;
  97908. lv1y += c.norU1Y * newImp1;
  97909. lv1z += c.norU1Z * newImp1;
  97910. av1x += c.norTU1X * newImp1;
  97911. av1y += c.norTU1Y * newImp1;
  97912. av1z += c.norTU1Z * newImp1;
  97913. lv2x -= c.norU2X * newImp1;
  97914. lv2y -= c.norU2Y * newImp1;
  97915. lv2z -= c.norU2Z * newImp1;
  97916. av2x -= c.norTU2X * newImp1;
  97917. av2y -= c.norTU2Y * newImp1;
  97918. av2z -= c.norTU2Z * newImp1;
  97919. c.norImp = norImp;
  97920. c.tanImp = tanImp;
  97921. c.binImp = binImp;
  97922. if (c.last) break;
  97923. c = c.next;
  97924. }
  97925. this.lv1.x = lv1x;
  97926. this.lv1.y = lv1y;
  97927. this.lv1.z = lv1z;
  97928. this.lv2.x = lv2x;
  97929. this.lv2.y = lv2y;
  97930. this.lv2.z = lv2z;
  97931. this.av1.x = av1x;
  97932. this.av1.y = av1y;
  97933. this.av1.z = av1z;
  97934. this.av2.x = av2x;
  97935. this.av2.y = av2y;
  97936. this.av2.z = av2z;
  97937. }
  97938. OIMO.ContactConstraint.prototype.postSolve = function () {
  97939. var c = this.cs;
  97940. var i = this.num;
  97941. while (i--) {
  97942. //for(var i=0;i<this.num;i++){
  97943. var p = this.ps[i];
  97944. p.normal.x = c.norX;
  97945. p.normal.y = c.norY;
  97946. p.normal.z = c.norZ;
  97947. p.tangent.x = c.tanX;
  97948. p.tangent.y = c.tanY;
  97949. p.tangent.z = c.tanZ;
  97950. p.binormal.x = c.binX;
  97951. p.binormal.y = c.binY;
  97952. p.binormal.z = c.binZ;
  97953. p.normalImpulse = c.norImp;
  97954. p.tangentImpulse = c.tanImp;
  97955. p.binormalImpulse = c.binImp;
  97956. p.normalDenominator = c.norDen;
  97957. p.tangentDenominator = c.tanDen;
  97958. p.binormalDenominator = c.binDen;
  97959. c = c.next;
  97960. }
  97961. }
  97962. /**
  97963. * A link list of contacts.
  97964. * @author saharan
  97965. */
  97966. OIMO.ContactLink = function (contact) {
  97967. // The previous contact link.
  97968. this.prev = null;
  97969. // The next contact link.
  97970. this.next = null;
  97971. // The shape of the contact.
  97972. this.shape = null;
  97973. // The other rigid body.
  97974. this.body = null;
  97975. // The contact of the link.
  97976. this.contact = contact;
  97977. }
  97978. /**
  97979. * A contact manifold between two shapes.
  97980. * @author saharan
  97981. */
  97982. OIMO.ContactManifold = function () {
  97983. // The first rigid body.
  97984. this.body1 = null;
  97985. // The second rigid body.
  97986. this.body2 = null;
  97987. // The number of manifold points.
  97988. this.numPoints = 0;
  97989. // The manifold points.
  97990. this.points = [];
  97991. this.points.length = 4;
  97992. this.points[0] = new OIMO.ManifoldPoint();
  97993. this.points[1] = new OIMO.ManifoldPoint();
  97994. this.points[2] = new OIMO.ManifoldPoint();
  97995. this.points[3] = new OIMO.ManifoldPoint();
  97996. }
  97997. OIMO.ContactManifold.prototype = {
  97998. constructor: OIMO.ContactManifold,
  97999. /**
  98000. * Reset the manifold.
  98001. * @param shape1
  98002. * @param shape2
  98003. */
  98004. reset: function (shape1, shape2) {
  98005. this.body1 = shape1.parent;
  98006. this.body2 = shape2.parent;
  98007. this.numPoints = 0;
  98008. },
  98009. /**
  98010. * Add a point into this manifold.
  98011. * @param x
  98012. * @param y
  98013. * @param z
  98014. * @param normalX
  98015. * @param normalY
  98016. * @param normalZ
  98017. * @param penetration
  98018. * @param flip
  98019. */
  98020. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  98021. var p = this.points[this.numPoints++];
  98022. p.position.x = x;
  98023. p.position.y = y;
  98024. p.position.z = z;
  98025. var r = this.body1.rotation;
  98026. var rx = x - this.body1.position.x;
  98027. var ry = y - this.body1.position.y;
  98028. var rz = z - this.body1.position.z;
  98029. var tr = r.elements;
  98030. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98031. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98032. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98033. r = this.body2.rotation;
  98034. rx = x - this.body2.position.x;
  98035. ry = y - this.body2.position.y;
  98036. rz = z - this.body2.position.z;
  98037. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98038. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98039. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98040. p.normalImpulse = 0;
  98041. if (flip) {
  98042. p.normal.x = -normalX;
  98043. p.normal.y = -normalY;
  98044. p.normal.z = -normalZ;
  98045. } else {
  98046. p.normal.x = normalX;
  98047. p.normal.y = normalY;
  98048. p.normal.z = normalZ;
  98049. }
  98050. p.penetration = penetration;
  98051. p.warmStarted = false;
  98052. }
  98053. }
  98054. OIMO.ContactPointDataBuffer = function () {
  98055. this.norX = NaN;
  98056. this.norY = NaN;
  98057. this.norZ = NaN;
  98058. this.tanX = NaN;
  98059. this.tanY = NaN;
  98060. this.tanZ = NaN;
  98061. this.binX = NaN;
  98062. this.binY = NaN;
  98063. this.binZ = NaN;
  98064. this.rp1X = NaN;
  98065. this.rp1Y = NaN;
  98066. this.rp1Z = NaN;
  98067. this.rp2X = NaN;
  98068. this.rp2Y = NaN;
  98069. this.rp2Z = NaN;
  98070. this.norU1X = NaN;
  98071. this.norU1Y = NaN;
  98072. this.norU1Z = NaN;
  98073. this.norU2X = NaN;
  98074. this.norU2Y = NaN;
  98075. this.norU2Z = NaN;
  98076. this.tanU1X = NaN;
  98077. this.tanU1Y = NaN;
  98078. this.tanU1Z = NaN;
  98079. this.tanU2X = NaN;
  98080. this.tanU2Y = NaN;
  98081. this.tanU2Z = NaN;
  98082. this.binU1X = NaN;
  98083. this.binU1Y = NaN;
  98084. this.binU1Z = NaN;
  98085. this.binU2X = NaN;
  98086. this.binU2Y = NaN;
  98087. this.binU2Z = NaN;
  98088. this.norT1X = NaN;
  98089. this.norT1Y = NaN;
  98090. this.norT1Z = NaN;
  98091. this.norT2X = NaN;
  98092. this.norT2Y = NaN;
  98093. this.norT2Z = NaN;
  98094. this.tanT1X = NaN;
  98095. this.tanT1Y = NaN;
  98096. this.tanT1Z = NaN;
  98097. this.tanT2X = NaN;
  98098. this.tanT2Y = NaN;
  98099. this.tanT2Z = NaN;
  98100. this.binT1X = NaN;
  98101. this.binT1Y = NaN;
  98102. this.binT1Z = NaN;
  98103. this.binT2X = NaN;
  98104. this.binT2Y = NaN;
  98105. this.binT2Z = NaN;
  98106. this.norTU1X = NaN;
  98107. this.norTU1Y = NaN;
  98108. this.norTU1Z = NaN;
  98109. this.norTU2X = NaN;
  98110. this.norTU2Y = NaN;
  98111. this.norTU2Z = NaN;
  98112. this.tanTU1X = NaN;
  98113. this.tanTU1Y = NaN;
  98114. this.tanTU1Z = NaN;
  98115. this.tanTU2X = NaN;
  98116. this.tanTU2Y = NaN;
  98117. this.tanTU2Z = NaN;
  98118. this.binTU1X = NaN;
  98119. this.binTU1Y = NaN;
  98120. this.binTU1Z = NaN;
  98121. this.binTU2X = NaN;
  98122. this.binTU2Y = NaN;
  98123. this.binTU2Z = NaN;
  98124. this.norImp = NaN;
  98125. this.tanImp = NaN;
  98126. this.binImp = NaN;
  98127. this.norDen = NaN;
  98128. this.tanDen = NaN;
  98129. this.binDen = NaN;
  98130. this.norTar = NaN;
  98131. this.next = null;
  98132. this.last = false;
  98133. }
  98134. OIMO.ImpulseDataBuffer = function () {
  98135. this.lp1X = NaN;
  98136. this.lp1Y = NaN;
  98137. this.lp1Z = NaN;
  98138. this.lp2X = NaN;
  98139. this.lp2Y = NaN;
  98140. this.lp2Z = NaN;
  98141. this.impulse = NaN;
  98142. }
  98143. /**
  98144. * The class holds details of the contact point.
  98145. * @author saharan
  98146. */
  98147. OIMO.ManifoldPoint = function () {
  98148. // Whether this manifold point is persisting or not.
  98149. this.warmStarted = false;
  98150. // The position of this manifold point.
  98151. this.position = new OIMO.Vec3();
  98152. // The position in the first shape's coordinate.
  98153. this.localPoint1 = new OIMO.Vec3();
  98154. // The position in the second shape's coordinate.
  98155. this.localPoint2 = new OIMO.Vec3();
  98156. // The normal vector of this manifold point.
  98157. this.normal = new OIMO.Vec3();
  98158. // The tangent vector of this manifold point.
  98159. this.tangent = new OIMO.Vec3();
  98160. // The binormal vector of this manifold point.
  98161. this.binormal = new OIMO.Vec3();
  98162. // The impulse in normal direction.
  98163. this.normalImpulse = 0;
  98164. // The impulse in tangent direction.
  98165. this.tangentImpulse = 0;
  98166. // The impulse in binormal direction.
  98167. this.binormalImpulse = 0;
  98168. // The denominator in normal direction.
  98169. this.normalDenominator = 0;
  98170. // The denominator in tangent direction.
  98171. this.tangentDenominator = 0;
  98172. // The denominator in binormal direction.
  98173. this.binormalDenominator = 0;
  98174. // The depth of penetration.
  98175. this.penetration = 0;
  98176. }
  98177. /**
  98178. * This class holds mass information of a shape.
  98179. * @author saharan
  98180. */
  98181. OIMO.MassInfo = function () {
  98182. // Mass of the shape.
  98183. this.mass = 0;
  98184. // The moment inertia of the shape.
  98185. this.inertia = new OIMO.Mat33();
  98186. };
  98187. /**
  98188. * A shape is used to detect collisions of rigid bodies.
  98189. * @author saharan
  98190. * @author lo-th
  98191. */
  98192. OIMO.Shape = function (config) {
  98193. this.type = OIMO.SHAPE_NULL;
  98194. // The global identification of the shape should be unique to the shape.
  98195. this.id = OIMO.nextID++;
  98196. // The previous shape in parent rigid body.
  98197. this.prev = null;
  98198. // The next shape in parent rigid body.
  98199. this.next = null;
  98200. // The proxy of the shape used for broad-phase collision detection.
  98201. this.proxy = null;
  98202. // The parent rigid body of the shape.
  98203. this.parent = null;
  98204. // The linked list of the contacts with the shape.
  98205. this.contactLink = null;
  98206. // The number of the contacts with the shape.
  98207. this.numContacts = 0;
  98208. // The center of gravity of the shape in world coordinate system.
  98209. this.position = new OIMO.Vec3();
  98210. // The rotation matrix of the shape in world coordinate system
  98211. this.rotation = new OIMO.Mat33();
  98212. // The position of the shape in parent's coordinate system.
  98213. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  98214. // The rotation matrix of the shape in parent's coordinate system.
  98215. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  98216. // The axis-aligned bounding box of the shape.
  98217. this.aabb = new OIMO.AABB();
  98218. // The density of the shape.
  98219. this.density = config.density;
  98220. // The coefficient of friction of the shape.
  98221. this.friction = config.friction;
  98222. // The coefficient of restitution of the shape.
  98223. this.restitution = config.restitution;
  98224. // The bits of the collision groups to which the shape belongs.
  98225. this.belongsTo = config.belongsTo;
  98226. // The bits of the collision groups with which the shape collides.
  98227. this.collidesWith = config.collidesWith;
  98228. };
  98229. OIMO.Shape.prototype = {
  98230. constructor: OIMO.Shape,
  98231. // Calculate the mass information of the shape.
  98232. calculateMassInfo: function (out) {
  98233. OIMO.Error("Shape", "Inheritance error.");
  98234. },
  98235. // Update the proxy of the shape.
  98236. updateProxy: function () {
  98237. OIMO.Error("Shape", "Inheritance error.");
  98238. }
  98239. };
  98240. /**
  98241. * A shape configuration holds common configuration data for constructing a shape.
  98242. * Shape configurations can be reused safely.
  98243. * @author saharan
  98244. */
  98245. OIMO.ShapeConfig = function () {
  98246. // The position of the shape in parent's coordinate system.
  98247. this.relativePosition = new OIMO.Vec3();
  98248. // The rotation matrix of the shape in parent's coordinate system.
  98249. this.relativeRotation = new OIMO.Mat33();
  98250. // The coefficient of friction of the shape.
  98251. this.friction = 0.4;
  98252. // The coefficient of restitution of the shape.
  98253. this.restitution = 0.2;
  98254. // The density of the shape.
  98255. this.density = 1;
  98256. // The bits of the collision groups to which the shape belongs.
  98257. this.belongsTo = 1;
  98258. // The bits of the collision groups with which the shape collides.
  98259. this.collidesWith = 0xffffffff;
  98260. };
  98261. /**
  98262. * A box shape.
  98263. * @author saharan
  98264. * @author lo-th
  98265. */
  98266. OIMO.BoxShape = function (config, Width, Height, Depth) {
  98267. OIMO.Shape.call(this, config);
  98268. this.type = OIMO.SHAPE_BOX;
  98269. // The width of the box.
  98270. this.width = Width;
  98271. // The height of the box.
  98272. this.height = Height;
  98273. // The depth of the box.
  98274. this.depth = Depth;
  98275. // The half-width of the box.
  98276. this.halfWidth = Width * 0.5;
  98277. // The half-height of the box.
  98278. this.halfHeight = Height * 0.5;
  98279. // The half-depth of the box.
  98280. this.halfDepth = Depth * 0.5;
  98281. this.dimentions = new OIMO_ARRAY_TYPE(18);
  98282. this.elements = new OIMO_ARRAY_TYPE(24);
  98283. };
  98284. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  98285. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  98286. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  98287. var mass = this.width * this.height * this.depth * this.density;
  98288. var divid = 1 / 12;
  98289. out.mass = mass;
  98290. out.inertia.set(
  98291. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  98292. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  98293. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  98294. );
  98295. };
  98296. OIMO.BoxShape.prototype.updateProxy = function () {
  98297. var te = this.rotation.elements;
  98298. var di = this.dimentions;
  98299. // Width
  98300. di[0] = te[0];
  98301. di[1] = te[3];
  98302. di[2] = te[6];
  98303. // Height
  98304. di[3] = te[1];
  98305. di[4] = te[4];
  98306. di[5] = te[7];
  98307. // Depth
  98308. di[6] = te[2];
  98309. di[7] = te[5];
  98310. di[8] = te[8];
  98311. // halp Width
  98312. di[9] = te[0] * this.halfWidth;
  98313. di[10] = te[3] * this.halfWidth;
  98314. di[11] = te[6] * this.halfWidth;
  98315. // halp Height
  98316. di[12] = te[1] * this.halfHeight;
  98317. di[13] = te[4] * this.halfHeight;
  98318. di[14] = te[7] * this.halfHeight;
  98319. // halp Depth
  98320. di[15] = te[2] * this.halfDepth;
  98321. di[16] = te[5] * this.halfDepth;
  98322. di[17] = te[8] * this.halfDepth;
  98323. var wx = di[9];
  98324. var wy = di[10];
  98325. var wz = di[11];
  98326. var hx = di[12];
  98327. var hy = di[13];
  98328. var hz = di[14];
  98329. var dx = di[15];
  98330. var dy = di[16];
  98331. var dz = di[17];
  98332. var x = this.position.x;
  98333. var y = this.position.y;
  98334. var z = this.position.z;
  98335. var v = this.elements;
  98336. //v1
  98337. v[0] = x + wx + hx + dx;
  98338. v[1] = y + wy + hy + dy;
  98339. v[2] = z + wz + hz + dz;
  98340. //v2
  98341. v[3] = x + wx + hx - dx;
  98342. v[4] = y + wy + hy - dy;
  98343. v[5] = z + wz + hz - dz;
  98344. //v3
  98345. v[6] = x + wx - hx + dx;
  98346. v[7] = y + wy - hy + dy;
  98347. v[8] = z + wz - hz + dz;
  98348. //v4
  98349. v[9] = x + wx - hx - dx;
  98350. v[10] = y + wy - hy - dy;
  98351. v[11] = z + wz - hz - dz;
  98352. //v5
  98353. v[12] = x - wx + hx + dx;
  98354. v[13] = y - wy + hy + dy;
  98355. v[14] = z - wz + hz + dz;
  98356. //v6
  98357. v[15] = x - wx + hx - dx;
  98358. v[16] = y - wy + hy - dy;
  98359. v[17] = z - wz + hz - dz;
  98360. //v7
  98361. v[18] = x - wx - hx + dx;
  98362. v[19] = y - wy - hy + dy;
  98363. v[20] = z - wz - hz + dz;
  98364. //v8
  98365. v[21] = x - wx - hx - dx;
  98366. v[22] = y - wy - hy - dy;
  98367. v[23] = z - wz - hz - dz;
  98368. var w = di[9] < 0 ? -di[9] : di[9];
  98369. var h = di[10] < 0 ? -di[10] : di[10];
  98370. var d = di[11] < 0 ? -di[11] : di[11];
  98371. w = di[12] < 0 ? w - di[12] : w + di[12];
  98372. h = di[13] < 0 ? h - di[13] : h + di[13];
  98373. d = di[14] < 0 ? d - di[14] : d + di[14];
  98374. w = di[15] < 0 ? w - di[15] : w + di[15];
  98375. h = di[16] < 0 ? h - di[16] : h + di[16];
  98376. d = di[17] < 0 ? d - di[17] : d + di[17];
  98377. var p = OIMO.AABB_PROX;
  98378. this.aabb.set(
  98379. this.position.x - w - p, this.position.x + w + p,
  98380. this.position.y - h - p, this.position.y + h + p,
  98381. this.position.z - d - p, this.position.z + d + p
  98382. );
  98383. if (this.proxy != null) this.proxy.update();
  98384. };
  98385. /**
  98386. * A sphere shape.
  98387. * @author saharan
  98388. * @author lo-th
  98389. */
  98390. OIMO.SphereShape = function (config, radius) {
  98391. OIMO.Shape.call(this, config);
  98392. this.type = OIMO.SHAPE_SPHERE;
  98393. // The radius of the shape.
  98394. this.radius = radius;
  98395. };
  98396. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  98397. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  98398. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  98399. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  98400. out.mass = mass;
  98401. var inertia = mass * this.radius * this.radius * 0.4;
  98402. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  98403. };
  98404. OIMO.SphereShape.prototype.updateProxy = function () {
  98405. var p = OIMO.AABB_PROX;
  98406. this.aabb.set(
  98407. this.position.x - this.radius - p, this.position.x + this.radius + p,
  98408. this.position.y - this.radius - p, this.position.y + this.radius + p,
  98409. this.position.z - this.radius - p, this.position.z + this.radius + p
  98410. );
  98411. if (this.proxy != null) this.proxy.update();
  98412. };
  98413. /**
  98414. * A cylinder shap.
  98415. * @author saharan
  98416. * @author lo-th
  98417. */
  98418. OIMO.CylinderShape = function (config, radius, height) {
  98419. OIMO.Shape.call(this, config);
  98420. this.type = OIMO.SHAPE_CYLINDER;
  98421. this.radius = radius;
  98422. this.height = height;
  98423. this.halfHeight = height * 0.5;
  98424. this.normalDirection = new OIMO.Vec3();
  98425. this.halfDirection = new OIMO.Vec3();
  98426. };
  98427. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  98428. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  98429. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  98430. var rsq = this.radius * this.radius;
  98431. var mass = OIMO.PI * rsq * this.height * this.density;
  98432. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  98433. var inertiaY = 0.5 * rsq;
  98434. out.mass = mass;
  98435. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  98436. };
  98437. OIMO.CylinderShape.prototype.updateProxy = function () {
  98438. var te = this.rotation.elements;
  98439. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  98440. xx = te[1] * te[1];
  98441. yy = te[4] * te[4];
  98442. zz = te[7] * te[7];
  98443. this.normalDirection.set(te[1], te[4], te[7]);
  98444. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  98445. wx = 1 - xx;
  98446. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  98447. if (len > 0) len = this.radius / len;
  98448. wx *= len;
  98449. hy = 1 - yy;
  98450. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  98451. if (len > 0) len = this.radius / len;
  98452. hy *= len;
  98453. dz = 1 - zz;
  98454. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  98455. if (len > 0) len = this.radius / len;
  98456. dz *= len;
  98457. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  98458. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  98459. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  98460. w = wx < 0 ? w - wx : w + wx;
  98461. h = hy < 0 ? h - hy : h + hy;
  98462. d = dz < 0 ? d - dz : d + dz;
  98463. p = OIMO.AABB_PROX;
  98464. this.aabb.set(
  98465. this.position.x - w - p, this.position.x + w + p,
  98466. this.position.y - h - p, this.position.y + h + p,
  98467. this.position.z - d - p, this.position.z + d + p
  98468. );
  98469. if (this.proxy != null) this.proxy.update();
  98470. };
  98471. /**
  98472. * A tetra shape.
  98473. * @author xprogram
  98474. */
  98475. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  98476. OIMO.Shape.call(this, config);
  98477. this.type = OIMO.SHAPE_TETRA;
  98478. // Vertices and faces of tetra
  98479. this.verts = [p1, p2, p3, p4];
  98480. this.faces = [
  98481. mtri(0, 1, 2),
  98482. mtri(1, 2, 3),
  98483. mtri(2, 3, 4),
  98484. mtri(4, 0, 1),
  98485. ];
  98486. };
  98487. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  98488. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  98489. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  98490. // I guess you could calculate box mass and split it
  98491. // in half for the tetra...
  98492. };
  98493. OIMO.TetraShape.prototype.updateProxy = function () {
  98494. this.aabb.setFromPoints(this.verts);
  98495. if (this.proxy !== null)
  98496. this.proxy.update();
  98497. };
  98498. function mtri(a, b, c) {
  98499. return { a: a, b: b, c: c };
  98500. }
  98501. OIMO.CollisionDetector = function () {
  98502. this.flip = false;
  98503. };
  98504. OIMO.CollisionDetector.prototype = {
  98505. constructor: OIMO.CollisionDetector,
  98506. detectCollision: function (shape1, shape2, manifold) {
  98507. OIMO.Error("CollisionDetector", "Inheritance error.");
  98508. }
  98509. };
  98510. /**
  98511. * A collision detector which detects collisions between two boxes.
  98512. * @author saharan
  98513. */
  98514. OIMO.BoxBoxCollisionDetector = function () {
  98515. OIMO.CollisionDetector.call(this);
  98516. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  98517. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  98518. this.used = new OIMO_ARRAY_TYPE(8);
  98519. this.INF = 1 / 0;
  98520. };
  98521. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  98522. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  98523. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  98524. // What you are doing
  98525. // · I to prepare a separate axis of the fifteen
  98526. //-Six in each of three normal vectors of the xyz direction of the box both
  98527. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  98528. // · Calculate the depth to the separation axis
  98529. // Calculates the distance using the inner product and put the amount of embedment
  98530. // · However a vertical separation axis and side to weight a little to avoid vibration
  98531. // And end when there is a separate axis that is remote even one
  98532. // · I look for separation axis with little to dent most
  98533. // Men and if separation axis of the first six - end collision
  98534. // Heng If it separate axis of nine other - side collision
  98535. // Heng - case of a side collision
  98536. // · Find points of two sides on which you made ​​the separation axis
  98537. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  98538. //-Surface - the case of the plane crash
  98539. //-Box A, box B and the other a box of better made ​​a separate axis
  98540. // • 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
  98541. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  98542. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  98543. // • If more than one candidate 5 exists, scraping up to four
  98544. // For potential collision points of all, to examine the distance between the surface A
  98545. // • If you were on the inside surface of A, and the collision point
  98546. var b1;
  98547. var b2;
  98548. if (shape1.id < shape2.id) {
  98549. b1 = (shape1);
  98550. b2 = (shape2);
  98551. } else {
  98552. b1 = (shape2);
  98553. b2 = (shape1);
  98554. }
  98555. var V1 = b1.elements;
  98556. var V2 = b2.elements;
  98557. var D1 = b1.dimentions;
  98558. var D2 = b2.dimentions;
  98559. var p1 = b1.position;
  98560. var p2 = b2.position;
  98561. var p1x = p1.x;
  98562. var p1y = p1.y;
  98563. var p1z = p1.z;
  98564. var p2x = p2.x;
  98565. var p2y = p2.y;
  98566. var p2z = p2.z;
  98567. // diff
  98568. var dx = p2x - p1x;
  98569. var dy = p2y - p1y;
  98570. var dz = p2z - p1z;
  98571. // distance
  98572. var w1 = b1.halfWidth;
  98573. var h1 = b1.halfHeight;
  98574. var d1 = b1.halfDepth;
  98575. var w2 = b2.halfWidth;
  98576. var h2 = b2.halfHeight;
  98577. var d2 = b2.halfDepth;
  98578. // direction
  98579. // ----------------------------
  98580. // 15 separating axes
  98581. // 1~6: face
  98582. // 7~f: edge
  98583. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  98584. // ----------------------------
  98585. var a1x = D1[0];
  98586. var a1y = D1[1];
  98587. var a1z = D1[2];
  98588. var a2x = D1[3];
  98589. var a2y = D1[4];
  98590. var a2z = D1[5];
  98591. var a3x = D1[6];
  98592. var a3y = D1[7];
  98593. var a3z = D1[8];
  98594. var d1x = D1[9];
  98595. var d1y = D1[10];
  98596. var d1z = D1[11];
  98597. var d2x = D1[12];
  98598. var d2y = D1[13];
  98599. var d2z = D1[14];
  98600. var d3x = D1[15];
  98601. var d3y = D1[16];
  98602. var d3z = D1[17];
  98603. var a4x = D2[0];
  98604. var a4y = D2[1];
  98605. var a4z = D2[2];
  98606. var a5x = D2[3];
  98607. var a5y = D2[4];
  98608. var a5z = D2[5];
  98609. var a6x = D2[6];
  98610. var a6y = D2[7];
  98611. var a6z = D2[8];
  98612. var d4x = D2[9];
  98613. var d4y = D2[10];
  98614. var d4z = D2[11];
  98615. var d5x = D2[12];
  98616. var d5y = D2[13];
  98617. var d5z = D2[14];
  98618. var d6x = D2[15];
  98619. var d6y = D2[16];
  98620. var d6z = D2[17];
  98621. var a7x = a1y * a4z - a1z * a4y;
  98622. var a7y = a1z * a4x - a1x * a4z;
  98623. var a7z = a1x * a4y - a1y * a4x;
  98624. var a8x = a1y * a5z - a1z * a5y;
  98625. var a8y = a1z * a5x - a1x * a5z;
  98626. var a8z = a1x * a5y - a1y * a5x;
  98627. var a9x = a1y * a6z - a1z * a6y;
  98628. var a9y = a1z * a6x - a1x * a6z;
  98629. var a9z = a1x * a6y - a1y * a6x;
  98630. var aax = a2y * a4z - a2z * a4y;
  98631. var aay = a2z * a4x - a2x * a4z;
  98632. var aaz = a2x * a4y - a2y * a4x;
  98633. var abx = a2y * a5z - a2z * a5y;
  98634. var aby = a2z * a5x - a2x * a5z;
  98635. var abz = a2x * a5y - a2y * a5x;
  98636. var acx = a2y * a6z - a2z * a6y;
  98637. var acy = a2z * a6x - a2x * a6z;
  98638. var acz = a2x * a6y - a2y * a6x;
  98639. var adx = a3y * a4z - a3z * a4y;
  98640. var ady = a3z * a4x - a3x * a4z;
  98641. var adz = a3x * a4y - a3y * a4x;
  98642. var aex = a3y * a5z - a3z * a5y;
  98643. var aey = a3z * a5x - a3x * a5z;
  98644. var aez = a3x * a5y - a3y * a5x;
  98645. var afx = a3y * a6z - a3z * a6y;
  98646. var afy = a3z * a6x - a3x * a6z;
  98647. var afz = a3x * a6y - a3y * a6x;
  98648. // right or left flags
  98649. var right1;
  98650. var right2;
  98651. var right3;
  98652. var right4;
  98653. var right5;
  98654. var right6;
  98655. var right7;
  98656. var right8;
  98657. var right9;
  98658. var righta;
  98659. var rightb;
  98660. var rightc;
  98661. var rightd;
  98662. var righte;
  98663. var rightf;
  98664. // overlapping distances
  98665. var overlap1;
  98666. var overlap2;
  98667. var overlap3;
  98668. var overlap4;
  98669. var overlap5;
  98670. var overlap6;
  98671. var overlap7;
  98672. var overlap8;
  98673. var overlap9;
  98674. var overlapa;
  98675. var overlapb;
  98676. var overlapc;
  98677. var overlapd;
  98678. var overlape;
  98679. var overlapf;
  98680. // invalid flags
  98681. var invalid7 = false;
  98682. var invalid8 = false;
  98683. var invalid9 = false;
  98684. var invalida = false;
  98685. var invalidb = false;
  98686. var invalidc = false;
  98687. var invalidd = false;
  98688. var invalide = false;
  98689. var invalidf = false;
  98690. // temporary variables
  98691. var len;
  98692. var len1;
  98693. var len2;
  98694. var dot1;
  98695. var dot2;
  98696. var dot3;
  98697. // try axis 1
  98698. len = a1x * dx + a1y * dy + a1z * dz;
  98699. right1 = len > 0;
  98700. if (!right1) len = -len;
  98701. len1 = w1;
  98702. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  98703. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  98704. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  98705. if (dot1 < 0) dot1 = -dot1;
  98706. if (dot2 < 0) dot2 = -dot2;
  98707. if (dot3 < 0) dot3 = -dot3;
  98708. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  98709. overlap1 = len - len1 - len2;
  98710. if (overlap1 > 0) return;
  98711. // try axis 2
  98712. len = a2x * dx + a2y * dy + a2z * dz;
  98713. right2 = len > 0;
  98714. if (!right2) len = -len;
  98715. len1 = h1;
  98716. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  98717. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  98718. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  98719. if (dot1 < 0) dot1 = -dot1;
  98720. if (dot2 < 0) dot2 = -dot2;
  98721. if (dot3 < 0) dot3 = -dot3;
  98722. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  98723. overlap2 = len - len1 - len2;
  98724. if (overlap2 > 0) return;
  98725. // try axis 3
  98726. len = a3x * dx + a3y * dy + a3z * dz;
  98727. right3 = len > 0;
  98728. if (!right3) len = -len;
  98729. len1 = d1;
  98730. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  98731. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  98732. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  98733. if (dot1 < 0) dot1 = -dot1;
  98734. if (dot2 < 0) dot2 = -dot2;
  98735. if (dot3 < 0) dot3 = -dot3;
  98736. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  98737. overlap3 = len - len1 - len2;
  98738. if (overlap3 > 0) return;
  98739. // try axis 4
  98740. len = a4x * dx + a4y * dy + a4z * dz;
  98741. right4 = len > 0;
  98742. if (!right4) len = -len;
  98743. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  98744. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  98745. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  98746. if (dot1 < 0) dot1 = -dot1;
  98747. if (dot2 < 0) dot2 = -dot2;
  98748. if (dot3 < 0) dot3 = -dot3;
  98749. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  98750. len2 = w2;
  98751. overlap4 = (len - len1 - len2) * 1.0;
  98752. if (overlap4 > 0) return;
  98753. // try axis 5
  98754. len = a5x * dx + a5y * dy + a5z * dz;
  98755. right5 = len > 0;
  98756. if (!right5) len = -len;
  98757. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  98758. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  98759. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  98760. if (dot1 < 0) dot1 = -dot1;
  98761. if (dot2 < 0) dot2 = -dot2;
  98762. if (dot3 < 0) dot3 = -dot3;
  98763. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  98764. len2 = h2;
  98765. overlap5 = (len - len1 - len2) * 1.0;
  98766. if (overlap5 > 0) return;
  98767. // try axis 6
  98768. len = a6x * dx + a6y * dy + a6z * dz;
  98769. right6 = len > 0;
  98770. if (!right6) len = -len;
  98771. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  98772. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  98773. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  98774. if (dot1 < 0) dot1 = -dot1;
  98775. if (dot2 < 0) dot2 = -dot2;
  98776. if (dot3 < 0) dot3 = -dot3;
  98777. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  98778. len2 = d2;
  98779. overlap6 = (len - len1 - len2) * 1.0;
  98780. if (overlap6 > 0) return;
  98781. // try axis 7
  98782. len = a7x * a7x + a7y * a7y + a7z * a7z;
  98783. if (len > 1e-5) {
  98784. len = 1 / OIMO.sqrt(len);
  98785. a7x *= len;
  98786. a7y *= len;
  98787. a7z *= len;
  98788. len = a7x * dx + a7y * dy + a7z * dz;
  98789. right7 = len > 0;
  98790. if (!right7) len = -len;
  98791. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  98792. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  98793. if (dot1 < 0) dot1 = -dot1;
  98794. if (dot2 < 0) dot2 = -dot2;
  98795. len1 = dot1 * h1 + dot2 * d1;
  98796. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  98797. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  98798. if (dot1 < 0) dot1 = -dot1;
  98799. if (dot2 < 0) dot2 = -dot2;
  98800. len2 = dot1 * h2 + dot2 * d2;
  98801. overlap7 = len - len1 - len2;
  98802. if (overlap7 > 0) return;
  98803. } else {
  98804. right7 = false;
  98805. overlap7 = 0;
  98806. invalid7 = true;
  98807. }
  98808. // try axis 8
  98809. len = a8x * a8x + a8y * a8y + a8z * a8z;
  98810. if (len > 1e-5) {
  98811. len = 1 / OIMO.sqrt(len);
  98812. a8x *= len;
  98813. a8y *= len;
  98814. a8z *= len;
  98815. len = a8x * dx + a8y * dy + a8z * dz;
  98816. right8 = len > 0;
  98817. if (!right8) len = -len;
  98818. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  98819. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  98820. if (dot1 < 0) dot1 = -dot1;
  98821. if (dot2 < 0) dot2 = -dot2;
  98822. len1 = dot1 * h1 + dot2 * d1;
  98823. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  98824. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  98825. if (dot1 < 0) dot1 = -dot1;
  98826. if (dot2 < 0) dot2 = -dot2;
  98827. len2 = dot1 * w2 + dot2 * d2;
  98828. overlap8 = len - len1 - len2;
  98829. if (overlap8 > 0) return;
  98830. } else {
  98831. right8 = false;
  98832. overlap8 = 0;
  98833. invalid8 = true;
  98834. }
  98835. // try axis 9
  98836. len = a9x * a9x + a9y * a9y + a9z * a9z;
  98837. if (len > 1e-5) {
  98838. len = 1 / OIMO.sqrt(len);
  98839. a9x *= len;
  98840. a9y *= len;
  98841. a9z *= len;
  98842. len = a9x * dx + a9y * dy + a9z * dz;
  98843. right9 = len > 0;
  98844. if (!right9) len = -len;
  98845. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  98846. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  98847. if (dot1 < 0) dot1 = -dot1;
  98848. if (dot2 < 0) dot2 = -dot2;
  98849. len1 = dot1 * h1 + dot2 * d1;
  98850. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  98851. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  98852. if (dot1 < 0) dot1 = -dot1;
  98853. if (dot2 < 0) dot2 = -dot2;
  98854. len2 = dot1 * w2 + dot2 * h2;
  98855. overlap9 = len - len1 - len2;
  98856. if (overlap9 > 0) return;
  98857. } else {
  98858. right9 = false;
  98859. overlap9 = 0;
  98860. invalid9 = true;
  98861. }
  98862. // try axis 10
  98863. len = aax * aax + aay * aay + aaz * aaz;
  98864. if (len > 1e-5) {
  98865. len = 1 / OIMO.sqrt(len);
  98866. aax *= len;
  98867. aay *= len;
  98868. aaz *= len;
  98869. len = aax * dx + aay * dy + aaz * dz;
  98870. righta = len > 0;
  98871. if (!righta) len = -len;
  98872. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  98873. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  98874. if (dot1 < 0) dot1 = -dot1;
  98875. if (dot2 < 0) dot2 = -dot2;
  98876. len1 = dot1 * w1 + dot2 * d1;
  98877. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  98878. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  98879. if (dot1 < 0) dot1 = -dot1;
  98880. if (dot2 < 0) dot2 = -dot2;
  98881. len2 = dot1 * h2 + dot2 * d2;
  98882. overlapa = len - len1 - len2;
  98883. if (overlapa > 0) return;
  98884. } else {
  98885. righta = false;
  98886. overlapa = 0;
  98887. invalida = true;
  98888. }
  98889. // try axis 11
  98890. len = abx * abx + aby * aby + abz * abz;
  98891. if (len > 1e-5) {
  98892. len = 1 / OIMO.sqrt(len);
  98893. abx *= len;
  98894. aby *= len;
  98895. abz *= len;
  98896. len = abx * dx + aby * dy + abz * dz;
  98897. rightb = len > 0;
  98898. if (!rightb) len = -len;
  98899. dot1 = abx * a1x + aby * a1y + abz * a1z;
  98900. dot2 = abx * a3x + aby * a3y + abz * a3z;
  98901. if (dot1 < 0) dot1 = -dot1;
  98902. if (dot2 < 0) dot2 = -dot2;
  98903. len1 = dot1 * w1 + dot2 * d1;
  98904. dot1 = abx * a4x + aby * a4y + abz * a4z;
  98905. dot2 = abx * a6x + aby * a6y + abz * a6z;
  98906. if (dot1 < 0) dot1 = -dot1;
  98907. if (dot2 < 0) dot2 = -dot2;
  98908. len2 = dot1 * w2 + dot2 * d2;
  98909. overlapb = len - len1 - len2;
  98910. if (overlapb > 0) return;
  98911. } else {
  98912. rightb = false;
  98913. overlapb = 0;
  98914. invalidb = true;
  98915. }
  98916. // try axis 12
  98917. len = acx * acx + acy * acy + acz * acz;
  98918. if (len > 1e-5) {
  98919. len = 1 / OIMO.sqrt(len);
  98920. acx *= len;
  98921. acy *= len;
  98922. acz *= len;
  98923. len = acx * dx + acy * dy + acz * dz;
  98924. rightc = len > 0;
  98925. if (!rightc) len = -len;
  98926. dot1 = acx * a1x + acy * a1y + acz * a1z;
  98927. dot2 = acx * a3x + acy * a3y + acz * a3z;
  98928. if (dot1 < 0) dot1 = -dot1;
  98929. if (dot2 < 0) dot2 = -dot2;
  98930. len1 = dot1 * w1 + dot2 * d1;
  98931. dot1 = acx * a4x + acy * a4y + acz * a4z;
  98932. dot2 = acx * a5x + acy * a5y + acz * a5z;
  98933. if (dot1 < 0) dot1 = -dot1;
  98934. if (dot2 < 0) dot2 = -dot2;
  98935. len2 = dot1 * w2 + dot2 * h2;
  98936. overlapc = len - len1 - len2;
  98937. if (overlapc > 0) return;
  98938. } else {
  98939. rightc = false;
  98940. overlapc = 0;
  98941. invalidc = true;
  98942. }
  98943. // try axis 13
  98944. len = adx * adx + ady * ady + adz * adz;
  98945. if (len > 1e-5) {
  98946. len = 1 / OIMO.sqrt(len);
  98947. adx *= len;
  98948. ady *= len;
  98949. adz *= len;
  98950. len = adx * dx + ady * dy + adz * dz;
  98951. rightd = len > 0;
  98952. if (!rightd) len = -len;
  98953. dot1 = adx * a1x + ady * a1y + adz * a1z;
  98954. dot2 = adx * a2x + ady * a2y + adz * a2z;
  98955. if (dot1 < 0) dot1 = -dot1;
  98956. if (dot2 < 0) dot2 = -dot2;
  98957. len1 = dot1 * w1 + dot2 * h1;
  98958. dot1 = adx * a5x + ady * a5y + adz * a5z;
  98959. dot2 = adx * a6x + ady * a6y + adz * a6z;
  98960. if (dot1 < 0) dot1 = -dot1;
  98961. if (dot2 < 0) dot2 = -dot2;
  98962. len2 = dot1 * h2 + dot2 * d2;
  98963. overlapd = len - len1 - len2;
  98964. if (overlapd > 0) return;
  98965. } else {
  98966. rightd = false;
  98967. overlapd = 0;
  98968. invalidd = true;
  98969. }
  98970. // try axis 14
  98971. len = aex * aex + aey * aey + aez * aez;
  98972. if (len > 1e-5) {
  98973. len = 1 / OIMO.sqrt(len);
  98974. aex *= len;
  98975. aey *= len;
  98976. aez *= len;
  98977. len = aex * dx + aey * dy + aez * dz;
  98978. righte = len > 0;
  98979. if (!righte) len = -len;
  98980. dot1 = aex * a1x + aey * a1y + aez * a1z;
  98981. dot2 = aex * a2x + aey * a2y + aez * a2z;
  98982. if (dot1 < 0) dot1 = -dot1;
  98983. if (dot2 < 0) dot2 = -dot2;
  98984. len1 = dot1 * w1 + dot2 * h1;
  98985. dot1 = aex * a4x + aey * a4y + aez * a4z;
  98986. dot2 = aex * a6x + aey * a6y + aez * a6z;
  98987. if (dot1 < 0) dot1 = -dot1;
  98988. if (dot2 < 0) dot2 = -dot2;
  98989. len2 = dot1 * w2 + dot2 * d2;
  98990. overlape = len - len1 - len2;
  98991. if (overlape > 0) return;
  98992. } else {
  98993. righte = false;
  98994. overlape = 0;
  98995. invalide = true;
  98996. }
  98997. // try axis 15
  98998. len = afx * afx + afy * afy + afz * afz;
  98999. if (len > 1e-5) {
  99000. len = 1 / OIMO.sqrt(len);
  99001. afx *= len;
  99002. afy *= len;
  99003. afz *= len;
  99004. len = afx * dx + afy * dy + afz * dz;
  99005. rightf = len > 0;
  99006. if (!rightf) len = -len;
  99007. dot1 = afx * a1x + afy * a1y + afz * a1z;
  99008. dot2 = afx * a2x + afy * a2y + afz * a2z;
  99009. if (dot1 < 0) dot1 = -dot1;
  99010. if (dot2 < 0) dot2 = -dot2;
  99011. len1 = dot1 * w1 + dot2 * h1;
  99012. dot1 = afx * a4x + afy * a4y + afz * a4z;
  99013. dot2 = afx * a5x + afy * a5y + afz * a5z;
  99014. if (dot1 < 0) dot1 = -dot1;
  99015. if (dot2 < 0) dot2 = -dot2;
  99016. len2 = dot1 * w2 + dot2 * h2;
  99017. overlapf = len - len1 - len2;
  99018. if (overlapf > 0) return;
  99019. } else {
  99020. rightf = false;
  99021. overlapf = 0;
  99022. invalidf = true;
  99023. }
  99024. // boxes are overlapping
  99025. var depth = overlap1;
  99026. var depth2 = overlap1;
  99027. var minIndex = 0;
  99028. var right = right1;
  99029. if (overlap2 > depth2) {
  99030. depth = overlap2;
  99031. depth2 = overlap2;
  99032. minIndex = 1;
  99033. right = right2;
  99034. }
  99035. if (overlap3 > depth2) {
  99036. depth = overlap3;
  99037. depth2 = overlap3;
  99038. minIndex = 2;
  99039. right = right3;
  99040. }
  99041. if (overlap4 > depth2) {
  99042. depth = overlap4;
  99043. depth2 = overlap4;
  99044. minIndex = 3;
  99045. right = right4;
  99046. }
  99047. if (overlap5 > depth2) {
  99048. depth = overlap5;
  99049. depth2 = overlap5;
  99050. minIndex = 4;
  99051. right = right5;
  99052. }
  99053. if (overlap6 > depth2) {
  99054. depth = overlap6;
  99055. depth2 = overlap6;
  99056. minIndex = 5;
  99057. right = right6;
  99058. }
  99059. if (overlap7 - 0.01 > depth2 && !invalid7) {
  99060. depth = overlap7;
  99061. depth2 = overlap7 - 0.01;
  99062. minIndex = 6;
  99063. right = right7;
  99064. }
  99065. if (overlap8 - 0.01 > depth2 && !invalid8) {
  99066. depth = overlap8;
  99067. depth2 = overlap8 - 0.01;
  99068. minIndex = 7;
  99069. right = right8;
  99070. }
  99071. if (overlap9 - 0.01 > depth2 && !invalid9) {
  99072. depth = overlap9;
  99073. depth2 = overlap9 - 0.01;
  99074. minIndex = 8;
  99075. right = right9;
  99076. }
  99077. if (overlapa - 0.01 > depth2 && !invalida) {
  99078. depth = overlapa;
  99079. depth2 = overlapa - 0.01;
  99080. minIndex = 9;
  99081. right = righta;
  99082. }
  99083. if (overlapb - 0.01 > depth2 && !invalidb) {
  99084. depth = overlapb;
  99085. depth2 = overlapb - 0.01;
  99086. minIndex = 10;
  99087. right = rightb;
  99088. }
  99089. if (overlapc - 0.01 > depth2 && !invalidc) {
  99090. depth = overlapc;
  99091. depth2 = overlapc - 0.01;
  99092. minIndex = 11;
  99093. right = rightc;
  99094. }
  99095. if (overlapd - 0.01 > depth2 && !invalidd) {
  99096. depth = overlapd;
  99097. depth2 = overlapd - 0.01;
  99098. minIndex = 12;
  99099. right = rightd;
  99100. }
  99101. if (overlape - 0.01 > depth2 && !invalide) {
  99102. depth = overlape;
  99103. depth2 = overlape - 0.01;
  99104. minIndex = 13;
  99105. right = righte;
  99106. }
  99107. if (overlapf - 0.01 > depth2 && !invalidf) {
  99108. depth = overlapf;
  99109. minIndex = 14;
  99110. right = rightf;
  99111. }
  99112. // normal
  99113. var nx = 0;
  99114. var ny = 0;
  99115. var nz = 0;
  99116. // edge line or face side normal
  99117. var n1x = 0;
  99118. var n1y = 0;
  99119. var n1z = 0;
  99120. var n2x = 0;
  99121. var n2y = 0;
  99122. var n2z = 0;
  99123. // center of current face
  99124. var cx = 0;
  99125. var cy = 0;
  99126. var cz = 0;
  99127. // face side
  99128. var s1x = 0;
  99129. var s1y = 0;
  99130. var s1z = 0;
  99131. var s2x = 0;
  99132. var s2y = 0;
  99133. var s2z = 0;
  99134. // swap b1 b2
  99135. var swap = false;
  99136. //_______________________________________
  99137. if (minIndex == 0) {// b1.x * b2
  99138. if (right) {
  99139. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  99140. nx = a1x; ny = a1y; nz = a1z;
  99141. } else {
  99142. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  99143. nx = -a1x; ny = -a1y; nz = -a1z;
  99144. }
  99145. s1x = d2x; s1y = d2y; s1z = d2z;
  99146. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  99147. s2x = d3x; s2y = d3y; s2z = d3z;
  99148. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99149. }
  99150. else if (minIndex == 1) {// b1.y * b2
  99151. if (right) {
  99152. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  99153. nx = a2x; ny = a2y; nz = a2z;
  99154. } else {
  99155. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  99156. nx = -a2x; ny = -a2y; nz = -a2z;
  99157. }
  99158. s1x = d1x; s1y = d1y; s1z = d1z;
  99159. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99160. s2x = d3x; s2y = d3y; s2z = d3z;
  99161. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99162. }
  99163. else if (minIndex == 2) {// b1.z * b2
  99164. if (right) {
  99165. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  99166. nx = a3x; ny = a3y; nz = a3z;
  99167. } else {
  99168. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  99169. nx = -a3x; ny = -a3y; nz = -a3z;
  99170. }
  99171. s1x = d1x; s1y = d1y; s1z = d1z;
  99172. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99173. s2x = d2x; s2y = d2y; s2z = d2z;
  99174. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  99175. }
  99176. else if (minIndex == 3) {// b2.x * b1
  99177. swap = true;
  99178. if (!right) {
  99179. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  99180. nx = a4x; ny = a4y; nz = a4z;
  99181. } else {
  99182. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  99183. nx = -a4x; ny = -a4y; nz = -a4z;
  99184. }
  99185. s1x = d5x; s1y = d5y; s1z = d5z;
  99186. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  99187. s2x = d6x; s2y = d6y; s2z = d6z;
  99188. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99189. }
  99190. else if (minIndex == 4) {// b2.y * b1
  99191. swap = true;
  99192. if (!right) {
  99193. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  99194. nx = a5x; ny = a5y; nz = a5z;
  99195. } else {
  99196. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  99197. nx = -a5x; ny = -a5y; nz = -a5z;
  99198. }
  99199. s1x = d4x; s1y = d4y; s1z = d4z;
  99200. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  99201. s2x = d6x; s2y = d6y; s2z = d6z;
  99202. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99203. }
  99204. else if (minIndex == 5) {// b2.z * b1
  99205. swap = true;
  99206. if (!right) {
  99207. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  99208. nx = a6x; ny = a6y; nz = a6z;
  99209. } else {
  99210. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  99211. nx = -a6x; ny = -a6y; nz = -a6z;
  99212. }
  99213. s1x = d4x; s1y = d4y; s1z = d4z;
  99214. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  99215. s2x = d5x; s2y = d5y; s2z = d5z;
  99216. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  99217. }
  99218. else if (minIndex == 6) {// b1.x * b2.x
  99219. nx = a7x; ny = a7y; nz = a7z;
  99220. n1x = a1x; n1y = a1y; n1z = a1z;
  99221. n2x = a4x; n2y = a4y; n2z = a4z;
  99222. }
  99223. else if (minIndex == 7) {// b1.x * b2.y
  99224. nx = a8x; ny = a8y; nz = a8z;
  99225. n1x = a1x; n1y = a1y; n1z = a1z;
  99226. n2x = a5x; n2y = a5y; n2z = a5z;
  99227. }
  99228. else if (minIndex == 8) {// b1.x * b2.z
  99229. nx = a9x; ny = a9y; nz = a9z;
  99230. n1x = a1x; n1y = a1y; n1z = a1z;
  99231. n2x = a6x; n2y = a6y; n2z = a6z;
  99232. }
  99233. else if (minIndex == 9) {// b1.y * b2.x
  99234. nx = aax; ny = aay; nz = aaz;
  99235. n1x = a2x; n1y = a2y; n1z = a2z;
  99236. n2x = a4x; n2y = a4y; n2z = a4z
  99237. }
  99238. else if (minIndex == 10) {// b1.y * b2.y
  99239. nx = abx; ny = aby; nz = abz;
  99240. n1x = a2x; n1y = a2y; n1z = a2z;
  99241. n2x = a5x; n2y = a5y; n2z = a5z;
  99242. }
  99243. else if (minIndex == 11) {// b1.y * b2.z
  99244. nx = acx; ny = acy; nz = acz;
  99245. n1x = a2x; n1y = a2y; n1z = a2z;
  99246. n2x = a6x; n2y = a6y; n2z = a6z;
  99247. }
  99248. else if (minIndex == 12) {// b1.z * b2.x
  99249. nx = adx; ny = ady; nz = adz;
  99250. n1x = a3x; n1y = a3y; n1z = a3z;
  99251. n2x = a4x; n2y = a4y; n2z = a4z;
  99252. }
  99253. else if (minIndex == 13) {// b1.z * b2.y
  99254. nx = aex; ny = aey; nz = aez;
  99255. n1x = a3x; n1y = a3y; n1z = a3z;
  99256. n2x = a5x; n2y = a5y; n2z = a5z;
  99257. }
  99258. else if (minIndex == 14) {// b1.z * b2.z
  99259. nx = afx; ny = afy; nz = afz;
  99260. n1x = a3x; n1y = a3y; n1z = a3z;
  99261. n2x = a6x; n2y = a6y; n2z = a6z;
  99262. }
  99263. //__________________________________________
  99264. var v;
  99265. if (minIndex > 5) {
  99266. if (!right) {
  99267. nx = -nx; ny = -ny; nz = -nz;
  99268. }
  99269. var distance;
  99270. var maxDistance;
  99271. var vx;
  99272. var vy;
  99273. var vz;
  99274. var v1x;
  99275. var v1y;
  99276. var v1z;
  99277. var v2x;
  99278. var v2y;
  99279. var v2z;
  99280. //vertex1;
  99281. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  99282. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  99283. //vertex2;
  99284. vx = V1[3]; vy = V1[4]; vz = V1[5];
  99285. distance = nx * vx + ny * vy + nz * vz;
  99286. if (distance > maxDistance) {
  99287. maxDistance = distance;
  99288. v1x = vx; v1y = vy; v1z = vz;
  99289. }
  99290. //vertex3;
  99291. vx = V1[6]; vy = V1[7]; vz = V1[8];
  99292. distance = nx * vx + ny * vy + nz * vz;
  99293. if (distance > maxDistance) {
  99294. maxDistance = distance;
  99295. v1x = vx; v1y = vy; v1z = vz;
  99296. }
  99297. //vertex4;
  99298. vx = V1[9]; vy = V1[10]; vz = V1[11];
  99299. distance = nx * vx + ny * vy + nz * vz;
  99300. if (distance > maxDistance) {
  99301. maxDistance = distance;
  99302. v1x = vx; v1y = vy; v1z = vz;
  99303. }
  99304. //vertex5;
  99305. vx = V1[12]; vy = V1[13]; vz = V1[14];
  99306. distance = nx * vx + ny * vy + nz * vz;
  99307. if (distance > maxDistance) {
  99308. maxDistance = distance;
  99309. v1x = vx; v1y = vy; v1z = vz;
  99310. }
  99311. //vertex6;
  99312. vx = V1[15]; vy = V1[16]; vz = V1[17];
  99313. distance = nx * vx + ny * vy + nz * vz;
  99314. if (distance > maxDistance) {
  99315. maxDistance = distance;
  99316. v1x = vx; v1y = vy; v1z = vz;
  99317. }
  99318. //vertex7;
  99319. vx = V1[18]; vy = V1[19]; vz = V1[20];
  99320. distance = nx * vx + ny * vy + nz * vz;
  99321. if (distance > maxDistance) {
  99322. maxDistance = distance;
  99323. v1x = vx; v1y = vy; v1z = vz;
  99324. }
  99325. //vertex8;
  99326. vx = V1[21]; vy = V1[22]; vz = V1[23];
  99327. distance = nx * vx + ny * vy + nz * vz;
  99328. if (distance > maxDistance) {
  99329. maxDistance = distance;
  99330. v1x = vx; v1y = vy; v1z = vz;
  99331. }
  99332. //vertex1;
  99333. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  99334. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  99335. //vertex2;
  99336. vx = V2[3]; vy = V2[4]; vz = V2[5];
  99337. distance = nx * vx + ny * vy + nz * vz;
  99338. if (distance < maxDistance) {
  99339. maxDistance = distance;
  99340. v2x = vx; v2y = vy; v2z = vz;
  99341. }
  99342. //vertex3;
  99343. vx = V2[6]; vy = V2[7]; vz = V2[8];
  99344. distance = nx * vx + ny * vy + nz * vz;
  99345. if (distance < maxDistance) {
  99346. maxDistance = distance;
  99347. v2x = vx; v2y = vy; v2z = vz;
  99348. }
  99349. //vertex4;
  99350. vx = V2[9]; vy = V2[10]; vz = V2[11];
  99351. distance = nx * vx + ny * vy + nz * vz;
  99352. if (distance < maxDistance) {
  99353. maxDistance = distance;
  99354. v2x = vx; v2y = vy; v2z = vz;
  99355. }
  99356. //vertex5;
  99357. vx = V2[12]; vy = V2[13]; vz = V2[14];
  99358. distance = nx * vx + ny * vy + nz * vz;
  99359. if (distance < maxDistance) {
  99360. maxDistance = distance;
  99361. v2x = vx; v2y = vy; v2z = vz;
  99362. }
  99363. //vertex6;
  99364. vx = V2[15]; vy = V2[16]; vz = V2[17];
  99365. distance = nx * vx + ny * vy + nz * vz;
  99366. if (distance < maxDistance) {
  99367. maxDistance = distance;
  99368. v2x = vx; v2y = vy; v2z = vz;
  99369. }
  99370. //vertex7;
  99371. vx = V2[18]; vy = V2[19]; vz = V2[20];
  99372. distance = nx * vx + ny * vy + nz * vz;
  99373. if (distance < maxDistance) {
  99374. maxDistance = distance;
  99375. v2x = vx; v2y = vy; v2z = vz;
  99376. }
  99377. //vertex8;
  99378. vx = V2[21]; vy = V2[22]; vz = V2[23];
  99379. distance = nx * vx + ny * vy + nz * vz;
  99380. if (distance < maxDistance) {
  99381. maxDistance = distance;
  99382. v2x = vx; v2y = vy; v2z = vz;
  99383. }
  99384. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  99385. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  99386. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  99387. 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);
  99388. return;
  99389. }
  99390. // now detect face-face collision...
  99391. // target quad
  99392. var q1x;
  99393. var q1y;
  99394. var q1z;
  99395. var q2x;
  99396. var q2y;
  99397. var q2z;
  99398. var q3x;
  99399. var q3y;
  99400. var q3z;
  99401. var q4x;
  99402. var q4y;
  99403. var q4z;
  99404. // search support face and vertex
  99405. var minDot = 1;
  99406. var dot = 0;
  99407. var minDotIndex = 0;
  99408. if (swap) {
  99409. dot = a1x * nx + a1y * ny + a1z * nz;
  99410. if (dot < minDot) {
  99411. minDot = dot;
  99412. minDotIndex = 0;
  99413. }
  99414. if (-dot < minDot) {
  99415. minDot = -dot;
  99416. minDotIndex = 1;
  99417. }
  99418. dot = a2x * nx + a2y * ny + a2z * nz;
  99419. if (dot < minDot) {
  99420. minDot = dot;
  99421. minDotIndex = 2;
  99422. }
  99423. if (-dot < minDot) {
  99424. minDot = -dot;
  99425. minDotIndex = 3;
  99426. }
  99427. dot = a3x * nx + a3y * ny + a3z * nz;
  99428. if (dot < minDot) {
  99429. minDot = dot;
  99430. minDotIndex = 4;
  99431. }
  99432. if (-dot < minDot) {
  99433. minDot = -dot;
  99434. minDotIndex = 5;
  99435. }
  99436. if (minDotIndex == 0) {// x+ face
  99437. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  99438. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  99439. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  99440. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  99441. }
  99442. else if (minDotIndex == 1) {// x- face
  99443. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  99444. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  99445. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  99446. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  99447. }
  99448. else if (minDotIndex == 2) {// y+ face
  99449. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  99450. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  99451. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  99452. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  99453. }
  99454. else if (minDotIndex == 3) {// y- face
  99455. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  99456. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  99457. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  99458. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  99459. }
  99460. else if (minDotIndex == 4) {// z+ face
  99461. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  99462. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  99463. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  99464. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  99465. }
  99466. else if (minDotIndex == 5) {// z- face
  99467. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  99468. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  99469. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  99470. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  99471. }
  99472. } else {
  99473. dot = a4x * nx + a4y * ny + a4z * nz;
  99474. if (dot < minDot) {
  99475. minDot = dot;
  99476. minDotIndex = 0;
  99477. }
  99478. if (-dot < minDot) {
  99479. minDot = -dot;
  99480. minDotIndex = 1;
  99481. }
  99482. dot = a5x * nx + a5y * ny + a5z * nz;
  99483. if (dot < minDot) {
  99484. minDot = dot;
  99485. minDotIndex = 2;
  99486. }
  99487. if (-dot < minDot) {
  99488. minDot = -dot;
  99489. minDotIndex = 3;
  99490. }
  99491. dot = a6x * nx + a6y * ny + a6z * nz;
  99492. if (dot < minDot) {
  99493. minDot = dot;
  99494. minDotIndex = 4;
  99495. }
  99496. if (-dot < minDot) {
  99497. minDot = -dot;
  99498. minDotIndex = 5;
  99499. }
  99500. //______________________________________________________
  99501. if (minDotIndex == 0) {// x+ face
  99502. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  99503. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  99504. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  99505. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  99506. }
  99507. else if (minDotIndex == 1) {// x- face
  99508. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  99509. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  99510. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  99511. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  99512. }
  99513. else if (minDotIndex == 2) {// y+ face
  99514. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  99515. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  99516. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  99517. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  99518. }
  99519. else if (minDotIndex == 3) {// y- face
  99520. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  99521. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  99522. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  99523. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  99524. }
  99525. else if (minDotIndex == 4) {// z+ face
  99526. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  99527. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  99528. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  99529. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  99530. }
  99531. else if (minDotIndex == 5) {// z- face
  99532. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  99533. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  99534. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  99535. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  99536. }
  99537. }
  99538. // clip vertices
  99539. var numClipVertices;
  99540. var numAddedClipVertices;
  99541. var index;
  99542. var x1;
  99543. var y1;
  99544. var z1;
  99545. var x2;
  99546. var y2;
  99547. var z2;
  99548. this.clipVertices1[0] = q1x;
  99549. this.clipVertices1[1] = q1y;
  99550. this.clipVertices1[2] = q1z;
  99551. this.clipVertices1[3] = q2x;
  99552. this.clipVertices1[4] = q2y;
  99553. this.clipVertices1[5] = q2z;
  99554. this.clipVertices1[6] = q3x;
  99555. this.clipVertices1[7] = q3y;
  99556. this.clipVertices1[8] = q3z;
  99557. this.clipVertices1[9] = q4x;
  99558. this.clipVertices1[10] = q4y;
  99559. this.clipVertices1[11] = q4z;
  99560. numAddedClipVertices = 0;
  99561. x1 = this.clipVertices1[9];
  99562. y1 = this.clipVertices1[10];
  99563. z1 = this.clipVertices1[11];
  99564. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  99565. //var i = 4;
  99566. //while(i--){
  99567. for (var i = 0; i < 4; i++) {
  99568. index = i * 3;
  99569. x2 = this.clipVertices1[index];
  99570. y2 = this.clipVertices1[index + 1];
  99571. z2 = this.clipVertices1[index + 2];
  99572. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  99573. if (dot1 > 0) {
  99574. if (dot2 > 0) {
  99575. index = numAddedClipVertices * 3;
  99576. numAddedClipVertices++;
  99577. this.clipVertices2[index] = x2;
  99578. this.clipVertices2[index + 1] = y2;
  99579. this.clipVertices2[index + 2] = z2;
  99580. } else {
  99581. index = numAddedClipVertices * 3;
  99582. numAddedClipVertices++;
  99583. t = dot1 / (dot1 - dot2);
  99584. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99585. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99586. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99587. }
  99588. } else {
  99589. if (dot2 > 0) {
  99590. index = numAddedClipVertices * 3;
  99591. numAddedClipVertices++;
  99592. t = dot1 / (dot1 - dot2);
  99593. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99594. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99595. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99596. index = numAddedClipVertices * 3;
  99597. numAddedClipVertices++;
  99598. this.clipVertices2[index] = x2;
  99599. this.clipVertices2[index + 1] = y2;
  99600. this.clipVertices2[index + 2] = z2;
  99601. }
  99602. }
  99603. x1 = x2;
  99604. y1 = y2;
  99605. z1 = z2;
  99606. dot1 = dot2;
  99607. }
  99608. numClipVertices = numAddedClipVertices;
  99609. if (numClipVertices == 0) return;
  99610. numAddedClipVertices = 0;
  99611. index = (numClipVertices - 1) * 3;
  99612. x1 = this.clipVertices2[index];
  99613. y1 = this.clipVertices2[index + 1];
  99614. z1 = this.clipVertices2[index + 2];
  99615. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  99616. //i = numClipVertices;
  99617. //while(i--){
  99618. for (i = 0; i < numClipVertices; i++) {
  99619. index = i * 3;
  99620. x2 = this.clipVertices2[index];
  99621. y2 = this.clipVertices2[index + 1];
  99622. z2 = this.clipVertices2[index + 2];
  99623. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  99624. if (dot1 > 0) {
  99625. if (dot2 > 0) {
  99626. index = numAddedClipVertices * 3;
  99627. numAddedClipVertices++;
  99628. this.clipVertices1[index] = x2;
  99629. this.clipVertices1[index + 1] = y2;
  99630. this.clipVertices1[index + 2] = z2;
  99631. } else {
  99632. index = numAddedClipVertices * 3;
  99633. numAddedClipVertices++;
  99634. t = dot1 / (dot1 - dot2);
  99635. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99636. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99637. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99638. }
  99639. } else {
  99640. if (dot2 > 0) {
  99641. index = numAddedClipVertices * 3;
  99642. numAddedClipVertices++;
  99643. t = dot1 / (dot1 - dot2);
  99644. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99645. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99646. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99647. index = numAddedClipVertices * 3;
  99648. numAddedClipVertices++;
  99649. this.clipVertices1[index] = x2;
  99650. this.clipVertices1[index + 1] = y2;
  99651. this.clipVertices1[index + 2] = z2;
  99652. }
  99653. }
  99654. x1 = x2;
  99655. y1 = y2;
  99656. z1 = z2;
  99657. dot1 = dot2;
  99658. }
  99659. numClipVertices = numAddedClipVertices;
  99660. if (numClipVertices == 0) return;
  99661. numAddedClipVertices = 0;
  99662. index = (numClipVertices - 1) * 3;
  99663. x1 = this.clipVertices1[index];
  99664. y1 = this.clipVertices1[index + 1];
  99665. z1 = this.clipVertices1[index + 2];
  99666. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  99667. //i = numClipVertices;
  99668. //while(i--){
  99669. for (i = 0; i < numClipVertices; i++) {
  99670. index = i * 3;
  99671. x2 = this.clipVertices1[index];
  99672. y2 = this.clipVertices1[index + 1];
  99673. z2 = this.clipVertices1[index + 2];
  99674. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  99675. if (dot1 > 0) {
  99676. if (dot2 > 0) {
  99677. index = numAddedClipVertices * 3;
  99678. numAddedClipVertices++;
  99679. this.clipVertices2[index] = x2;
  99680. this.clipVertices2[index + 1] = y2;
  99681. this.clipVertices2[index + 2] = z2;
  99682. } else {
  99683. index = numAddedClipVertices * 3;
  99684. numAddedClipVertices++;
  99685. t = dot1 / (dot1 - dot2);
  99686. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99687. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99688. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99689. }
  99690. } else {
  99691. if (dot2 > 0) {
  99692. index = numAddedClipVertices * 3;
  99693. numAddedClipVertices++;
  99694. t = dot1 / (dot1 - dot2);
  99695. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  99696. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  99697. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  99698. index = numAddedClipVertices * 3;
  99699. numAddedClipVertices++;
  99700. this.clipVertices2[index] = x2;
  99701. this.clipVertices2[index + 1] = y2;
  99702. this.clipVertices2[index + 2] = z2;
  99703. }
  99704. }
  99705. x1 = x2;
  99706. y1 = y2;
  99707. z1 = z2;
  99708. dot1 = dot2;
  99709. }
  99710. numClipVertices = numAddedClipVertices;
  99711. if (numClipVertices == 0) return;
  99712. numAddedClipVertices = 0;
  99713. index = (numClipVertices - 1) * 3;
  99714. x1 = this.clipVertices2[index];
  99715. y1 = this.clipVertices2[index + 1];
  99716. z1 = this.clipVertices2[index + 2];
  99717. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  99718. //i = numClipVertices;
  99719. //while(i--){
  99720. for (i = 0; i < numClipVertices; i++) {
  99721. index = i * 3;
  99722. x2 = this.clipVertices2[index];
  99723. y2 = this.clipVertices2[index + 1];
  99724. z2 = this.clipVertices2[index + 2];
  99725. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  99726. if (dot1 > 0) {
  99727. if (dot2 > 0) {
  99728. index = numAddedClipVertices * 3;
  99729. numAddedClipVertices++;
  99730. this.clipVertices1[index] = x2;
  99731. this.clipVertices1[index + 1] = y2;
  99732. this.clipVertices1[index + 2] = z2;
  99733. } else {
  99734. index = numAddedClipVertices * 3;
  99735. numAddedClipVertices++;
  99736. t = dot1 / (dot1 - dot2);
  99737. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99738. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99739. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99740. }
  99741. } else {
  99742. if (dot2 > 0) {
  99743. index = numAddedClipVertices * 3;
  99744. numAddedClipVertices++;
  99745. t = dot1 / (dot1 - dot2);
  99746. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  99747. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  99748. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  99749. index = numAddedClipVertices * 3;
  99750. numAddedClipVertices++;
  99751. this.clipVertices1[index] = x2;
  99752. this.clipVertices1[index + 1] = y2;
  99753. this.clipVertices1[index + 2] = z2;
  99754. }
  99755. }
  99756. x1 = x2;
  99757. y1 = y2;
  99758. z1 = z2;
  99759. dot1 = dot2;
  99760. }
  99761. numClipVertices = numAddedClipVertices;
  99762. if (swap) {
  99763. var tb = b1;
  99764. b1 = b2;
  99765. b2 = tb;
  99766. }
  99767. if (numClipVertices == 0) return;
  99768. var flipped = b1 != shape1;
  99769. if (numClipVertices > 4) {
  99770. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  99771. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  99772. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  99773. n1x = q1x - x1;
  99774. n1y = q1y - y1;
  99775. n1z = q1z - z1;
  99776. n2x = q2x - x1;
  99777. n2y = q2y - y1;
  99778. n2z = q2z - z1;
  99779. var index1 = 0;
  99780. var index2 = 0;
  99781. var index3 = 0;
  99782. var index4 = 0;
  99783. var maxDot = -this.INF;
  99784. minDot = this.INF;
  99785. //i = numClipVertices;
  99786. //while(i--){
  99787. for (i = 0; i < numClipVertices; i++) {
  99788. this.used[i] = false;
  99789. index = i * 3;
  99790. x1 = this.clipVertices1[index];
  99791. y1 = this.clipVertices1[index + 1];
  99792. z1 = this.clipVertices1[index + 2];
  99793. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  99794. if (dot < minDot) {
  99795. minDot = dot;
  99796. index1 = i;
  99797. }
  99798. if (dot > maxDot) {
  99799. maxDot = dot;
  99800. index3 = i;
  99801. }
  99802. }
  99803. this.used[index1] = true;
  99804. this.used[index3] = true;
  99805. maxDot = -this.INF;
  99806. minDot = this.INF;
  99807. //i = numClipVertices;
  99808. //while(i--){
  99809. for (i = 0; i < numClipVertices; i++) {
  99810. if (this.used[i]) continue;
  99811. index = i * 3;
  99812. x1 = this.clipVertices1[index];
  99813. y1 = this.clipVertices1[index + 1];
  99814. z1 = this.clipVertices1[index + 2];
  99815. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  99816. if (dot < minDot) {
  99817. minDot = dot;
  99818. index2 = i;
  99819. }
  99820. if (dot > maxDot) {
  99821. maxDot = dot;
  99822. index4 = i;
  99823. }
  99824. }
  99825. index = index1 * 3;
  99826. x1 = this.clipVertices1[index];
  99827. y1 = this.clipVertices1[index + 1];
  99828. z1 = this.clipVertices1[index + 2];
  99829. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99830. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99831. index = index2 * 3;
  99832. x1 = this.clipVertices1[index];
  99833. y1 = this.clipVertices1[index + 1];
  99834. z1 = this.clipVertices1[index + 2];
  99835. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99836. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99837. index = index3 * 3;
  99838. x1 = this.clipVertices1[index];
  99839. y1 = this.clipVertices1[index + 1];
  99840. z1 = this.clipVertices1[index + 2];
  99841. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99842. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99843. index = index4 * 3;
  99844. x1 = this.clipVertices1[index];
  99845. y1 = this.clipVertices1[index + 1];
  99846. z1 = this.clipVertices1[index + 2];
  99847. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99848. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99849. } else {
  99850. //i = numClipVertices;
  99851. //while(i--){
  99852. for (i = 0; i < numClipVertices; i++) {
  99853. index = i * 3;
  99854. x1 = this.clipVertices1[index];
  99855. y1 = this.clipVertices1[index + 1];
  99856. z1 = this.clipVertices1[index + 2];
  99857. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  99858. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  99859. }
  99860. }
  99861. };
  99862. /**
  99863. * A collision detector which detects collisions between sphere and box.
  99864. * @author saharan
  99865. */
  99866. OIMO.SphereBoxCollisionDetector = function (flip) {
  99867. OIMO.CollisionDetector.call(this);
  99868. this.flip = flip;
  99869. };
  99870. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99871. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  99872. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99873. var s;
  99874. var b;
  99875. if (this.flip) {
  99876. s = (shape2);
  99877. b = (shape1);
  99878. } else {
  99879. s = (shape1);
  99880. b = (shape2);
  99881. }
  99882. var D = b.dimentions;
  99883. var ps = s.position;
  99884. var psx = ps.x;
  99885. var psy = ps.y;
  99886. var psz = ps.z;
  99887. var pb = b.position;
  99888. var pbx = pb.x;
  99889. var pby = pb.y;
  99890. var pbz = pb.z;
  99891. var rad = s.radius;
  99892. var hw = b.halfWidth;
  99893. var hh = b.halfHeight;
  99894. var hd = b.halfDepth;
  99895. var dx = psx - pbx;
  99896. var dy = psy - pby;
  99897. var dz = psz - pbz;
  99898. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  99899. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  99900. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  99901. var cx;
  99902. var cy;
  99903. var cz;
  99904. var len;
  99905. var invLen;
  99906. var overlap = 0;
  99907. if (sx > hw) {
  99908. sx = hw;
  99909. } else if (sx < -hw) {
  99910. sx = -hw;
  99911. } else {
  99912. overlap = 1;
  99913. }
  99914. if (sy > hh) {
  99915. sy = hh;
  99916. } else if (sy < -hh) {
  99917. sy = -hh;
  99918. } else {
  99919. overlap |= 2;
  99920. }
  99921. if (sz > hd) {
  99922. sz = hd;
  99923. } else if (sz < -hd) {
  99924. sz = -hd;
  99925. } else {
  99926. overlap |= 4;
  99927. }
  99928. if (overlap == 7) {
  99929. // center of sphere is in the box
  99930. if (sx < 0) {
  99931. dx = hw + sx;
  99932. } else {
  99933. dx = hw - sx;
  99934. }
  99935. if (sy < 0) {
  99936. dy = hh + sy;
  99937. } else {
  99938. dy = hh - sy;
  99939. }
  99940. if (sz < 0) {
  99941. dz = hd + sz;
  99942. } else {
  99943. dz = hd - sz;
  99944. }
  99945. if (dx < dy) {
  99946. if (dx < dz) {
  99947. len = dx - hw;
  99948. if (sx < 0) {
  99949. sx = -hw;
  99950. dx = D[0];
  99951. dy = D[1];
  99952. dz = D[2];
  99953. } else {
  99954. sx = hw;
  99955. dx = -D[0];
  99956. dy = -D[1];
  99957. dz = -D[2];
  99958. }
  99959. } else {
  99960. len = dz - hd;
  99961. if (sz < 0) {
  99962. sz = -hd;
  99963. dx = D[6];
  99964. dy = D[7];
  99965. dz = D[8];
  99966. } else {
  99967. sz = hd;
  99968. dx = -D[6];
  99969. dy = -D[7];
  99970. dz = -D[8];
  99971. }
  99972. }
  99973. } else {
  99974. if (dy < dz) {
  99975. len = dy - hh;
  99976. if (sy < 0) {
  99977. sy = -hh;
  99978. dx = D[3];
  99979. dy = D[4];
  99980. dz = D[5];
  99981. } else {
  99982. sy = hh;
  99983. dx = -D[3];
  99984. dy = -D[4];
  99985. dz = -D[5];
  99986. }
  99987. } else {
  99988. len = dz - hd;
  99989. if (sz < 0) {
  99990. sz = -hd;
  99991. dx = D[6];
  99992. dy = D[7];
  99993. dz = D[8];
  99994. } else {
  99995. sz = hd;
  99996. dx = -D[6];
  99997. dy = -D[7];
  99998. dz = -D[8];
  99999. }
  100000. }
  100001. }
  100002. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100003. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100004. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100005. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100006. } else {
  100007. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100008. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100009. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100010. dx = cx - ps.x;
  100011. dy = cy - ps.y;
  100012. dz = cz - ps.z;
  100013. len = dx * dx + dy * dy + dz * dz;
  100014. if (len > 0 && len < rad * rad) {
  100015. len = OIMO.sqrt(len);
  100016. invLen = 1 / len;
  100017. dx *= invLen;
  100018. dy *= invLen;
  100019. dz *= invLen;
  100020. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100021. }
  100022. }
  100023. };
  100024. /**
  100025. * A collision detector which detects collisions between two spheres.
  100026. * @author saharan
  100027. */
  100028. OIMO.SphereSphereCollisionDetector = function () {
  100029. OIMO.CollisionDetector.call(this);
  100030. };
  100031. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100032. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  100033. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100034. var s1 = shape1;
  100035. var s2 = shape2;
  100036. var p1 = s1.position;
  100037. var p2 = s2.position;
  100038. var dx = p2.x - p1.x;
  100039. var dy = p2.y - p1.y;
  100040. var dz = p2.z - p1.z;
  100041. var len = dx * dx + dy * dy + dz * dz;
  100042. var r1 = s1.radius;
  100043. var r2 = s2.radius;
  100044. var rad = r1 + r2;
  100045. if (len > 0 && len < rad * rad) {
  100046. len = OIMO.sqrt(len);
  100047. var invLen = 1 / len;
  100048. dx *= invLen;
  100049. dy *= invLen;
  100050. dz *= invLen;
  100051. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  100052. }
  100053. };
  100054. OIMO.BoxCylinderCollisionDetector = function (flip) {
  100055. OIMO.CollisionDetector.call(this);
  100056. this.flip = flip;
  100057. };
  100058. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100059. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  100060. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  100061. var t1x;
  100062. var t1y;
  100063. var t1z;
  100064. var t2x;
  100065. var t2y;
  100066. var t2z;
  100067. var sup = new OIMO.Vec3();
  100068. var len;
  100069. var p1x;
  100070. var p1y;
  100071. var p1z;
  100072. var p2x;
  100073. var p2y;
  100074. var p2z;
  100075. var v01x = c1.position.x;
  100076. var v01y = c1.position.y;
  100077. var v01z = c1.position.z;
  100078. var v02x = c2.position.x;
  100079. var v02y = c2.position.y;
  100080. var v02z = c2.position.z;
  100081. var v0x = v02x - v01x;
  100082. var v0y = v02y - v01y;
  100083. var v0z = v02z - v01z;
  100084. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  100085. var nx = -v0x;
  100086. var ny = -v0y;
  100087. var nz = -v0z;
  100088. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100089. var v11x = sup.x;
  100090. var v11y = sup.y;
  100091. var v11z = sup.z;
  100092. this.supportPointC(c2, nx, ny, nz, sup);
  100093. var v12x = sup.x;
  100094. var v12y = sup.y;
  100095. var v12z = sup.z;
  100096. var v1x = v12x - v11x;
  100097. var v1y = v12y - v11y;
  100098. var v1z = v12z - v11z;
  100099. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  100100. return false;
  100101. }
  100102. nx = v1y * v0z - v1z * v0y;
  100103. ny = v1z * v0x - v1x * v0z;
  100104. nz = v1x * v0y - v1y * v0x;
  100105. if (nx * nx + ny * ny + nz * nz == 0) {
  100106. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  100107. sep.normalize(sep);
  100108. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  100109. return true;
  100110. }
  100111. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100112. var v21x = sup.x;
  100113. var v21y = sup.y;
  100114. var v21z = sup.z;
  100115. this.supportPointC(c2, nx, ny, nz, sup);
  100116. var v22x = sup.x;
  100117. var v22y = sup.y;
  100118. var v22z = sup.z;
  100119. var v2x = v22x - v21x;
  100120. var v2y = v22y - v21y;
  100121. var v2z = v22z - v21z;
  100122. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  100123. return false;
  100124. }
  100125. t1x = v1x - v0x;
  100126. t1y = v1y - v0y;
  100127. t1z = v1z - v0z;
  100128. t2x = v2x - v0x;
  100129. t2y = v2y - v0y;
  100130. t2z = v2z - v0z;
  100131. nx = t1y * t2z - t1z * t2y;
  100132. ny = t1z * t2x - t1x * t2z;
  100133. nz = t1x * t2y - t1y * t2x;
  100134. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  100135. t1x = v1x;
  100136. t1y = v1y;
  100137. t1z = v1z;
  100138. v1x = v2x;
  100139. v1y = v2y;
  100140. v1z = v2z;
  100141. v2x = t1x;
  100142. v2y = t1y;
  100143. v2z = t1z;
  100144. t1x = v11x;
  100145. t1y = v11y;
  100146. t1z = v11z;
  100147. v11x = v21x;
  100148. v11y = v21y;
  100149. v11z = v21z;
  100150. v21x = t1x;
  100151. v21y = t1y;
  100152. v21z = t1z;
  100153. t1x = v12x;
  100154. t1y = v12y;
  100155. t1z = v12z;
  100156. v12x = v22x;
  100157. v12y = v22y;
  100158. v12z = v22z;
  100159. v22x = t1x;
  100160. v22y = t1y;
  100161. v22z = t1z;
  100162. nx = -nx;
  100163. ny = -ny;
  100164. nz = -nz;
  100165. }
  100166. var iterations = 0;
  100167. while (true) {
  100168. if (++iterations > 100) {
  100169. return false;
  100170. }
  100171. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100172. var v31x = sup.x;
  100173. var v31y = sup.y;
  100174. var v31z = sup.z;
  100175. this.supportPointC(c2, nx, ny, nz, sup);
  100176. var v32x = sup.x;
  100177. var v32y = sup.y;
  100178. var v32z = sup.z;
  100179. var v3x = v32x - v31x;
  100180. var v3y = v32y - v31y;
  100181. var v3z = v32z - v31z;
  100182. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  100183. return false;
  100184. }
  100185. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  100186. v2x = v3x;
  100187. v2y = v3y;
  100188. v2z = v3z;
  100189. v21x = v31x;
  100190. v21y = v31y;
  100191. v21z = v31z;
  100192. v22x = v32x;
  100193. v22y = v32y;
  100194. v22z = v32z;
  100195. t1x = v1x - v0x;
  100196. t1y = v1y - v0y;
  100197. t1z = v1z - v0z;
  100198. t2x = v3x - v0x;
  100199. t2y = v3y - v0y;
  100200. t2z = v3z - v0z;
  100201. nx = t1y * t2z - t1z * t2y;
  100202. ny = t1z * t2x - t1x * t2z;
  100203. nz = t1x * t2y - t1y * t2x;
  100204. continue;
  100205. }
  100206. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  100207. v1x = v3x;
  100208. v1y = v3y;
  100209. v1z = v3z;
  100210. v11x = v31x;
  100211. v11y = v31y;
  100212. v11z = v31z;
  100213. v12x = v32x;
  100214. v12y = v32y;
  100215. v12z = v32z;
  100216. t1x = v3x - v0x;
  100217. t1y = v3y - v0y;
  100218. t1z = v3z - v0z;
  100219. t2x = v2x - v0x;
  100220. t2y = v2y - v0y;
  100221. t2z = v2z - v0z;
  100222. nx = t1y * t2z - t1z * t2y;
  100223. ny = t1z * t2x - t1x * t2z;
  100224. nz = t1x * t2y - t1y * t2x;
  100225. continue;
  100226. }
  100227. var hit = false;
  100228. while (true) {
  100229. t1x = v2x - v1x;
  100230. t1y = v2y - v1y;
  100231. t1z = v2z - v1z;
  100232. t2x = v3x - v1x;
  100233. t2y = v3y - v1y;
  100234. t2z = v3z - v1z;
  100235. nx = t1y * t2z - t1z * t2y;
  100236. ny = t1z * t2x - t1x * t2z;
  100237. nz = t1x * t2y - t1y * t2x;
  100238. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  100239. nx *= len;
  100240. ny *= len;
  100241. nz *= len;
  100242. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  100243. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  100244. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  100245. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  100246. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  100247. var sum = b0 + b1 + b2 + b3;
  100248. if (sum <= 0) {
  100249. b0 = 0;
  100250. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  100251. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  100252. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  100253. sum = b1 + b2 + b3;
  100254. }
  100255. var inv = 1 / sum;
  100256. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  100257. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  100258. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  100259. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  100260. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  100261. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  100262. hit = true;
  100263. }
  100264. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100265. var v41x = sup.x;
  100266. var v41y = sup.y;
  100267. var v41z = sup.z;
  100268. this.supportPointC(c2, nx, ny, nz, sup);
  100269. var v42x = sup.x;
  100270. var v42y = sup.y;
  100271. var v42z = sup.z;
  100272. var v4x = v42x - v41x;
  100273. var v4y = v42y - v41y;
  100274. var v4z = v42z - v41z;
  100275. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  100276. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  100277. if (hit) {
  100278. sep.init(-nx, -ny, -nz);
  100279. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  100280. dep.x = separation;
  100281. return true;
  100282. }
  100283. return false;
  100284. }
  100285. if (
  100286. (v4y * v1z - v4z * v1y) * v0x +
  100287. (v4z * v1x - v4x * v1z) * v0y +
  100288. (v4x * v1y - v4y * v1x) * v0z < 0
  100289. ) {
  100290. if (
  100291. (v4y * v2z - v4z * v2y) * v0x +
  100292. (v4z * v2x - v4x * v2z) * v0y +
  100293. (v4x * v2y - v4y * v2x) * v0z < 0
  100294. ) {
  100295. v1x = v4x;
  100296. v1y = v4y;
  100297. v1z = v4z;
  100298. v11x = v41x;
  100299. v11y = v41y;
  100300. v11z = v41z;
  100301. v12x = v42x;
  100302. v12y = v42y;
  100303. v12z = v42z;
  100304. } else {
  100305. v3x = v4x;
  100306. v3y = v4y;
  100307. v3z = v4z;
  100308. v31x = v41x;
  100309. v31y = v41y;
  100310. v31z = v41z;
  100311. v32x = v42x;
  100312. v32y = v42y;
  100313. v32z = v42z;
  100314. }
  100315. } else {
  100316. if (
  100317. (v4y * v3z - v4z * v3y) * v0x +
  100318. (v4z * v3x - v4x * v3z) * v0y +
  100319. (v4x * v3y - v4y * v3x) * v0z < 0
  100320. ) {
  100321. v2x = v4x;
  100322. v2y = v4y;
  100323. v2z = v4z;
  100324. v21x = v41x;
  100325. v21y = v41y;
  100326. v21z = v41z;
  100327. v22x = v42x;
  100328. v22y = v42y;
  100329. v22z = v42z;
  100330. } else {
  100331. v1x = v4x;
  100332. v1y = v4y;
  100333. v1z = v4z;
  100334. v11x = v41x;
  100335. v11y = v41y;
  100336. v11z = v41z;
  100337. v12x = v42x;
  100338. v12y = v42y;
  100339. v12z = v42z;
  100340. }
  100341. }
  100342. }
  100343. }
  100344. //return false;
  100345. };
  100346. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  100347. var rot = c.rotation.elements;
  100348. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100349. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100350. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100351. var w = c.halfWidth;
  100352. var h = c.halfHeight;
  100353. var d = c.halfDepth;
  100354. var ox;
  100355. var oy;
  100356. var oz;
  100357. if (ldx < 0) ox = -w;
  100358. else ox = w;
  100359. if (ldy < 0) oy = -h;
  100360. else oy = h;
  100361. if (ldz < 0) oz = -d;
  100362. else oz = d;
  100363. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100364. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100365. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100366. out.init(ldx, ldy, ldz);
  100367. };
  100368. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  100369. var rot = c.rotation.elements;
  100370. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100371. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100372. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100373. var radx = ldx;
  100374. var radz = ldz;
  100375. var len = radx * radx + radz * radz;
  100376. var rad = c.radius;
  100377. var hh = c.halfHeight;
  100378. var ox;
  100379. var oy;
  100380. var oz;
  100381. if (len == 0) {
  100382. if (ldy < 0) {
  100383. ox = rad;
  100384. oy = -hh;
  100385. oz = 0;
  100386. } else {
  100387. ox = rad;
  100388. oy = hh;
  100389. oz = 0;
  100390. }
  100391. } else {
  100392. len = c.radius / OIMO.sqrt(len);
  100393. if (ldy < 0) {
  100394. ox = radx * len;
  100395. oy = -hh;
  100396. oz = radz * len;
  100397. } else {
  100398. ox = radx * len;
  100399. oy = hh;
  100400. oz = radz * len;
  100401. }
  100402. }
  100403. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100404. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100405. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100406. out.init(ldx, ldy, ldz);
  100407. };
  100408. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100409. var b;
  100410. var c;
  100411. if (this.flip) {
  100412. b = shape2;
  100413. c = shape1;
  100414. } else {
  100415. b = shape1;
  100416. c = shape2;
  100417. }
  100418. var sep = new OIMO.Vec3();
  100419. var pos = new OIMO.Vec3();
  100420. var dep = new OIMO.Vec3();
  100421. var co;
  100422. if (!this.getSep(b, c, sep, pos, dep)) return;
  100423. var pbx = b.position.x;
  100424. var pby = b.position.y;
  100425. var pbz = b.position.z;
  100426. var pcx = c.position.x;
  100427. var pcy = c.position.y;
  100428. var pcz = c.position.z;
  100429. var bw = b.halfWidth;
  100430. var bh = b.halfHeight;
  100431. var bd = b.halfDepth;
  100432. var ch = c.halfHeight;
  100433. var r = c.radius;
  100434. var D = b.dimentions;
  100435. var nwx = D[0];//b.normalDirectionWidth.x;
  100436. var nwy = D[1];//b.normalDirectionWidth.y;
  100437. var nwz = D[2];//b.normalDirectionWidth.z;
  100438. var nhx = D[3];//b.normalDirectionHeight.x;
  100439. var nhy = D[4];//b.normalDirectionHeight.y;
  100440. var nhz = D[5];//b.normalDirectionHeight.z;
  100441. var ndx = D[6];//b.normalDirectionDepth.x;
  100442. var ndy = D[7];//b.normalDirectionDepth.y;
  100443. var ndz = D[8];//b.normalDirectionDepth.z;
  100444. var dwx = D[9];//b.halfDirectionWidth.x;
  100445. var dwy = D[10];//b.halfDirectionWidth.y;
  100446. var dwz = D[11];//b.halfDirectionWidth.z;
  100447. var dhx = D[12];//b.halfDirectionHeight.x;
  100448. var dhy = D[13];//b.halfDirectionHeight.y;
  100449. var dhz = D[14];//b.halfDirectionHeight.z;
  100450. var ddx = D[15];//b.halfDirectionDepth.x;
  100451. var ddy = D[16];//b.halfDirectionDepth.y;
  100452. var ddz = D[17];//b.halfDirectionDepth.z;
  100453. var ncx = c.normalDirection.x;
  100454. var ncy = c.normalDirection.y;
  100455. var ncz = c.normalDirection.z;
  100456. var dcx = c.halfDirection.x;
  100457. var dcy = c.halfDirection.y;
  100458. var dcz = c.halfDirection.z;
  100459. var nx = sep.x;
  100460. var ny = sep.y;
  100461. var nz = sep.z;
  100462. var dotw = nx * nwx + ny * nwy + nz * nwz;
  100463. var doth = nx * nhx + ny * nhy + nz * nhz;
  100464. var dotd = nx * ndx + ny * ndy + nz * ndz;
  100465. var dotc = nx * ncx + ny * ncy + nz * ncz;
  100466. var right1 = dotw > 0;
  100467. var right2 = doth > 0;
  100468. var right3 = dotd > 0;
  100469. var right4 = dotc > 0;
  100470. if (!right1) dotw = -dotw;
  100471. if (!right2) doth = -doth;
  100472. if (!right3) dotd = -dotd;
  100473. if (!right4) dotc = -dotc;
  100474. var state = 0;
  100475. if (dotc > 0.999) {
  100476. if (dotw > 0.999) {
  100477. if (dotw > dotc) state = 1;
  100478. else state = 4;
  100479. } else if (doth > 0.999) {
  100480. if (doth > dotc) state = 2;
  100481. else state = 4;
  100482. } else if (dotd > 0.999) {
  100483. if (dotd > dotc) state = 3;
  100484. else state = 4;
  100485. } else state = 4;
  100486. } else {
  100487. if (dotw > 0.999) state = 1;
  100488. else if (doth > 0.999) state = 2;
  100489. else if (dotd > 0.999) state = 3;
  100490. }
  100491. var cbx;
  100492. var cby;
  100493. var cbz;
  100494. var ccx;
  100495. var ccy;
  100496. var ccz;
  100497. var r00;
  100498. var r01;
  100499. var r02;
  100500. var r10;
  100501. var r11;
  100502. var r12;
  100503. var r20;
  100504. var r21;
  100505. var r22;
  100506. var px;
  100507. var py;
  100508. var pz;
  100509. var pd;
  100510. var dot;
  100511. var len;
  100512. var tx;
  100513. var ty;
  100514. var tz;
  100515. var td;
  100516. var dx;
  100517. var dy;
  100518. var dz;
  100519. var d1x;
  100520. var d1y;
  100521. var d1z;
  100522. var d2x;
  100523. var d2y;
  100524. var d2z;
  100525. var sx;
  100526. var sy;
  100527. var sz;
  100528. var sd;
  100529. var ex;
  100530. var ey;
  100531. var ez;
  100532. var ed;
  100533. var dot1;
  100534. var dot2;
  100535. var t1;
  100536. var t2;
  100537. var dir1x;
  100538. var dir1y;
  100539. var dir1z;
  100540. var dir2x;
  100541. var dir2y;
  100542. var dir2z;
  100543. var dir1l;
  100544. var dir2l;
  100545. if (state == 0) {
  100546. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  100547. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  100548. } else if (state == 4) {
  100549. if (right4) {
  100550. ccx = pcx - dcx;
  100551. ccy = pcy - dcy;
  100552. ccz = pcz - dcz;
  100553. nx = -ncx;
  100554. ny = -ncy;
  100555. nz = -ncz;
  100556. } else {
  100557. ccx = pcx + dcx;
  100558. ccy = pcy + dcy;
  100559. ccz = pcz + dcz;
  100560. nx = ncx;
  100561. ny = ncy;
  100562. nz = ncz;
  100563. }
  100564. var v1x;
  100565. var v1y;
  100566. var v1z;
  100567. var v2x;
  100568. var v2y;
  100569. var v2z;
  100570. var v3x;
  100571. var v3y;
  100572. var v3z;
  100573. var v4x;
  100574. var v4y;
  100575. var v4z;
  100576. dot = 1;
  100577. state = 0;
  100578. dot1 = nwx * nx + nwy * ny + nwz * nz;
  100579. if (dot1 < dot) {
  100580. dot = dot1;
  100581. state = 0;
  100582. }
  100583. if (-dot1 < dot) {
  100584. dot = -dot1;
  100585. state = 1;
  100586. }
  100587. dot1 = nhx * nx + nhy * ny + nhz * nz;
  100588. if (dot1 < dot) {
  100589. dot = dot1;
  100590. state = 2;
  100591. }
  100592. if (-dot1 < dot) {
  100593. dot = -dot1;
  100594. state = 3;
  100595. }
  100596. dot1 = ndx * nx + ndy * ny + ndz * nz;
  100597. if (dot1 < dot) {
  100598. dot = dot1;
  100599. state = 4;
  100600. }
  100601. if (-dot1 < dot) {
  100602. dot = -dot1;
  100603. state = 5;
  100604. }
  100605. var v = b.elements;
  100606. switch (state) {
  100607. case 0:
  100608. //v=b.vertex1;
  100609. v1x = v[0];//v.x;
  100610. v1y = v[1];//v.y;
  100611. v1z = v[2];//v.z;
  100612. //v=b.vertex3;
  100613. v2x = v[6];//v.x;
  100614. v2y = v[7];//v.y;
  100615. v2z = v[8];//v.z;
  100616. //v=b.vertex4;
  100617. v3x = v[9];//v.x;
  100618. v3y = v[10];//v.y;
  100619. v3z = v[11];//v.z;
  100620. //v=b.vertex2;
  100621. v4x = v[3];//v.x;
  100622. v4y = v[4];//v.y;
  100623. v4z = v[5];//v.z;
  100624. break;
  100625. case 1:
  100626. //v=b.vertex6;
  100627. v1x = v[15];//v.x;
  100628. v1y = v[16];//v.y;
  100629. v1z = v[17];//v.z;
  100630. //v=b.vertex8;
  100631. v2x = v[21];//v.x;
  100632. v2y = v[22];//v.y;
  100633. v2z = v[23];//v.z;
  100634. //v=b.vertex7;
  100635. v3x = v[18];//v.x;
  100636. v3y = v[19];//v.y;
  100637. v3z = v[20];//v.z;
  100638. //v=b.vertex5;
  100639. v4x = v[12];//v.x;
  100640. v4y = v[13];//v.y;
  100641. v4z = v[14];//v.z;
  100642. break;
  100643. case 2:
  100644. //v=b.vertex5;
  100645. v1x = v[12];//v.x;
  100646. v1y = v[13];//v.y;
  100647. v1z = v[14];//v.z;
  100648. //v=b.vertex1;
  100649. v2x = v[0];//v.x;
  100650. v2y = v[1];//v.y;
  100651. v2z = v[2];//v.z;
  100652. //v=b.vertex2;
  100653. v3x = v[3];//v.x;
  100654. v3y = v[4];//v.y;
  100655. v3z = v[5];//v.z;
  100656. //v=b.vertex6;
  100657. v4x = v[15];//v.x;
  100658. v4y = v[16];//v.y;
  100659. v4z = v[17];//v.z;
  100660. break;
  100661. case 3:
  100662. //v=b.vertex8;
  100663. v1x = v[21];//v.x;
  100664. v1y = v[22];//v.y;
  100665. v1z = v[23];//v.z;
  100666. //v=b.vertex4;
  100667. v2x = v[9];//v.x;
  100668. v2y = v[10];//v.y;
  100669. v2z = v[11];//v.z;
  100670. //v=b.vertex3;
  100671. v3x = v[6];//v.x;
  100672. v3y = v[7];//v.y;
  100673. v3z = v[8];//v.z;
  100674. //v=b.vertex7;
  100675. v4x = v[18];//v.x;
  100676. v4y = v[19];//v.y;
  100677. v4z = v[20];//v.z;
  100678. break;
  100679. case 4:
  100680. //v=b.vertex5;
  100681. v1x = v[12];//v.x;
  100682. v1y = v[13];//v.y;
  100683. v1z = v[14];//v.z;
  100684. //v=b.vertex7;
  100685. v2x = v[18];//v.x;
  100686. v2y = v[19];//v.y;
  100687. v2z = v[20];//v.z;
  100688. //v=b.vertex3;
  100689. v3x = v[6];//v.x;
  100690. v3y = v[7];//v.y;
  100691. v3z = v[8];//v.z;
  100692. //v=b.vertex1;
  100693. v4x = v[0];//v.x;
  100694. v4y = v[1];//v.y;
  100695. v4z = v[2];//v.z;
  100696. break;
  100697. case 5:
  100698. //v=b.vertex2;
  100699. v1x = v[3];//v.x;
  100700. v1y = v[4];//v.y;
  100701. v1z = v[5];//v.z;
  100702. //v=b.vertex4;
  100703. v2x = v[9];//v.x;
  100704. v2y = v[10];//v.y;
  100705. v2z = v[11];//v.z;
  100706. //v=b.vertex8;
  100707. v3x = v[21];//v.x;
  100708. v3y = v[22];//v.y;
  100709. v3z = v[23];//v.z;
  100710. //v=b.vertex6;
  100711. v4x = v[15];//v.x;
  100712. v4y = v[16];//v.y;
  100713. v4z = v[17];//v.z;
  100714. break;
  100715. }
  100716. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  100717. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  100718. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  100719. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  100720. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  100721. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  100722. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  100723. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  100724. } else {
  100725. switch (state) {
  100726. case 1:
  100727. if (right1) {
  100728. cbx = pbx + dwx;
  100729. cby = pby + dwy;
  100730. cbz = pbz + dwz;
  100731. nx = nwx;
  100732. ny = nwy;
  100733. nz = nwz;
  100734. } else {
  100735. cbx = pbx - dwx;
  100736. cby = pby - dwy;
  100737. cbz = pbz - dwz;
  100738. nx = -nwx;
  100739. ny = -nwy;
  100740. nz = -nwz;
  100741. }
  100742. dir1x = nhx;
  100743. dir1y = nhy;
  100744. dir1z = nhz;
  100745. dir1l = bh;
  100746. dir2x = ndx;
  100747. dir2y = ndy;
  100748. dir2z = ndz;
  100749. dir2l = bd;
  100750. break;
  100751. case 2:
  100752. if (right2) {
  100753. cbx = pbx + dhx;
  100754. cby = pby + dhy;
  100755. cbz = pbz + dhz;
  100756. nx = nhx;
  100757. ny = nhy;
  100758. nz = nhz;
  100759. } else {
  100760. cbx = pbx - dhx;
  100761. cby = pby - dhy;
  100762. cbz = pbz - dhz;
  100763. nx = -nhx;
  100764. ny = -nhy;
  100765. nz = -nhz;
  100766. }
  100767. dir1x = nwx;
  100768. dir1y = nwy;
  100769. dir1z = nwz;
  100770. dir1l = bw;
  100771. dir2x = ndx;
  100772. dir2y = ndy;
  100773. dir2z = ndz;
  100774. dir2l = bd;
  100775. break;
  100776. case 3:
  100777. if (right3) {
  100778. cbx = pbx + ddx;
  100779. cby = pby + ddy;
  100780. cbz = pbz + ddz;
  100781. nx = ndx;
  100782. ny = ndy;
  100783. nz = ndz;
  100784. } else {
  100785. cbx = pbx - ddx;
  100786. cby = pby - ddy;
  100787. cbz = pbz - ddz;
  100788. nx = -ndx;
  100789. ny = -ndy;
  100790. nz = -ndz;
  100791. }
  100792. dir1x = nwx;
  100793. dir1y = nwy;
  100794. dir1z = nwz;
  100795. dir1l = bw;
  100796. dir2x = nhx;
  100797. dir2y = nhy;
  100798. dir2z = nhz;
  100799. dir2l = bh;
  100800. break;
  100801. }
  100802. dot = nx * ncx + ny * ncy + nz * ncz;
  100803. if (dot < 0) len = ch;
  100804. else len = -ch;
  100805. ccx = pcx + len * ncx;
  100806. ccy = pcy + len * ncy;
  100807. ccz = pcz + len * ncz;
  100808. if (dotc >= 0.999999) {
  100809. tx = -ny;
  100810. ty = nz;
  100811. tz = nx;
  100812. } else {
  100813. tx = nx;
  100814. ty = ny;
  100815. tz = nz;
  100816. }
  100817. len = tx * ncx + ty * ncy + tz * ncz;
  100818. dx = len * ncx - tx;
  100819. dy = len * ncy - ty;
  100820. dz = len * ncz - tz;
  100821. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  100822. if (len == 0) return;
  100823. len = r / len;
  100824. dx *= len;
  100825. dy *= len;
  100826. dz *= len;
  100827. tx = ccx + dx;
  100828. ty = ccy + dy;
  100829. tz = ccz + dz;
  100830. if (dot < -0.96 || dot > 0.96) {
  100831. r00 = ncx * ncx * 1.5 - 0.5;
  100832. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  100833. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  100834. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  100835. r11 = ncy * ncy * 1.5 - 0.5;
  100836. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  100837. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  100838. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  100839. r22 = ncz * ncz * 1.5 - 0.5;
  100840. px = tx;
  100841. py = ty;
  100842. pz = tz;
  100843. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  100844. tx = px - pd * nx - cbx;
  100845. ty = py - pd * ny - cby;
  100846. tz = pz - pd * nz - cbz;
  100847. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  100848. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  100849. if (sd < -dir1l) sd = -dir1l;
  100850. else if (sd > dir1l) sd = dir1l;
  100851. if (ed < -dir2l) ed = -dir2l;
  100852. else if (ed > dir2l) ed = dir2l;
  100853. tx = sd * dir1x + ed * dir2x;
  100854. ty = sd * dir1y + ed * dir2y;
  100855. tz = sd * dir1z + ed * dir2z;
  100856. px = cbx + tx;
  100857. py = cby + ty;
  100858. pz = cbz + tz;
  100859. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  100860. px = dx * r00 + dy * r01 + dz * r02;
  100861. py = dx * r10 + dy * r11 + dz * r12;
  100862. pz = dx * r20 + dy * r21 + dz * r22;
  100863. px = (dx = px) + ccx;
  100864. py = (dy = py) + ccy;
  100865. pz = (dz = pz) + ccz;
  100866. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  100867. if (pd <= 0) {
  100868. tx = px - pd * nx - cbx;
  100869. ty = py - pd * ny - cby;
  100870. tz = pz - pd * nz - cbz;
  100871. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  100872. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  100873. if (sd < -dir1l) sd = -dir1l;
  100874. else if (sd > dir1l) sd = dir1l;
  100875. if (ed < -dir2l) ed = -dir2l;
  100876. else if (ed > dir2l) ed = dir2l;
  100877. tx = sd * dir1x + ed * dir2x;
  100878. ty = sd * dir1y + ed * dir2y;
  100879. tz = sd * dir1z + ed * dir2z;
  100880. px = cbx + tx;
  100881. py = cby + ty;
  100882. pz = cbz + tz;
  100883. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  100884. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  100885. }
  100886. px = dx * r00 + dy * r01 + dz * r02;
  100887. py = dx * r10 + dy * r11 + dz * r12;
  100888. pz = dx * r20 + dy * r21 + dz * r22;
  100889. px = (dx = px) + ccx;
  100890. py = (dy = py) + ccy;
  100891. pz = (dz = pz) + ccz;
  100892. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  100893. if (pd <= 0) {
  100894. tx = px - pd * nx - cbx;
  100895. ty = py - pd * ny - cby;
  100896. tz = pz - pd * nz - cbz;
  100897. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  100898. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  100899. if (sd < -dir1l) sd = -dir1l;
  100900. else if (sd > dir1l) sd = dir1l;
  100901. if (ed < -dir2l) ed = -dir2l;
  100902. else if (ed > dir2l) ed = dir2l;
  100903. tx = sd * dir1x + ed * dir2x;
  100904. ty = sd * dir1y + ed * dir2y;
  100905. tz = sd * dir1z + ed * dir2z;
  100906. px = cbx + tx;
  100907. py = cby + ty;
  100908. pz = cbz + tz;
  100909. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  100910. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  100911. }
  100912. } else {
  100913. sx = tx;
  100914. sy = ty;
  100915. sz = tz;
  100916. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  100917. sx -= sd * nx;
  100918. sy -= sd * ny;
  100919. sz -= sd * nz;
  100920. if (dot > 0) {
  100921. ex = tx + dcx * 2;
  100922. ey = ty + dcy * 2;
  100923. ez = tz + dcz * 2;
  100924. } else {
  100925. ex = tx - dcx * 2;
  100926. ey = ty - dcy * 2;
  100927. ez = tz - dcz * 2;
  100928. }
  100929. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  100930. ex -= ed * nx;
  100931. ey -= ed * ny;
  100932. ez -= ed * nz;
  100933. d1x = sx - cbx;
  100934. d1y = sy - cby;
  100935. d1z = sz - cbz;
  100936. d2x = ex - cbx;
  100937. d2y = ey - cby;
  100938. d2z = ez - cbz;
  100939. tx = ex - sx;
  100940. ty = ey - sy;
  100941. tz = ez - sz;
  100942. td = ed - sd;
  100943. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  100944. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  100945. dot1 = dotw - dir1l;
  100946. dot2 = doth - dir1l;
  100947. if (dot1 > 0) {
  100948. if (dot2 > 0) return;
  100949. t1 = dot1 / (dot1 - dot2);
  100950. sx = sx + tx * t1;
  100951. sy = sy + ty * t1;
  100952. sz = sz + tz * t1;
  100953. sd = sd + td * t1;
  100954. d1x = sx - cbx;
  100955. d1y = sy - cby;
  100956. d1z = sz - cbz;
  100957. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  100958. tx = ex - sx;
  100959. ty = ey - sy;
  100960. tz = ez - sz;
  100961. td = ed - sd;
  100962. } else if (dot2 > 0) {
  100963. t1 = dot1 / (dot1 - dot2);
  100964. ex = sx + tx * t1;
  100965. ey = sy + ty * t1;
  100966. ez = sz + tz * t1;
  100967. ed = sd + td * t1;
  100968. d2x = ex - cbx;
  100969. d2y = ey - cby;
  100970. d2z = ez - cbz;
  100971. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  100972. tx = ex - sx;
  100973. ty = ey - sy;
  100974. tz = ez - sz;
  100975. td = ed - sd;
  100976. }
  100977. dot1 = dotw + dir1l;
  100978. dot2 = doth + dir1l;
  100979. if (dot1 < 0) {
  100980. if (dot2 < 0) return;
  100981. t1 = dot1 / (dot1 - dot2);
  100982. sx = sx + tx * t1;
  100983. sy = sy + ty * t1;
  100984. sz = sz + tz * t1;
  100985. sd = sd + td * t1;
  100986. d1x = sx - cbx;
  100987. d1y = sy - cby;
  100988. d1z = sz - cbz;
  100989. tx = ex - sx;
  100990. ty = ey - sy;
  100991. tz = ez - sz;
  100992. td = ed - sd;
  100993. } else if (dot2 < 0) {
  100994. t1 = dot1 / (dot1 - dot2);
  100995. ex = sx + tx * t1;
  100996. ey = sy + ty * t1;
  100997. ez = sz + tz * t1;
  100998. ed = sd + td * t1;
  100999. d2x = ex - cbx;
  101000. d2y = ey - cby;
  101001. d2z = ez - cbz;
  101002. tx = ex - sx;
  101003. ty = ey - sy;
  101004. tz = ez - sz;
  101005. td = ed - sd;
  101006. }
  101007. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101008. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101009. dot1 = dotw - dir2l;
  101010. dot2 = doth - dir2l;
  101011. if (dot1 > 0) {
  101012. if (dot2 > 0) return;
  101013. t1 = dot1 / (dot1 - dot2);
  101014. sx = sx + tx * t1;
  101015. sy = sy + ty * t1;
  101016. sz = sz + tz * t1;
  101017. sd = sd + td * t1;
  101018. d1x = sx - cbx;
  101019. d1y = sy - cby;
  101020. d1z = sz - cbz;
  101021. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101022. tx = ex - sx;
  101023. ty = ey - sy;
  101024. tz = ez - sz;
  101025. td = ed - sd;
  101026. } else if (dot2 > 0) {
  101027. t1 = dot1 / (dot1 - dot2);
  101028. ex = sx + tx * t1;
  101029. ey = sy + ty * t1;
  101030. ez = sz + tz * t1;
  101031. ed = sd + td * t1;
  101032. d2x = ex - cbx;
  101033. d2y = ey - cby;
  101034. d2z = ez - cbz;
  101035. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101036. tx = ex - sx;
  101037. ty = ey - sy;
  101038. tz = ez - sz;
  101039. td = ed - sd;
  101040. }
  101041. dot1 = dotw + dir2l;
  101042. dot2 = doth + dir2l;
  101043. if (dot1 < 0) {
  101044. if (dot2 < 0) return;
  101045. t1 = dot1 / (dot1 - dot2);
  101046. sx = sx + tx * t1;
  101047. sy = sy + ty * t1;
  101048. sz = sz + tz * t1;
  101049. sd = sd + td * t1;
  101050. } else if (dot2 < 0) {
  101051. t1 = dot1 / (dot1 - dot2);
  101052. ex = sx + tx * t1;
  101053. ey = sy + ty * t1;
  101054. ez = sz + tz * t1;
  101055. ed = sd + td * t1;
  101056. }
  101057. if (sd < 0) {
  101058. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  101059. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  101060. }
  101061. if (ed < 0) {
  101062. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  101063. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  101064. }
  101065. }
  101066. }
  101067. };
  101068. OIMO.CylinderCylinderCollisionDetector = function () {
  101069. OIMO.CollisionDetector.call(this);
  101070. };
  101071. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101072. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  101073. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  101074. var t1x;
  101075. var t1y;
  101076. var t1z;
  101077. var t2x;
  101078. var t2y;
  101079. var t2z;
  101080. var sup = new OIMO.Vec3();
  101081. var len;
  101082. var p1x;
  101083. var p1y;
  101084. var p1z;
  101085. var p2x;
  101086. var p2y;
  101087. var p2z;
  101088. var v01x = c1.position.x;
  101089. var v01y = c1.position.y;
  101090. var v01z = c1.position.z;
  101091. var v02x = c2.position.x;
  101092. var v02y = c2.position.y;
  101093. var v02z = c2.position.z;
  101094. var v0x = v02x - v01x;
  101095. var v0y = v02y - v01y;
  101096. var v0z = v02z - v01z;
  101097. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  101098. var nx = -v0x;
  101099. var ny = -v0y;
  101100. var nz = -v0z;
  101101. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101102. var v11x = sup.x;
  101103. var v11y = sup.y;
  101104. var v11z = sup.z;
  101105. this.supportPoint(c2, nx, ny, nz, sup);
  101106. var v12x = sup.x;
  101107. var v12y = sup.y;
  101108. var v12z = sup.z;
  101109. var v1x = v12x - v11x;
  101110. var v1y = v12y - v11y;
  101111. var v1z = v12z - v11z;
  101112. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  101113. return false;
  101114. }
  101115. nx = v1y * v0z - v1z * v0y;
  101116. ny = v1z * v0x - v1x * v0z;
  101117. nz = v1x * v0y - v1y * v0x;
  101118. if (nx * nx + ny * ny + nz * nz == 0) {
  101119. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  101120. sep.normalize(sep);
  101121. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  101122. return true;
  101123. }
  101124. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101125. var v21x = sup.x;
  101126. var v21y = sup.y;
  101127. var v21z = sup.z;
  101128. this.supportPoint(c2, nx, ny, nz, sup);
  101129. var v22x = sup.x;
  101130. var v22y = sup.y;
  101131. var v22z = sup.z;
  101132. var v2x = v22x - v21x;
  101133. var v2y = v22y - v21y;
  101134. var v2z = v22z - v21z;
  101135. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  101136. return false;
  101137. }
  101138. t1x = v1x - v0x;
  101139. t1y = v1y - v0y;
  101140. t1z = v1z - v0z;
  101141. t2x = v2x - v0x;
  101142. t2y = v2y - v0y;
  101143. t2z = v2z - v0z;
  101144. nx = t1y * t2z - t1z * t2y;
  101145. ny = t1z * t2x - t1x * t2z;
  101146. nz = t1x * t2y - t1y * t2x;
  101147. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  101148. t1x = v1x;
  101149. t1y = v1y;
  101150. t1z = v1z;
  101151. v1x = v2x;
  101152. v1y = v2y;
  101153. v1z = v2z;
  101154. v2x = t1x;
  101155. v2y = t1y;
  101156. v2z = t1z;
  101157. t1x = v11x;
  101158. t1y = v11y;
  101159. t1z = v11z;
  101160. v11x = v21x;
  101161. v11y = v21y;
  101162. v11z = v21z;
  101163. v21x = t1x;
  101164. v21y = t1y;
  101165. v21z = t1z;
  101166. t1x = v12x;
  101167. t1y = v12y;
  101168. t1z = v12z;
  101169. v12x = v22x;
  101170. v12y = v22y;
  101171. v12z = v22z;
  101172. v22x = t1x;
  101173. v22y = t1y;
  101174. v22z = t1z;
  101175. nx = -nx;
  101176. ny = -ny;
  101177. nz = -nz;
  101178. }
  101179. var iterations = 0;
  101180. while (true) {
  101181. if (++iterations > 100) {
  101182. return false;
  101183. }
  101184. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101185. var v31x = sup.x;
  101186. var v31y = sup.y;
  101187. var v31z = sup.z;
  101188. this.supportPoint(c2, nx, ny, nz, sup);
  101189. var v32x = sup.x;
  101190. var v32y = sup.y;
  101191. var v32z = sup.z;
  101192. var v3x = v32x - v31x;
  101193. var v3y = v32y - v31y;
  101194. var v3z = v32z - v31z;
  101195. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  101196. return false;
  101197. }
  101198. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  101199. v2x = v3x;
  101200. v2y = v3y;
  101201. v2z = v3z;
  101202. v21x = v31x;
  101203. v21y = v31y;
  101204. v21z = v31z;
  101205. v22x = v32x;
  101206. v22y = v32y;
  101207. v22z = v32z;
  101208. t1x = v1x - v0x;
  101209. t1y = v1y - v0y;
  101210. t1z = v1z - v0z;
  101211. t2x = v3x - v0x;
  101212. t2y = v3y - v0y;
  101213. t2z = v3z - v0z;
  101214. nx = t1y * t2z - t1z * t2y;
  101215. ny = t1z * t2x - t1x * t2z;
  101216. nz = t1x * t2y - t1y * t2x;
  101217. continue;
  101218. }
  101219. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  101220. v1x = v3x;
  101221. v1y = v3y;
  101222. v1z = v3z;
  101223. v11x = v31x;
  101224. v11y = v31y;
  101225. v11z = v31z;
  101226. v12x = v32x;
  101227. v12y = v32y;
  101228. v12z = v32z;
  101229. t1x = v3x - v0x;
  101230. t1y = v3y - v0y;
  101231. t1z = v3z - v0z;
  101232. t2x = v2x - v0x;
  101233. t2y = v2y - v0y;
  101234. t2z = v2z - v0z;
  101235. nx = t1y * t2z - t1z * t2y;
  101236. ny = t1z * t2x - t1x * t2z;
  101237. nz = t1x * t2y - t1y * t2x;
  101238. continue;
  101239. }
  101240. var hit = false;
  101241. while (true) {
  101242. t1x = v2x - v1x;
  101243. t1y = v2y - v1y;
  101244. t1z = v2z - v1z;
  101245. t2x = v3x - v1x;
  101246. t2y = v3y - v1y;
  101247. t2z = v3z - v1z;
  101248. nx = t1y * t2z - t1z * t2y;
  101249. ny = t1z * t2x - t1x * t2z;
  101250. nz = t1x * t2y - t1y * t2x;
  101251. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  101252. nx *= len;
  101253. ny *= len;
  101254. nz *= len;
  101255. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  101256. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  101257. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  101258. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  101259. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  101260. var sum = b0 + b1 + b2 + b3;
  101261. if (sum <= 0) {
  101262. b0 = 0;
  101263. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  101264. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  101265. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  101266. sum = b1 + b2 + b3;
  101267. }
  101268. var inv = 1 / sum;
  101269. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  101270. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  101271. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  101272. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  101273. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  101274. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  101275. hit = true;
  101276. }
  101277. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101278. var v41x = sup.x;
  101279. var v41y = sup.y;
  101280. var v41z = sup.z;
  101281. this.supportPoint(c2, nx, ny, nz, sup);
  101282. var v42x = sup.x;
  101283. var v42y = sup.y;
  101284. var v42z = sup.z;
  101285. var v4x = v42x - v41x;
  101286. var v4y = v42y - v41y;
  101287. var v4z = v42z - v41z;
  101288. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  101289. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  101290. if (hit) {
  101291. sep.init(-nx, -ny, -nz);
  101292. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  101293. dep.x = separation;
  101294. return true;
  101295. }
  101296. return false;
  101297. }
  101298. if (
  101299. (v4y * v1z - v4z * v1y) * v0x +
  101300. (v4z * v1x - v4x * v1z) * v0y +
  101301. (v4x * v1y - v4y * v1x) * v0z < 0
  101302. ) {
  101303. if (
  101304. (v4y * v2z - v4z * v2y) * v0x +
  101305. (v4z * v2x - v4x * v2z) * v0y +
  101306. (v4x * v2y - v4y * v2x) * v0z < 0
  101307. ) {
  101308. v1x = v4x;
  101309. v1y = v4y;
  101310. v1z = v4z;
  101311. v11x = v41x;
  101312. v11y = v41y;
  101313. v11z = v41z;
  101314. v12x = v42x;
  101315. v12y = v42y;
  101316. v12z = v42z;
  101317. } else {
  101318. v3x = v4x;
  101319. v3y = v4y;
  101320. v3z = v4z;
  101321. v31x = v41x;
  101322. v31y = v41y;
  101323. v31z = v41z;
  101324. v32x = v42x;
  101325. v32y = v42y;
  101326. v32z = v42z;
  101327. }
  101328. } else {
  101329. if (
  101330. (v4y * v3z - v4z * v3y) * v0x +
  101331. (v4z * v3x - v4x * v3z) * v0y +
  101332. (v4x * v3y - v4y * v3x) * v0z < 0
  101333. ) {
  101334. v2x = v4x;
  101335. v2y = v4y;
  101336. v2z = v4z;
  101337. v21x = v41x;
  101338. v21y = v41y;
  101339. v21z = v41z;
  101340. v22x = v42x;
  101341. v22y = v42y;
  101342. v22z = v42z;
  101343. } else {
  101344. v1x = v4x;
  101345. v1y = v4y;
  101346. v1z = v4z;
  101347. v11x = v41x;
  101348. v11y = v41y;
  101349. v11z = v41z;
  101350. v12x = v42x;
  101351. v12y = v42y;
  101352. v12z = v42z;
  101353. }
  101354. }
  101355. }
  101356. }
  101357. //return false;
  101358. };
  101359. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  101360. var rot = c.rotation.elements;
  101361. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101362. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101363. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101364. var radx = ldx;
  101365. var radz = ldz;
  101366. var len = radx * radx + radz * radz;
  101367. var rad = c.radius;
  101368. var hh = c.halfHeight;
  101369. var ox;
  101370. var oy;
  101371. var oz;
  101372. if (len == 0) {
  101373. if (ldy < 0) {
  101374. ox = rad;
  101375. oy = -hh;
  101376. oz = 0;
  101377. } else {
  101378. ox = rad;
  101379. oy = hh;
  101380. oz = 0;
  101381. }
  101382. } else {
  101383. len = c.radius / OIMO.sqrt(len);
  101384. if (ldy < 0) {
  101385. ox = radx * len;
  101386. oy = -hh;
  101387. oz = radz * len;
  101388. } else {
  101389. ox = radx * len;
  101390. oy = hh;
  101391. oz = radz * len;
  101392. }
  101393. }
  101394. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101395. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101396. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101397. out.init(ldx, ldy, ldz);
  101398. };
  101399. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101400. var c1;
  101401. var c2;
  101402. if (shape1.id < shape2.id) {
  101403. c1 = shape1;
  101404. c2 = shape2;
  101405. } else {
  101406. c1 = shape2;
  101407. c2 = shape1;
  101408. }
  101409. var p1 = c1.position;
  101410. var p2 = c2.position;
  101411. var p1x = p1.x;
  101412. var p1y = p1.y;
  101413. var p1z = p1.z;
  101414. var p2x = p2.x;
  101415. var p2y = p2.y;
  101416. var p2z = p2.z;
  101417. var h1 = c1.halfHeight;
  101418. var h2 = c2.halfHeight;
  101419. var n1 = c1.normalDirection;
  101420. var n2 = c2.normalDirection;
  101421. var d1 = c1.halfDirection;
  101422. var d2 = c2.halfDirection;
  101423. var r1 = c1.radius;
  101424. var r2 = c2.radius;
  101425. var n1x = n1.x;
  101426. var n1y = n1.y;
  101427. var n1z = n1.z;
  101428. var n2x = n2.x;
  101429. var n2y = n2.y;
  101430. var n2z = n2.z;
  101431. var d1x = d1.x;
  101432. var d1y = d1.y;
  101433. var d1z = d1.z;
  101434. var d2x = d2.x;
  101435. var d2y = d2.y;
  101436. var d2z = d2.z;
  101437. var dx = p1x - p2x;
  101438. var dy = p1y - p2y;
  101439. var dz = p1z - p2z;
  101440. var len;
  101441. var len1;
  101442. var len2;
  101443. var c;
  101444. var c1x;
  101445. var c1y;
  101446. var c1z;
  101447. var c2x;
  101448. var c2y;
  101449. var c2z;
  101450. var tx;
  101451. var ty;
  101452. var tz;
  101453. var sx;
  101454. var sy;
  101455. var sz;
  101456. var ex;
  101457. var ey;
  101458. var ez;
  101459. var depth1;
  101460. var depth2;
  101461. var dot;
  101462. var t1;
  101463. var t2;
  101464. var sep = new OIMO.Vec3();
  101465. var pos = new OIMO.Vec3();
  101466. var dep = new OIMO.Vec3();
  101467. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  101468. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  101469. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  101470. var right1 = dot1 > 0;
  101471. var right2 = dot2 > 0;
  101472. if (!right1) dot1 = -dot1;
  101473. if (!right2) dot2 = -dot2;
  101474. var state = 0;
  101475. if (dot1 > 0.999 || dot2 > 0.999) {
  101476. if (dot1 > dot2) state = 1;
  101477. else state = 2;
  101478. }
  101479. var nx;
  101480. var ny;
  101481. var nz;
  101482. var depth = dep.x;
  101483. var r00;
  101484. var r01;
  101485. var r02;
  101486. var r10;
  101487. var r11;
  101488. var r12;
  101489. var r20;
  101490. var r21;
  101491. var r22;
  101492. var px;
  101493. var py;
  101494. var pz;
  101495. var pd;
  101496. var a;
  101497. var b;
  101498. var e;
  101499. var f;
  101500. nx = sep.x;
  101501. ny = sep.y;
  101502. nz = sep.z;
  101503. switch (state) {
  101504. case 0:
  101505. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  101506. break;
  101507. case 1:
  101508. if (right1) {
  101509. c1x = p1x + d1x;
  101510. c1y = p1y + d1y;
  101511. c1z = p1z + d1z;
  101512. nx = n1x;
  101513. ny = n1y;
  101514. nz = n1z;
  101515. } else {
  101516. c1x = p1x - d1x;
  101517. c1y = p1y - d1y;
  101518. c1z = p1z - d1z;
  101519. nx = -n1x;
  101520. ny = -n1y;
  101521. nz = -n1z;
  101522. }
  101523. dot = nx * n2x + ny * n2y + nz * n2z;
  101524. if (dot < 0) len = h2;
  101525. else len = -h2;
  101526. c2x = p2x + len * n2x;
  101527. c2y = p2y + len * n2y;
  101528. c2z = p2z + len * n2z;
  101529. if (dot2 >= 0.999999) {
  101530. tx = -ny;
  101531. ty = nz;
  101532. tz = nx;
  101533. } else {
  101534. tx = nx;
  101535. ty = ny;
  101536. tz = nz;
  101537. }
  101538. len = tx * n2x + ty * n2y + tz * n2z;
  101539. dx = len * n2x - tx;
  101540. dy = len * n2y - ty;
  101541. dz = len * n2z - tz;
  101542. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101543. if (len == 0) break;
  101544. len = r2 / len;
  101545. dx *= len;
  101546. dy *= len;
  101547. dz *= len;
  101548. tx = c2x + dx;
  101549. ty = c2y + dy;
  101550. tz = c2z + dz;
  101551. if (dot < -0.96 || dot > 0.96) {
  101552. r00 = n2x * n2x * 1.5 - 0.5;
  101553. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  101554. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  101555. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  101556. r11 = n2y * n2y * 1.5 - 0.5;
  101557. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  101558. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  101559. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  101560. r22 = n2z * n2z * 1.5 - 0.5;
  101561. px = tx;
  101562. py = ty;
  101563. pz = tz;
  101564. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101565. tx = px - pd * nx - c1x;
  101566. ty = py - pd * ny - c1y;
  101567. tz = pz - pd * nz - c1z;
  101568. len = tx * tx + ty * ty + tz * tz;
  101569. if (len > r1 * r1) {
  101570. len = r1 / OIMO.sqrt(len);
  101571. tx *= len;
  101572. ty *= len;
  101573. tz *= len;
  101574. }
  101575. px = c1x + tx;
  101576. py = c1y + ty;
  101577. pz = c1z + tz;
  101578. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101579. px = dx * r00 + dy * r01 + dz * r02;
  101580. py = dx * r10 + dy * r11 + dz * r12;
  101581. pz = dx * r20 + dy * r21 + dz * r22;
  101582. px = (dx = px) + c2x;
  101583. py = (dy = py) + c2y;
  101584. pz = (dz = pz) + c2z;
  101585. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101586. if (pd <= 0) {
  101587. tx = px - pd * nx - c1x;
  101588. ty = py - pd * ny - c1y;
  101589. tz = pz - pd * nz - c1z;
  101590. len = tx * tx + ty * ty + tz * tz;
  101591. if (len > r1 * r1) {
  101592. len = r1 / OIMO.sqrt(len);
  101593. tx *= len;
  101594. ty *= len;
  101595. tz *= len;
  101596. }
  101597. px = c1x + tx;
  101598. py = c1y + ty;
  101599. pz = c1z + tz;
  101600. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101601. }
  101602. px = dx * r00 + dy * r01 + dz * r02;
  101603. py = dx * r10 + dy * r11 + dz * r12;
  101604. pz = dx * r20 + dy * r21 + dz * r22;
  101605. px = (dx = px) + c2x;
  101606. py = (dy = py) + c2y;
  101607. pz = (dz = pz) + c2z;
  101608. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  101609. if (pd <= 0) {
  101610. tx = px - pd * nx - c1x;
  101611. ty = py - pd * ny - c1y;
  101612. tz = pz - pd * nz - c1z;
  101613. len = tx * tx + ty * ty + tz * tz;
  101614. if (len > r1 * r1) {
  101615. len = r1 / OIMO.sqrt(len);
  101616. tx *= len;
  101617. ty *= len;
  101618. tz *= len;
  101619. }
  101620. px = c1x + tx;
  101621. py = c1y + ty;
  101622. pz = c1z + tz;
  101623. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  101624. }
  101625. } else {
  101626. sx = tx;
  101627. sy = ty;
  101628. sz = tz;
  101629. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  101630. sx -= depth1 * nx;
  101631. sy -= depth1 * ny;
  101632. sz -= depth1 * nz;
  101633. if (dot > 0) {
  101634. ex = tx + n2x * h2 * 2;
  101635. ey = ty + n2y * h2 * 2;
  101636. ez = tz + n2z * h2 * 2;
  101637. } else {
  101638. ex = tx - n2x * h2 * 2;
  101639. ey = ty - n2y * h2 * 2;
  101640. ez = tz - n2z * h2 * 2;
  101641. }
  101642. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  101643. ex -= depth2 * nx;
  101644. ey -= depth2 * ny;
  101645. ez -= depth2 * nz;
  101646. dx = c1x - sx;
  101647. dy = c1y - sy;
  101648. dz = c1z - sz;
  101649. tx = ex - sx;
  101650. ty = ey - sy;
  101651. tz = ez - sz;
  101652. a = dx * dx + dy * dy + dz * dz;
  101653. b = dx * tx + dy * ty + dz * tz;
  101654. e = tx * tx + ty * ty + tz * tz;
  101655. f = b * b - e * (a - r1 * r1);
  101656. if (f < 0) break;
  101657. f = OIMO.sqrt(f);
  101658. t1 = (b + f) / e;
  101659. t2 = (b - f) / e;
  101660. if (t2 < t1) {
  101661. len = t1;
  101662. t1 = t2;
  101663. t2 = len;
  101664. }
  101665. if (t2 > 1) t2 = 1;
  101666. if (t1 < 0) t1 = 0;
  101667. tx = sx + (ex - sx) * t1;
  101668. ty = sy + (ey - sy) * t1;
  101669. tz = sz + (ez - sz) * t1;
  101670. ex = sx + (ex - sx) * t2;
  101671. ey = sy + (ey - sy) * t2;
  101672. ez = sz + (ez - sz) * t2;
  101673. sx = tx;
  101674. sy = ty;
  101675. sz = tz;
  101676. len = depth1 + (depth2 - depth1) * t1;
  101677. depth2 = depth1 + (depth2 - depth1) * t2;
  101678. depth1 = len;
  101679. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  101680. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  101681. }
  101682. break;
  101683. case 2:
  101684. if (right2) {
  101685. c2x = p2x - d2x;
  101686. c2y = p2y - d2y;
  101687. c2z = p2z - d2z;
  101688. nx = -n2x;
  101689. ny = -n2y;
  101690. nz = -n2z;
  101691. } else {
  101692. c2x = p2x + d2x;
  101693. c2y = p2y + d2y;
  101694. c2z = p2z + d2z;
  101695. nx = n2x;
  101696. ny = n2y;
  101697. nz = n2z;
  101698. }
  101699. dot = nx * n1x + ny * n1y + nz * n1z;
  101700. if (dot < 0) len = h1;
  101701. else len = -h1;
  101702. c1x = p1x + len * n1x;
  101703. c1y = p1y + len * n1y;
  101704. c1z = p1z + len * n1z;
  101705. if (dot1 >= 0.999999) {
  101706. tx = -ny;
  101707. ty = nz;
  101708. tz = nx;
  101709. } else {
  101710. tx = nx;
  101711. ty = ny;
  101712. tz = nz;
  101713. }
  101714. len = tx * n1x + ty * n1y + tz * n1z;
  101715. dx = len * n1x - tx;
  101716. dy = len * n1y - ty;
  101717. dz = len * n1z - tz;
  101718. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101719. if (len == 0) break;
  101720. len = r1 / len;
  101721. dx *= len;
  101722. dy *= len;
  101723. dz *= len;
  101724. tx = c1x + dx;
  101725. ty = c1y + dy;
  101726. tz = c1z + dz;
  101727. if (dot < -0.96 || dot > 0.96) {
  101728. r00 = n1x * n1x * 1.5 - 0.5;
  101729. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  101730. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  101731. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  101732. r11 = n1y * n1y * 1.5 - 0.5;
  101733. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  101734. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  101735. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  101736. r22 = n1z * n1z * 1.5 - 0.5;
  101737. px = tx;
  101738. py = ty;
  101739. pz = tz;
  101740. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  101741. tx = px - pd * nx - c2x;
  101742. ty = py - pd * ny - c2y;
  101743. tz = pz - pd * nz - c2z;
  101744. len = tx * tx + ty * ty + tz * tz;
  101745. if (len > r2 * r2) {
  101746. len = r2 / OIMO.sqrt(len);
  101747. tx *= len;
  101748. ty *= len;
  101749. tz *= len;
  101750. }
  101751. px = c2x + tx;
  101752. py = c2y + ty;
  101753. pz = c2z + tz;
  101754. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  101755. px = dx * r00 + dy * r01 + dz * r02;
  101756. py = dx * r10 + dy * r11 + dz * r12;
  101757. pz = dx * r20 + dy * r21 + dz * r22;
  101758. px = (dx = px) + c1x;
  101759. py = (dy = py) + c1y;
  101760. pz = (dz = pz) + c1z;
  101761. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  101762. if (pd <= 0) {
  101763. tx = px - pd * nx - c2x;
  101764. ty = py - pd * ny - c2y;
  101765. tz = pz - pd * nz - c2z;
  101766. len = tx * tx + ty * ty + tz * tz;
  101767. if (len > r2 * r2) {
  101768. len = r2 / OIMO.sqrt(len);
  101769. tx *= len;
  101770. ty *= len;
  101771. tz *= len;
  101772. }
  101773. px = c2x + tx;
  101774. py = c2y + ty;
  101775. pz = c2z + tz;
  101776. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  101777. }
  101778. px = dx * r00 + dy * r01 + dz * r02;
  101779. py = dx * r10 + dy * r11 + dz * r12;
  101780. pz = dx * r20 + dy * r21 + dz * r22;
  101781. px = (dx = px) + c1x;
  101782. py = (dy = py) + c1y;
  101783. pz = (dz = pz) + c1z;
  101784. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  101785. if (pd <= 0) {
  101786. tx = px - pd * nx - c2x;
  101787. ty = py - pd * ny - c2y;
  101788. tz = pz - pd * nz - c2z;
  101789. len = tx * tx + ty * ty + tz * tz;
  101790. if (len > r2 * r2) {
  101791. len = r2 / OIMO.sqrt(len);
  101792. tx *= len;
  101793. ty *= len;
  101794. tz *= len;
  101795. }
  101796. px = c2x + tx;
  101797. py = c2y + ty;
  101798. pz = c2z + tz;
  101799. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  101800. }
  101801. } else {
  101802. sx = tx;
  101803. sy = ty;
  101804. sz = tz;
  101805. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  101806. sx -= depth1 * nx;
  101807. sy -= depth1 * ny;
  101808. sz -= depth1 * nz;
  101809. if (dot > 0) {
  101810. ex = tx + n1x * h1 * 2;
  101811. ey = ty + n1y * h1 * 2;
  101812. ez = tz + n1z * h1 * 2;
  101813. } else {
  101814. ex = tx - n1x * h1 * 2;
  101815. ey = ty - n1y * h1 * 2;
  101816. ez = tz - n1z * h1 * 2;
  101817. }
  101818. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  101819. ex -= depth2 * nx;
  101820. ey -= depth2 * ny;
  101821. ez -= depth2 * nz;
  101822. dx = c2x - sx;
  101823. dy = c2y - sy;
  101824. dz = c2z - sz;
  101825. tx = ex - sx;
  101826. ty = ey - sy;
  101827. tz = ez - sz;
  101828. a = dx * dx + dy * dy + dz * dz;
  101829. b = dx * tx + dy * ty + dz * tz;
  101830. e = tx * tx + ty * ty + tz * tz;
  101831. f = b * b - e * (a - r2 * r2);
  101832. if (f < 0) break;
  101833. f = OIMO.sqrt(f);
  101834. t1 = (b + f) / e;
  101835. t2 = (b - f) / e;
  101836. if (t2 < t1) {
  101837. len = t1;
  101838. t1 = t2;
  101839. t2 = len;
  101840. }
  101841. if (t2 > 1) t2 = 1;
  101842. if (t1 < 0) t1 = 0;
  101843. tx = sx + (ex - sx) * t1;
  101844. ty = sy + (ey - sy) * t1;
  101845. tz = sz + (ez - sz) * t1;
  101846. ex = sx + (ex - sx) * t2;
  101847. ey = sy + (ey - sy) * t2;
  101848. ez = sz + (ez - sz) * t2;
  101849. sx = tx;
  101850. sy = ty;
  101851. sz = tz;
  101852. len = depth1 + (depth2 - depth1) * t1;
  101853. depth2 = depth1 + (depth2 - depth1) * t2;
  101854. depth1 = len;
  101855. if (depth1 < 0) {
  101856. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  101857. }
  101858. if (depth2 < 0) {
  101859. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  101860. }
  101861. }
  101862. break;
  101863. }
  101864. };
  101865. OIMO.SphereCylinderCollisionDetector = function (flip) {
  101866. OIMO.CollisionDetector.call(this);
  101867. this.flip = flip;
  101868. };
  101869. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101870. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  101871. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101872. var s;
  101873. var c;
  101874. if (this.flip) {
  101875. s = shape2;
  101876. c = shape1;
  101877. } else {
  101878. s = shape1;
  101879. c = shape2;
  101880. }
  101881. var ps = s.position;
  101882. var psx = ps.x;
  101883. var psy = ps.y;
  101884. var psz = ps.z;
  101885. var pc = c.position;
  101886. var pcx = pc.x;
  101887. var pcy = pc.y;
  101888. var pcz = pc.z;
  101889. var dirx = c.normalDirection.x;
  101890. var diry = c.normalDirection.y;
  101891. var dirz = c.normalDirection.z;
  101892. var rads = s.radius;
  101893. var radc = c.radius;
  101894. var rad2 = rads + radc;
  101895. var halfh = c.halfHeight;
  101896. var dx = psx - pcx;
  101897. var dy = psy - pcy;
  101898. var dz = psz - pcz;
  101899. var dot = dx * dirx + dy * diry + dz * dirz;
  101900. if (dot < -halfh - rads || dot > halfh + rads) return;
  101901. var cx = pcx + dot * dirx;
  101902. var cy = pcy + dot * diry;
  101903. var cz = pcz + dot * dirz;
  101904. var d2x = psx - cx;
  101905. var d2y = psy - cy;
  101906. var d2z = psz - cz;
  101907. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  101908. if (len > rad2 * rad2) return;
  101909. if (len > radc * radc) {
  101910. len = radc / OIMO.sqrt(len);
  101911. d2x *= len;
  101912. d2y *= len;
  101913. d2z *= len;
  101914. }
  101915. if (dot < -halfh) dot = -halfh;
  101916. else if (dot > halfh) dot = halfh;
  101917. cx = pcx + dot * dirx + d2x;
  101918. cy = pcy + dot * diry + d2y;
  101919. cz = pcz + dot * dirz + d2z;
  101920. dx = cx - psx;
  101921. dy = cy - psy;
  101922. dz = cz - psz;
  101923. len = dx * dx + dy * dy + dz * dz;
  101924. var invLen;
  101925. if (len > 0 && len < rads * rads) {
  101926. len = OIMO.sqrt(len);
  101927. invLen = 1 / len;
  101928. dx *= invLen;
  101929. dy *= invLen;
  101930. dz *= invLen;
  101931. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  101932. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  101933. }
  101934. };
  101935. /**
  101936. * Class for checking collisions between 2 tetras,
  101937. * a shape that is made with 4 vertices and 4 faces
  101938. * arranged in triangles. With this algorigthm, soft
  101939. * body physics are possible and easier to implement.
  101940. * @author xprogram
  101941. */
  101942. OIMO.TetraTetraCollisionDetector = function () {
  101943. OIMO.CollisionDetector.call(this);
  101944. };
  101945. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101946. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  101947. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  101948. /*
  101949. * What we are doing:
  101950. * Each tetra is represented by four 3D triangles. The only
  101951. * quick way of finding if another tetra is within the other
  101952. * tetra is to see if a single vertex is within the triangles
  101953. * of the other tetra. So, for example, a tetra is represented
  101954. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  101955. * There is another tetra with a vertex A which was detected for
  101956. * collision by the broadphase. Now, if the point A is between ALL
  101957. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  101958. * is valid and we can pass point A to the manifold. Since the only
  101959. * points on the tetra are the 4 vertices, collision detection is
  101960. * not so complex. However, it can be time-consuming because we
  101961. * need to split the 3D triangles into three 2D triangles each for
  101962. * collision detection.
  101963. */
  101964. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  101965. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  101966. // fs is undeclared
  101967. var fs = fs1;
  101968. for (i = 0; i < 4; i++) {
  101969. vec = vs1[i];
  101970. for (j = 0; j < 4; j++) {
  101971. j1 = vs2[fs[i].a];
  101972. j2 = vs2[fs[i].b];
  101973. j3 = vs2[fs[i].c];
  101974. if (
  101975. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  101976. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  101977. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  101978. )
  101979. ts++;
  101980. if (ts === 4) // Only add point if it is inside all 4 triangles
  101981. manifold.addPoint(vec);
  101982. }
  101983. }
  101984. };
  101985. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  101986. function tricheck(p, p0, p1, p2) {
  101987. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  101988. var sg = A < 0 ? -1 : 1;
  101989. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  101990. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  101991. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  101992. }
  101993. function pt(x, y) { return { x: x, y: y }; }
  101994. /**
  101995. * An axis-aligned bounding box.
  101996. * @author saharan
  101997. * @author lo-th
  101998. */
  101999. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  102000. this.elements = new OIMO_ARRAY_TYPE(6);
  102001. var te = this.elements;
  102002. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  102003. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  102004. };
  102005. OIMO.AABB.prototype = {
  102006. constructor: OIMO.AABB,
  102007. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  102008. var te = this.elements;
  102009. te[0] = minX; te[3] = maxX;
  102010. te[1] = minY; te[4] = maxY;
  102011. te[2] = minZ; te[5] = maxZ;
  102012. return this;
  102013. },
  102014. intersectTest: function (aabb) {
  102015. var te = this.elements;
  102016. var ue = aabb.elements;
  102017. 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];
  102018. },
  102019. intersectTestTwo: function (aabb) {
  102020. var te = this.elements;
  102021. var ue = aabb.elements;
  102022. 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];
  102023. },
  102024. clone: function () {
  102025. return new this.constructor().fromArray(this.elements);
  102026. },
  102027. copy: function (aabb, margin) {
  102028. var m = margin || 0;
  102029. var me = aabb.elements;
  102030. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  102031. return this;
  102032. },
  102033. fromArray: function (array) {
  102034. this.elements.set(array);
  102035. return this;
  102036. },
  102037. // Set this AABB to the combined AABB of aabb1 and aabb2.
  102038. combine: function (aabb1, aabb2) {
  102039. var a = aabb1.elements;
  102040. var b = aabb2.elements;
  102041. var te = this.elements;
  102042. te[0] = a[0] < b[0] ? a[0] : b[0];
  102043. te[1] = a[1] < b[1] ? a[1] : b[1];
  102044. te[2] = a[2] < b[2] ? a[2] : b[2];
  102045. te[3] = a[3] > b[3] ? a[3] : b[3];
  102046. te[4] = a[4] > b[4] ? a[4] : b[4];
  102047. te[5] = a[5] > b[5] ? a[5] : b[5];
  102048. return this;
  102049. },
  102050. // Get the surface area.
  102051. surfaceArea: function () {
  102052. var te = this.elements;
  102053. var a = te[3] - te[0];
  102054. var h = te[4] - te[1];
  102055. var d = te[5] - te[2];
  102056. return 2 * (a * (h + d) + h * d);
  102057. },
  102058. // Get whether the AABB intersects with the point or not.
  102059. intersectsWithPoint: function (x, y, z) {
  102060. var te = this.elements;
  102061. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  102062. },
  102063. /**
  102064. * Set the AABB from an array
  102065. * of vertices. From THREE.
  102066. * @author mrdoob
  102067. * @author xprogram
  102068. */
  102069. setFromPoints: function (arr) {
  102070. this.makeEmpty();
  102071. for (var i = 0; i < arr.length; i++) {
  102072. this.expandByPoint(arr[i]);
  102073. }
  102074. },
  102075. makeEmpty: function () {
  102076. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  102077. },
  102078. expandByPoint: function (pt) {
  102079. var te = this.elements;
  102080. this.set(
  102081. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  102082. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  102083. );
  102084. }
  102085. };
  102086. /**
  102087. * A proxy is used for broad-phase collecting pairs that can be colliding.
  102088. */
  102089. OIMO.Proxy = function (shape) {
  102090. // The parent shape.
  102091. this.shape = shape;
  102092. // The axis-aligned bounding box.
  102093. this.aabb = shape.aabb;
  102094. };
  102095. OIMO.Proxy.prototype = {
  102096. constructor: OIMO.Proxy,
  102097. // Update the proxy.
  102098. update: function () {
  102099. OIMO.Error("Proxy", "Inheritance error.");
  102100. }
  102101. };
  102102. /**
  102103. * A basic implementation of proxies.
  102104. * @author saharan
  102105. */
  102106. OIMO.BasicProxy = function (shape) {
  102107. OIMO.Proxy.call(this, shape);
  102108. this.id = OIMO.proxyID++;
  102109. };
  102110. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102111. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  102112. OIMO.BasicProxy.prototype.update = function () {
  102113. };
  102114. /**
  102115. * The broad-phase is used for collecting all possible pairs for collision.
  102116. */
  102117. OIMO.BroadPhase = function () {
  102118. this.types = OIMO.BR_NULL;
  102119. this.numPairChecks = 0;
  102120. this.numPairs = 0;
  102121. this.pairs = [];
  102122. };
  102123. OIMO.BroadPhase.prototype = {
  102124. constructor: OIMO.BroadPhase,
  102125. /**
  102126. * Create a new proxy.
  102127. * @param shape
  102128. * @return
  102129. */
  102130. createProxy: function (shape) {
  102131. OIMO.Error("BroadPhase", "Inheritance error.");
  102132. },
  102133. /**
  102134. * Add the proxy into the broad-phase.
  102135. * @param proxy
  102136. */
  102137. addProxy: function (proxy) {
  102138. OIMO.Error("BroadPhase", "Inheritance error.");
  102139. },
  102140. /**
  102141. * Remove the proxy from the broad-phase.
  102142. * @param proxy
  102143. */
  102144. removeProxy: function (proxy) {
  102145. OIMO.Error("BroadPhase", "Inheritance error.");
  102146. },
  102147. /**
  102148. * Returns whether the pair is available or not.
  102149. * @param s1
  102150. * @param s2
  102151. * @return
  102152. */
  102153. isAvailablePair: function (s1, s2) {
  102154. var b1 = s1.parent;
  102155. var b2 = s2.parent;
  102156. if (b1 == b2 || // same parents
  102157. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  102158. (s1.belongsTo & s2.collidesWith) == 0 ||
  102159. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  102160. ) { return false; }
  102161. var js;
  102162. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  102163. else js = b2.jointLink;
  102164. while (js !== null) {
  102165. var joint = js.joint;
  102166. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  102167. js = js.next;
  102168. }
  102169. return true;
  102170. },
  102171. // Detect overlapping pairs.
  102172. detectPairs: function () {
  102173. // clear old
  102174. this.pairs = [];
  102175. this.numPairs = 0;
  102176. this.numPairChecks = 0;
  102177. this.collectPairs();
  102178. },
  102179. collectPairs: function () {
  102180. OIMO.Error("BroadPhase", "Inheritance error.");
  102181. },
  102182. addPair: function (s1, s2) {
  102183. var pair = new OIMO.Pair(s1, s2);
  102184. this.pairs.push(pair);
  102185. this.numPairs++;
  102186. }
  102187. };
  102188. /**
  102189. * A broad-phase algorithm with brute-force search.
  102190. * This always checks for all possible pairs.
  102191. */
  102192. OIMO.BruteForceBroadPhase = function () {
  102193. OIMO.BroadPhase.call(this);
  102194. this.types = OIMO.BR_BRUTE_FORCE;;
  102195. //this.numProxies=0;
  102196. ///this.maxProxies = 256;
  102197. this.proxies = [];
  102198. //this.proxies.length = 256;
  102199. };
  102200. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102201. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  102202. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  102203. return new OIMO.BasicProxy(shape);
  102204. };
  102205. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  102206. /*if(this.numProxies==this.maxProxies){
  102207. //this.maxProxies<<=1;
  102208. this.maxProxies*=2;
  102209. var newProxies=[];
  102210. newProxies.length = this.maxProxies;
  102211. var i = this.numProxies;
  102212. while(i--){
  102213. //for(var i=0, l=this.numProxies;i<l;i++){
  102214. newProxies[i]=this.proxies[i];
  102215. }
  102216. this.proxies=newProxies;
  102217. }*/
  102218. //this.proxies[this.numProxies++] = proxy;
  102219. this.proxies.push(proxy);
  102220. //this.numProxies++;
  102221. };
  102222. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  102223. var n = this.proxies.indexOf(proxy);
  102224. if (n > -1) {
  102225. this.proxies.splice(n, 1);
  102226. //this.numProxies--;
  102227. }
  102228. /*var i = this.numProxies;
  102229. while(i--){
  102230. //for(var i=0, l=this.numProxies;i<l;i++){
  102231. if(this.proxies[i] == proxy){
  102232. this.proxies[i] = this.proxies[--this.numProxies];
  102233. this.proxies[this.numProxies] = null;
  102234. return;
  102235. }
  102236. }*/
  102237. };
  102238. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  102239. var i = 0, j, p1, p2;
  102240. var px = this.proxies;
  102241. var l = px.length;//this.numProxies;
  102242. //var ar1 = [];
  102243. //var ar2 = [];
  102244. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  102245. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  102246. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  102247. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  102248. this.numPairChecks = l * (l - 1) >> 1;
  102249. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  102250. while (i < l) {
  102251. p1 = px[i++];
  102252. j = i + 1;
  102253. while (j < l) {
  102254. p2 = px[j++];
  102255. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  102256. this.addPair(p1.shape, p2.shape);
  102257. }
  102258. }
  102259. };
  102260. /**
  102261. * A pair of shapes that may collide.
  102262. * @author saharan
  102263. */
  102264. OIMO.Pair = function (s1, s2) {
  102265. // The first shape.
  102266. this.shape1 = s1 || null;
  102267. // The second shape.
  102268. this.shape2 = s2 || null;
  102269. };
  102270. /**
  102271. * A projection axis for sweep and prune broad-phase.
  102272. * @author saharan
  102273. */
  102274. OIMO.SAPAxis = function () {
  102275. this.numElements = 0;
  102276. this.bufferSize = 256;
  102277. this.elements = [];
  102278. this.elements.length = this.bufferSize;
  102279. this.stack = new OIMO_ARRAY_TYPE(64);
  102280. };
  102281. OIMO.SAPAxis.prototype = {
  102282. constructor: OIMO.SAPAxis,
  102283. addElements: function (min, max) {
  102284. if (this.numElements + 2 >= this.bufferSize) {
  102285. //this.bufferSize<<=1;
  102286. this.bufferSize *= 2;
  102287. var newElements = [];
  102288. var i = this.numElements;
  102289. while (i--) {
  102290. //for(var i=0, l=this.numElements; i<l; i++){
  102291. newElements[i] = this.elements[i];
  102292. }
  102293. }
  102294. this.elements[this.numElements++] = min;
  102295. this.elements[this.numElements++] = max;
  102296. },
  102297. removeElements: function (min, max) {
  102298. var minIndex = -1;
  102299. var maxIndex = -1;
  102300. for (var i = 0, l = this.numElements; i < l; i++) {
  102301. var e = this.elements[i];
  102302. if (e == min || e == max) {
  102303. if (minIndex == -1) {
  102304. minIndex = i;
  102305. } else {
  102306. maxIndex = i;
  102307. break;
  102308. }
  102309. }
  102310. }
  102311. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  102312. this.elements[i - 1] = this.elements[i];
  102313. }
  102314. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  102315. this.elements[i - 2] = this.elements[i];
  102316. }
  102317. this.elements[--this.numElements] = null;
  102318. this.elements[--this.numElements] = null;
  102319. },
  102320. sort: function () {
  102321. var count = 0;
  102322. var threshold = 1;
  102323. while ((this.numElements >> threshold) != 0) threshold++;
  102324. threshold = threshold * this.numElements >> 2;
  102325. count = 0;
  102326. var giveup = false;
  102327. var elements = this.elements;
  102328. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  102329. var tmp = elements[i];
  102330. var pivot = tmp.value;
  102331. var tmp2 = elements[i - 1];
  102332. if (tmp2.value > pivot) {
  102333. var j = i;
  102334. do {
  102335. elements[j] = tmp2;
  102336. if (--j == 0) break;
  102337. tmp2 = elements[j - 1];
  102338. } while (tmp2.value > pivot);
  102339. elements[j] = tmp;
  102340. count += i - j;
  102341. if (count > threshold) {
  102342. giveup = true; // stop and use quick sort
  102343. break;
  102344. }
  102345. }
  102346. }
  102347. if (!giveup) return;
  102348. count = 2; var stack = this.stack;
  102349. stack[0] = 0;
  102350. stack[1] = this.numElements - 1;
  102351. while (count > 0) {
  102352. var right = stack[--count];
  102353. var left = stack[--count];
  102354. var diff = right - left;
  102355. if (diff > 16) { // quick sort
  102356. //var mid=left+(diff>>1);
  102357. var mid = left + (OIMO.floor(diff * 0.5));
  102358. tmp = elements[mid];
  102359. elements[mid] = elements[right];
  102360. elements[right] = tmp;
  102361. pivot = tmp.value;
  102362. i = left - 1;
  102363. j = right;
  102364. while (true) {
  102365. var ei;
  102366. var ej;
  102367. do { ei = elements[++i]; } while (ei.value < pivot);
  102368. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  102369. if (i >= j) break;
  102370. elements[i] = ej;
  102371. elements[j] = ei;
  102372. }
  102373. elements[right] = elements[i];
  102374. elements[i] = tmp;
  102375. if (i - left > right - i) {
  102376. stack[count++] = left;
  102377. stack[count++] = i - 1;
  102378. stack[count++] = i + 1;
  102379. stack[count++] = right;
  102380. } else {
  102381. stack[count++] = i + 1;
  102382. stack[count++] = right;
  102383. stack[count++] = left;
  102384. stack[count++] = i - 1;
  102385. }
  102386. } else {
  102387. for (i = left + 1; i <= right; i++) {
  102388. tmp = elements[i];
  102389. pivot = tmp.value;
  102390. tmp2 = elements[i - 1];
  102391. if (tmp2.value > pivot) {
  102392. j = i;
  102393. do {
  102394. elements[j] = tmp2;
  102395. if (--j == 0) break;
  102396. tmp2 = elements[j - 1];
  102397. } while (tmp2.value > pivot);
  102398. elements[j] = tmp;
  102399. }
  102400. }
  102401. }
  102402. }
  102403. },
  102404. calculateTestCount: function () {
  102405. var num = 1;
  102406. var sum = 0;
  102407. for (var i = 1, l = this.numElements; i < l; i++) {
  102408. if (this.elements[i].max) {
  102409. num--;
  102410. } else {
  102411. sum += num;
  102412. num++;
  102413. }
  102414. }
  102415. return sum;
  102416. }
  102417. }
  102418. /**
  102419. * A broad-phase collision detection algorithm using sweep and prune.
  102420. * @author saharan
  102421. * @author lo-th
  102422. */
  102423. OIMO.SAPBroadPhase = function () {
  102424. OIMO.BroadPhase.call(this);
  102425. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  102426. this.numElementsD = 0;
  102427. this.numElementsS = 0;
  102428. // dynamic proxies
  102429. this.axesD = [
  102430. new OIMO.SAPAxis(),
  102431. new OIMO.SAPAxis(),
  102432. new OIMO.SAPAxis()
  102433. ];
  102434. // static or sleeping proxies
  102435. this.axesS = [
  102436. new OIMO.SAPAxis(),
  102437. new OIMO.SAPAxis(),
  102438. new OIMO.SAPAxis()
  102439. ];
  102440. this.index1 = 0;
  102441. this.index2 = 1;
  102442. };
  102443. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102444. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  102445. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  102446. return new OIMO.SAPProxy(this, shape);
  102447. };
  102448. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  102449. var p = proxy;
  102450. if (p.isDynamic()) {
  102451. this.axesD[0].addElements(p.min[0], p.max[0]);
  102452. this.axesD[1].addElements(p.min[1], p.max[1]);
  102453. this.axesD[2].addElements(p.min[2], p.max[2]);
  102454. p.belongsTo = 1;
  102455. this.numElementsD += 2;
  102456. } else {
  102457. this.axesS[0].addElements(p.min[0], p.max[0]);
  102458. this.axesS[1].addElements(p.min[1], p.max[1]);
  102459. this.axesS[2].addElements(p.min[2], p.max[2]);
  102460. p.belongsTo = 2;
  102461. this.numElementsS += 2;
  102462. }
  102463. };
  102464. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  102465. var p = proxy;
  102466. if (p.belongsTo == 0) return;
  102467. /*else if ( p.belongsTo == 1 ) {
  102468. this.axesD[0].removeElements( p.min[0], p.max[0] );
  102469. this.axesD[1].removeElements( p.min[1], p.max[1] );
  102470. this.axesD[2].removeElements( p.min[2], p.max[2] );
  102471. this.numElementsD -= 2;
  102472. } else if ( p.belongsTo == 2 ) {
  102473. this.axesS[0].removeElements( p.min[0], p.max[0] );
  102474. this.axesS[1].removeElements( p.min[1], p.max[1] );
  102475. this.axesS[2].removeElements( p.min[2], p.max[2] );
  102476. this.numElementsS -= 2;
  102477. }*/
  102478. switch (p.belongsTo) {
  102479. case 1:
  102480. this.axesD[0].removeElements(p.min[0], p.max[0]);
  102481. this.axesD[1].removeElements(p.min[1], p.max[1]);
  102482. this.axesD[2].removeElements(p.min[2], p.max[2]);
  102483. this.numElementsD -= 2;
  102484. break;
  102485. case 2:
  102486. this.axesS[0].removeElements(p.min[0], p.max[0]);
  102487. this.axesS[1].removeElements(p.min[1], p.max[1]);
  102488. this.axesS[2].removeElements(p.min[2], p.max[2]);
  102489. this.numElementsS -= 2;
  102490. break;
  102491. }
  102492. p.belongsTo = 0;
  102493. };
  102494. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  102495. if (this.numElementsD == 0) return;
  102496. var axis1 = this.axesD[this.index1];
  102497. var axis2 = this.axesD[this.index2];
  102498. axis1.sort();
  102499. axis2.sort();
  102500. var count1 = axis1.calculateTestCount();
  102501. var count2 = axis2.calculateTestCount();
  102502. var elementsD;
  102503. var elementsS;
  102504. if (count1 <= count2) {// select the best axis
  102505. axis2 = this.axesS[this.index1];
  102506. axis2.sort();
  102507. elementsD = axis1.elements;
  102508. elementsS = axis2.elements;
  102509. } else {
  102510. axis1 = this.axesS[this.index2];
  102511. axis1.sort();
  102512. elementsD = axis2.elements;
  102513. elementsS = axis1.elements;
  102514. this.index1 ^= this.index2;
  102515. this.index2 ^= this.index1;
  102516. this.index1 ^= this.index2;
  102517. }
  102518. var activeD;
  102519. var activeS;
  102520. var p = 0;
  102521. var q = 0;
  102522. while (p < this.numElementsD) {
  102523. var e1;
  102524. var dyn;
  102525. if (q == this.numElementsS) {
  102526. e1 = elementsD[p];
  102527. dyn = true;
  102528. p++;
  102529. } else {
  102530. var d = elementsD[p];
  102531. var s = elementsS[q];
  102532. if (d.value < s.value) {
  102533. e1 = d;
  102534. dyn = true;
  102535. p++;
  102536. } else {
  102537. e1 = s;
  102538. dyn = false;
  102539. q++;
  102540. }
  102541. }
  102542. if (!e1.max) {
  102543. var s1 = e1.proxy.shape;
  102544. var min1 = e1.min1.value;
  102545. var max1 = e1.max1.value;
  102546. var min2 = e1.min2.value;
  102547. var max2 = e1.max2.value;
  102548. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  102549. var s2 = e2.proxy.shape;
  102550. this.numPairChecks++;
  102551. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  102552. this.addPair(s1, s2);
  102553. }
  102554. if (dyn) {
  102555. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  102556. s2 = e2.proxy.shape;
  102557. this.numPairChecks++;
  102558. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  102559. this.addPair(s1, s2);
  102560. }
  102561. e1.pair = activeD;
  102562. activeD = e1;
  102563. } else {
  102564. e1.pair = activeS;
  102565. activeS = e1;
  102566. }
  102567. } else {
  102568. var min = e1.pair;
  102569. if (dyn) {
  102570. if (min == activeD) {
  102571. activeD = activeD.pair;
  102572. continue;
  102573. } else {
  102574. e1 = activeD;
  102575. }
  102576. } else {
  102577. if (min == activeS) {
  102578. activeS = activeS.pair;
  102579. continue;
  102580. } else {
  102581. e1 = activeS;
  102582. }
  102583. }
  102584. do {
  102585. e2 = e1.pair;
  102586. if (e2 == min) {
  102587. e1.pair = e2.pair;
  102588. break;
  102589. }
  102590. e1 = e2;
  102591. } while (e1 != null);
  102592. }
  102593. }
  102594. this.index2 = (this.index1 | this.index2) ^ 3;
  102595. };
  102596. /**
  102597. * An element of proxies.
  102598. * @author saharan
  102599. */
  102600. OIMO.SAPElement = function (proxy, max) {
  102601. // The parent proxy
  102602. this.proxy = proxy;
  102603. // The pair element.
  102604. this.pair = null;
  102605. // The minimum element on other axis.
  102606. this.min1 = null;
  102607. // The maximum element on other axis.
  102608. this.max1 = null;
  102609. // The minimum element on other axis.
  102610. this.min2 = null;
  102611. // The maximum element on other axis.
  102612. this.max2 = null;
  102613. // Whether the element has maximum value or not.
  102614. this.max = max;
  102615. // The value of the element.
  102616. this.value = 0;
  102617. };
  102618. /**
  102619. * A proxy for sweep and prune broad-phase.
  102620. * @author saharan
  102621. * @author lo-th
  102622. */
  102623. OIMO.SAPProxy = function (sap, shape) {
  102624. OIMO.Proxy.call(this, shape);
  102625. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  102626. this.belongsTo = 0;
  102627. // The maximum elements on each axis.
  102628. this.max = [];
  102629. // The minimum elements on each axis.
  102630. this.min = [];
  102631. this.sap = sap;
  102632. this.min[0] = new OIMO.SAPElement(this, false);
  102633. this.max[0] = new OIMO.SAPElement(this, true);
  102634. this.min[1] = new OIMO.SAPElement(this, false);
  102635. this.max[1] = new OIMO.SAPElement(this, true);
  102636. this.min[2] = new OIMO.SAPElement(this, false);
  102637. this.max[2] = new OIMO.SAPElement(this, true);
  102638. this.max[0].pair = this.min[0];
  102639. this.max[1].pair = this.min[1];
  102640. this.max[2].pair = this.min[2];
  102641. this.min[0].min1 = this.min[1];
  102642. this.min[0].max1 = this.max[1];
  102643. this.min[0].min2 = this.min[2];
  102644. this.min[0].max2 = this.max[2];
  102645. this.min[1].min1 = this.min[0];
  102646. this.min[1].max1 = this.max[0];
  102647. this.min[1].min2 = this.min[2];
  102648. this.min[1].max2 = this.max[2];
  102649. this.min[2].min1 = this.min[0];
  102650. this.min[2].max1 = this.max[0];
  102651. this.min[2].min2 = this.min[1];
  102652. this.min[2].max2 = this.max[1];
  102653. };
  102654. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102655. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  102656. // Returns whether the proxy is dynamic or not.
  102657. OIMO.SAPProxy.prototype.isDynamic = function () {
  102658. var body = this.shape.parent;
  102659. return body.isDynamic && !body.sleeping;
  102660. };
  102661. OIMO.SAPProxy.prototype.update = function () {
  102662. var te = this.aabb.elements;
  102663. this.min[0].value = te[0];
  102664. this.min[1].value = te[1];
  102665. this.min[2].value = te[2];
  102666. this.max[0].value = te[3];
  102667. this.max[1].value = te[4];
  102668. this.max[2].value = te[5];
  102669. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  102670. this.sap.removeProxy(this);
  102671. this.sap.addProxy(this);
  102672. }
  102673. };
  102674. /**
  102675. * A dynamic bounding volume tree for the broad-phase algorithm.
  102676. * @author saharan
  102677. * @author lo-th
  102678. */
  102679. OIMO.DBVT = function () {
  102680. // The root of the tree.
  102681. this.root = null;
  102682. this.freeNodes = [];
  102683. this.freeNodes.length = 16384;
  102684. this.numFreeNodes = 0;
  102685. this.aabb = new OIMO.AABB();
  102686. };
  102687. OIMO.DBVT.prototype = {
  102688. constructor: OIMO.DBVT,
  102689. /**
  102690. * Move a leaf.
  102691. * @param leaf
  102692. */
  102693. moveLeaf: function (leaf) {
  102694. this.deleteLeaf(leaf);
  102695. this.insertLeaf(leaf);
  102696. },
  102697. /**
  102698. * Insert a leaf to the tree.
  102699. * @param node
  102700. */
  102701. insertLeaf: function (leaf) {
  102702. if (this.root == null) {
  102703. this.root = leaf;
  102704. return;
  102705. }
  102706. var lb = leaf.aabb;
  102707. var sibling = this.root;
  102708. var oldArea;
  102709. var newArea;
  102710. while (sibling.proxy == null) { // descend the node to search the best pair
  102711. var c1 = sibling.child1;
  102712. var c2 = sibling.child2;
  102713. var b = sibling.aabb;
  102714. var c1b = c1.aabb;
  102715. var c2b = c2.aabb;
  102716. oldArea = b.surfaceArea();
  102717. this.aabb.combine(lb, b);
  102718. newArea = this.aabb.surfaceArea();
  102719. var creatingCost = newArea * 2;
  102720. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  102721. var discendingCost1 = incrementalCost;
  102722. this.aabb.combine(lb, c1b);
  102723. if (c1.proxy != null) {
  102724. // leaf cost = area(combined aabb)
  102725. discendingCost1 += this.aabb.surfaceArea();
  102726. } else {
  102727. // node cost = area(combined aabb) - area(old aabb)
  102728. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  102729. }
  102730. var discendingCost2 = incrementalCost;
  102731. this.aabb.combine(lb, c2b);
  102732. if (c2.proxy != null) {
  102733. // leaf cost = area(combined aabb)
  102734. discendingCost2 += this.aabb.surfaceArea();
  102735. } else {
  102736. // node cost = area(combined aabb) - area(old aabb)
  102737. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  102738. }
  102739. if (discendingCost1 < discendingCost2) {
  102740. if (creatingCost < discendingCost1) {
  102741. break;// stop descending
  102742. } else {
  102743. sibling = c1;// descend into first child
  102744. }
  102745. } else {
  102746. if (creatingCost < discendingCost2) {
  102747. break;// stop descending
  102748. } else {
  102749. sibling = c2;// descend into second child
  102750. }
  102751. }
  102752. }
  102753. var oldParent = sibling.parent;
  102754. var newParent;
  102755. if (this.numFreeNodes > 0) {
  102756. newParent = this.freeNodes[--this.numFreeNodes];
  102757. } else {
  102758. newParent = new OIMO.DBVTNode();
  102759. }
  102760. newParent.parent = oldParent;
  102761. newParent.child1 = leaf;
  102762. newParent.child2 = sibling;
  102763. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  102764. newParent.height = sibling.height + 1;
  102765. sibling.parent = newParent;
  102766. leaf.parent = newParent;
  102767. if (sibling == this.root) {
  102768. // replace root
  102769. this.root = newParent;
  102770. } else {
  102771. // replace child
  102772. if (oldParent.child1 == sibling) {
  102773. oldParent.child1 = newParent;
  102774. } else {
  102775. oldParent.child2 = newParent;
  102776. }
  102777. }
  102778. // update whole tree
  102779. do {
  102780. newParent = this.balance(newParent);
  102781. this.fix(newParent);
  102782. newParent = newParent.parent;
  102783. } while (newParent != null);
  102784. },
  102785. getBalance: function (node) {
  102786. if (node.proxy != null) return 0;
  102787. return node.child1.height - node.child2.height;
  102788. },
  102789. /*print:function(node,indent,text){
  102790. var hasChild=node.proxy==null;
  102791. if(hasChild)text=this.print(node.child1,indent+1,text);
  102792. for(var i=indent*2;i>=0;i--){
  102793. text+=" ";
  102794. }
  102795. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  102796. if(hasChild)text=this.print(node.child2,indent+1,text);
  102797. return text;
  102798. },*/
  102799. /**
  102800. * Delete a leaf from the tree.
  102801. * @param node
  102802. */
  102803. deleteLeaf: function (leaf) {
  102804. if (leaf == this.root) {
  102805. this.root = null;
  102806. return;
  102807. }
  102808. var parent = leaf.parent;
  102809. var sibling;
  102810. if (parent.child1 == leaf) {
  102811. sibling = parent.child2;
  102812. } else {
  102813. sibling = parent.child1;
  102814. }
  102815. if (parent == this.root) {
  102816. this.root = sibling;
  102817. sibling.parent = null;
  102818. return;
  102819. }
  102820. var grandParent = parent.parent;
  102821. sibling.parent = grandParent;
  102822. if (grandParent.child1 == parent) {
  102823. grandParent.child1 = sibling;
  102824. } else {
  102825. grandParent.child2 = sibling;
  102826. }
  102827. if (this.numFreeNodes < 16384) {
  102828. this.freeNodes[this.numFreeNodes++] = parent;
  102829. }
  102830. do {
  102831. grandParent = this.balance(grandParent);
  102832. this.fix(grandParent);
  102833. grandParent = grandParent.parent;
  102834. } while (grandParent != null);
  102835. },
  102836. balance: function (node) {
  102837. var nh = node.height;
  102838. if (nh < 2) {
  102839. return node;
  102840. }
  102841. var p = node.parent;
  102842. var l = node.child1;
  102843. var r = node.child2;
  102844. var lh = l.height;
  102845. var rh = r.height;
  102846. var balance = lh - rh;
  102847. var t;// for bit operation
  102848. // [ N ]
  102849. // / \
  102850. // [ L ] [ R ]
  102851. // / \ / \
  102852. // [L-L] [L-R] [R-L] [R-R]
  102853. // Is the tree balanced?
  102854. if (balance > 1) {
  102855. var ll = l.child1;
  102856. var lr = l.child2;
  102857. var llh = ll.height;
  102858. var lrh = lr.height;
  102859. // Is L-L higher than L-R?
  102860. if (llh > lrh) {
  102861. // set N to L-R
  102862. l.child2 = node;
  102863. node.parent = l;
  102864. // [ L ]
  102865. // / \
  102866. // [L-L] [ N ]
  102867. // / \ / \
  102868. // [...] [...] [ L ] [ R ]
  102869. // set L-R
  102870. node.child1 = lr;
  102871. lr.parent = node;
  102872. // [ L ]
  102873. // / \
  102874. // [L-L] [ N ]
  102875. // / \ / \
  102876. // [...] [...] [L-R] [ R ]
  102877. // fix bounds and heights
  102878. node.aabb.combine(lr.aabb, r.aabb);
  102879. t = lrh - rh;
  102880. node.height = lrh - (t & t >> 31) + 1;
  102881. l.aabb.combine(ll.aabb, node.aabb);
  102882. t = llh - nh;
  102883. l.height = llh - (t & t >> 31) + 1;
  102884. } else {
  102885. // set N to L-L
  102886. l.child1 = node;
  102887. node.parent = l;
  102888. // [ L ]
  102889. // / \
  102890. // [ N ] [L-R]
  102891. // / \ / \
  102892. // [ L ] [ R ] [...] [...]
  102893. // set L-L
  102894. node.child1 = ll;
  102895. ll.parent = node;
  102896. // [ L ]
  102897. // / \
  102898. // [ N ] [L-R]
  102899. // / \ / \
  102900. // [L-L] [ R ] [...] [...]
  102901. // fix bounds and heights
  102902. node.aabb.combine(ll.aabb, r.aabb);
  102903. t = llh - rh;
  102904. node.height = llh - (t & t >> 31) + 1;
  102905. l.aabb.combine(node.aabb, lr.aabb);
  102906. t = nh - lrh;
  102907. l.height = nh - (t & t >> 31) + 1;
  102908. }
  102909. // set new parent of L
  102910. if (p != null) {
  102911. if (p.child1 == node) {
  102912. p.child1 = l;
  102913. } else {
  102914. p.child2 = l;
  102915. }
  102916. } else {
  102917. this.root = l;
  102918. }
  102919. l.parent = p;
  102920. return l;
  102921. } else if (balance < -1) {
  102922. var rl = r.child1;
  102923. var rr = r.child2;
  102924. var rlh = rl.height;
  102925. var rrh = rr.height;
  102926. // Is R-L higher than R-R?
  102927. if (rlh > rrh) {
  102928. // set N to R-R
  102929. r.child2 = node;
  102930. node.parent = r;
  102931. // [ R ]
  102932. // / \
  102933. // [R-L] [ N ]
  102934. // / \ / \
  102935. // [...] [...] [ L ] [ R ]
  102936. // set R-R
  102937. node.child2 = rr;
  102938. rr.parent = node;
  102939. // [ R ]
  102940. // / \
  102941. // [R-L] [ N ]
  102942. // / \ / \
  102943. // [...] [...] [ L ] [R-R]
  102944. // fix bounds and heights
  102945. node.aabb.combine(l.aabb, rr.aabb);
  102946. t = lh - rrh;
  102947. node.height = lh - (t & t >> 31) + 1;
  102948. r.aabb.combine(rl.aabb, node.aabb);
  102949. t = rlh - nh;
  102950. r.height = rlh - (t & t >> 31) + 1;
  102951. } else {
  102952. // set N to R-L
  102953. r.child1 = node;
  102954. node.parent = r;
  102955. // [ R ]
  102956. // / \
  102957. // [ N ] [R-R]
  102958. // / \ / \
  102959. // [ L ] [ R ] [...] [...]
  102960. // set R-L
  102961. node.child2 = rl;
  102962. rl.parent = node;
  102963. // [ R ]
  102964. // / \
  102965. // [ N ] [R-R]
  102966. // / \ / \
  102967. // [ L ] [R-L] [...] [...]
  102968. // fix bounds and heights
  102969. node.aabb.combine(l.aabb, rl.aabb);
  102970. t = lh - rlh;
  102971. node.height = lh - (t & t >> 31) + 1;
  102972. r.aabb.combine(node.aabb, rr.aabb);
  102973. t = nh - rrh;
  102974. r.height = nh - (t & t >> 31) + 1;
  102975. }
  102976. // set new parent of R
  102977. if (p != null) {
  102978. if (p.child1 == node) {
  102979. p.child1 = r;
  102980. } else {
  102981. p.child2 = r;
  102982. }
  102983. } else {
  102984. this.root = r;
  102985. }
  102986. r.parent = p;
  102987. return r;
  102988. }
  102989. return node;
  102990. },
  102991. fix: function (node) {
  102992. var c1 = node.child1;
  102993. var c2 = node.child2;
  102994. node.aabb.combine(c1.aabb, c2.aabb);
  102995. //var h1 = c1.height;
  102996. //var h2 = c2.height;
  102997. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  102998. /*if( h1 < h2 ) {
  102999. node.height = h2+1;
  103000. }else{
  103001. node.height = h1+1;
  103002. }*/
  103003. }
  103004. }
  103005. /**
  103006. * A broad-phase algorithm using dynamic bounding volume tree.
  103007. * @author saharan
  103008. * @author lo-th
  103009. */
  103010. OIMO.DBVTBroadPhase = function () {
  103011. OIMO.BroadPhase.call(this);
  103012. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  103013. this.tree = new OIMO.DBVT();
  103014. this.stack = [];
  103015. this.leaves = [];
  103016. this.numLeaves = 0;
  103017. };
  103018. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103019. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  103020. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  103021. return new OIMO.DBVTProxy(shape);
  103022. };
  103023. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  103024. this.tree.insertLeaf(proxy.leaf);
  103025. this.leaves.push(proxy.leaf);
  103026. this.numLeaves++;
  103027. };
  103028. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  103029. this.tree.deleteLeaf(proxy.leaf);
  103030. var n = this.leaves.indexOf(proxy.leaf);
  103031. if (n > -1) {
  103032. this.leaves.splice(n, 1);
  103033. this.numLeaves--;
  103034. }
  103035. };
  103036. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  103037. if (this.numLeaves < 2) return;
  103038. var leaf, margin = 0.1, i = this.numLeaves;
  103039. while (i--) {
  103040. leaf = this.leaves[i];
  103041. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  103042. leaf.aabb.copy(leaf.proxy.aabb, margin);
  103043. this.tree.deleteLeaf(leaf);
  103044. this.tree.insertLeaf(leaf);
  103045. this.collide(leaf, this.tree.root);
  103046. }
  103047. }
  103048. };
  103049. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  103050. var stackCount = 2;
  103051. var s1, s2, n1, n2, l1, l2;
  103052. this.stack[0] = node1;
  103053. this.stack[1] = node2;
  103054. while (stackCount > 0) {
  103055. n1 = this.stack[--stackCount];
  103056. n2 = this.stack[--stackCount];
  103057. l1 = n1.proxy != null;
  103058. l2 = n2.proxy != null;
  103059. this.numPairChecks++;
  103060. if (l1 && l2) {
  103061. s1 = n1.proxy.shape;
  103062. s2 = n2.proxy.shape;
  103063. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  103064. this.addPair(s1, s2);
  103065. } else {
  103066. if (n1.aabb.intersectTest(n2.aabb)) continue;
  103067. /*if(stackCount+4>=this.maxStack){// expand the stack
  103068. //this.maxStack<<=1;
  103069. this.maxStack*=2;
  103070. var newStack = [];// vector
  103071. newStack.length = this.maxStack;
  103072. for(var i=0;i<stackCount;i++){
  103073. newStack[i] = this.stack[i];
  103074. }
  103075. this.stack = newStack;
  103076. }*/
  103077. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  103078. this.stack[stackCount++] = n1.child1;
  103079. this.stack[stackCount++] = n2;
  103080. this.stack[stackCount++] = n1.child2;
  103081. this.stack[stackCount++] = n2;
  103082. } else {
  103083. this.stack[stackCount++] = n1;
  103084. this.stack[stackCount++] = n2.child1;
  103085. this.stack[stackCount++] = n1;
  103086. this.stack[stackCount++] = n2.child2;
  103087. }
  103088. }
  103089. }
  103090. };
  103091. /**
  103092. * A node of the dynamic bounding volume tree.
  103093. * @author saharan
  103094. */
  103095. OIMO.DBVTNode = function () {
  103096. // The first child node of this node.
  103097. this.child1 = null;
  103098. // The second child node of this node.
  103099. this.child2 = null;
  103100. // The parent node of this tree.
  103101. this.parent = null;
  103102. // The proxy of this node. This has no value if this node is not leaf.
  103103. this.proxy = null;
  103104. // The maximum distance from leaf nodes.
  103105. this.height = 0;
  103106. // The AABB of this node.
  103107. this.aabb = new OIMO.AABB();
  103108. };
  103109. /**
  103110. * A proxy for dynamic bounding volume tree broad-phase.
  103111. * @author saharan
  103112. */
  103113. OIMO.DBVTProxy = function (shape) {
  103114. OIMO.Proxy.call(this, shape);
  103115. // The leaf of the proxy.
  103116. this.leaf = new OIMO.DBVTNode();
  103117. this.leaf.proxy = this;
  103118. };
  103119. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103120. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  103121. OIMO.DBVTProxy.prototype.update = function () {
  103122. };
  103123. OIMO.World.prototype.add = function (obj) {
  103124. obj = obj || {};
  103125. var type = obj.type || "box";
  103126. if (typeof type === 'string') type = [type];// single shape
  103127. if (type[0].substring(0, 5) == 'joint') { // is joint
  103128. if (type[0] === 'joint') type[0] = 'jointHinge';
  103129. var axe1 = obj.axe1 || [1, 0, 0];
  103130. var axe2 = obj.axe2 || [1, 0, 0];
  103131. var pos1 = obj.pos1 || [0, 0, 0];
  103132. var pos2 = obj.pos2 || [0, 0, 0];
  103133. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  103134. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  103135. var min, max;
  103136. if (type[0] === "jointDistance") {
  103137. min = obj.min || 0;
  103138. max = obj.max || 10;
  103139. min = min * OIMO.INV_SCALE;
  103140. max = max * OIMO.INV_SCALE;
  103141. } else {
  103142. min = obj.min || 57.29578;
  103143. max = obj.max || 0;
  103144. min = min * OIMO.degtorad;
  103145. max = max * OIMO.degtorad;
  103146. }
  103147. var limit = obj.limit || null;
  103148. var spring = obj.spring || null;
  103149. var motor = obj.motor || null;
  103150. // joint setting
  103151. var jc = new OIMO.JointConfig();
  103152. jc.allowCollision = obj.collision || false;;
  103153. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  103154. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  103155. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  103156. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  103157. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  103158. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  103159. jc.body1 = obj.body1;
  103160. jc.body2 = obj.body2;
  103161. var joint;
  103162. switch (type[0]) {
  103163. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  103164. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  103165. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103166. break;
  103167. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  103168. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  103169. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103170. break;
  103171. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  103172. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  103173. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  103174. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  103175. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  103176. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  103177. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  103178. break;
  103179. }
  103180. joint.name = obj.name || '';
  103181. // finaly add to physics world
  103182. this.addJoint(joint);
  103183. return joint;
  103184. } else { // is body
  103185. // I'm dynamique or not
  103186. var move = obj.move || false;
  103187. // I can sleep or not
  103188. var noSleep = obj.noSleep || false;
  103189. // My start position
  103190. var p = obj.pos || [0, 0, 0];
  103191. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  103192. // My size
  103193. var s = obj.size || [1, 1, 1];
  103194. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  103195. // My rotation in degre
  103196. var rot = obj.rot || [0, 0, 0];
  103197. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  103198. var r = [];
  103199. for (var i = 0; i < rot.length / 3; i++) {
  103200. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  103201. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  103202. }
  103203. // My physics setting
  103204. var sc = new OIMO.ShapeConfig();
  103205. if (obj.sc !== undefined) sc = obj.sc;
  103206. if (obj.config) {
  103207. // The density of the shape.
  103208. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  103209. // The coefficient of friction of the shape.
  103210. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  103211. // The coefficient of restitution of the shape.
  103212. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  103213. // The bits of the collision groups to which the shape belongs.
  103214. sc.belongsTo = obj.config[3] || 1;
  103215. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  103216. // The bits of the collision groups with which the shape collides.
  103217. sc.collidesWith = obj.config[4] || 0xffffffff;
  103218. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  103219. }
  103220. // direct physics setting
  103221. if (obj.density !== undefined) sc.density = obj.density;
  103222. if (obj.friction !== undefined) sc.friction = obj.friction;
  103223. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  103224. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  103225. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  103226. if (obj.massPos) {
  103227. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  103228. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  103229. }
  103230. if (obj.massRot) {
  103231. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  103232. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  103233. }
  103234. // My rigidbody
  103235. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  103236. // My shapes
  103237. var shapes = [];
  103238. //if( typeof type === 'string' ) type = [type];// single shape
  103239. var n, n2;
  103240. for (var i = 0; i < type.length; i++) {
  103241. n = i * 3;
  103242. n2 = i * 4;
  103243. switch (type[i]) {
  103244. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  103245. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  103246. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  103247. }
  103248. body.addShape(shapes[i]);
  103249. if (i > 0) {
  103250. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  103251. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  103252. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  103253. }
  103254. }
  103255. // I'm static or i move
  103256. if (move) {
  103257. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  103258. else body.setupMass(0x1, true);
  103259. if (noSleep) body.allowSleep = false;
  103260. else body.allowSleep = true;
  103261. } else {
  103262. body.setupMass(0x2);
  103263. }
  103264. body.name = obj.name || ' ';
  103265. // finaly add to physics world
  103266. this.addRigidBody(body);
  103267. return body;
  103268. }
  103269. }
  103270. //UMD simplified
  103271. var root = this;
  103272. if (!root['OIMO']) {
  103273. if (true)
  103274. module.exports = OIMO;
  103275. else if (typeof define === 'function' && define.amd)
  103276. define([], function () {
  103277. return OIMO;
  103278. });
  103279. else if (typeof exports === 'object')
  103280. exports["OIMO"] = OIMO;
  103281. else {
  103282. root["OIMO"] = OIMO;
  103283. }
  103284. }
  103285. /***/ }),
  103286. /* 19 */
  103287. /***/ (function(module, exports, __webpack_require__) {
  103288. "use strict";
  103289. Object.defineProperty(exports, "__esModule", { value: true });
  103290. var babylonjs_1 = __webpack_require__(0);
  103291. var helper_1 = __webpack_require__(2);
  103292. var TemplateManager = (function () {
  103293. function TemplateManager(containerElement) {
  103294. this.containerElement = containerElement;
  103295. this.templates = {};
  103296. this.onInit = new babylonjs_1.Observable();
  103297. this.onLoaded = new babylonjs_1.Observable();
  103298. this.onStateChange = new babylonjs_1.Observable();
  103299. this.onAllLoaded = new babylonjs_1.Observable();
  103300. this.onEventTriggered = new babylonjs_1.Observable();
  103301. this.eventManager = new eventManager_1.EventManager(this);
  103302. }
  103303. TemplateManager.prototype.initTemplate = function (templates) {
  103304. var _this = this;
  103305. var internalInit = function (dependencyMap, name, parentTemplate) {
  103306. var template = _this.templates[name];
  103307. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  103308. return internalInit(dependencyMap[childName], childName, template);
  103309. });
  103310. var addToParent = function () {
  103311. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  103312. template.appendTo(containingElement);
  103313. _this.checkLoadedState();
  103314. };
  103315. if (parentTemplate && !parentTemplate.parent) {
  103316. parentTemplate.onAppended.add(function () {
  103317. addToParent();
  103318. });
  103319. }
  103320. else {
  103321. addToParent();
  103322. }
  103323. return template;
  103324. };
  103325. return this.buildHTMLTree(templates).then(function (htmlTree) {
  103326. if (_this.templates['main']) {
  103327. internalInit(htmlTree, 'main');
  103328. }
  103329. else {
  103330. _this.checkLoadedState();
  103331. }
  103332. return;
  103333. });
  103334. };
  103335. TemplateManager.prototype.buildHTMLTree = function (templates) {
  103336. var _this = this;
  103337. var promises = Object.keys(templates).map(function (name) {
  103338. if (!templates[name])
  103339. return Promise.resolve(false);
  103340. var template = new Template(name, templates[name]);
  103341. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  103342. _this.templates[name] = template;
  103343. return template.initPromise;
  103344. });
  103345. return Promise.all(promises).then(function () {
  103346. var templateStructure = {};
  103347. var buildTree = function (parentObject, name) {
  103348. _this.templates[name].isInHtmlTree = true;
  103349. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  103350. childNodes.forEach(function (element) {
  103351. parentObject[element] = {};
  103352. buildTree(parentObject[element], element);
  103353. });
  103354. };
  103355. if (_this.templates['main']) {
  103356. buildTree(templateStructure, "main");
  103357. }
  103358. return templateStructure;
  103359. });
  103360. };
  103361. TemplateManager.prototype.getCanvas = function () {
  103362. return this.containerElement.querySelector('canvas');
  103363. };
  103364. TemplateManager.prototype.getTemplate = function (name) {
  103365. return this.templates[name];
  103366. };
  103367. TemplateManager.prototype.checkLoadedState = function () {
  103368. var _this = this;
  103369. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  103370. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  103371. });
  103372. if (done) {
  103373. this.onAllLoaded.notifyObservers(this);
  103374. }
  103375. };
  103376. TemplateManager.prototype.dispose = function () {
  103377. var _this = this;
  103378. Object.keys(this.templates).forEach(function (template) {
  103379. _this.templates[template].dispose();
  103380. });
  103381. this.onInit.clear();
  103382. this.onAllLoaded.clear();
  103383. this.onEventTriggered.clear();
  103384. this.onLoaded.clear();
  103385. this.onStateChange.clear();
  103386. };
  103387. return TemplateManager;
  103388. }());
  103389. exports.TemplateManager = TemplateManager;
  103390. var Handlebars = __webpack_require__(20);
  103391. var eventManager_1 = __webpack_require__(21);
  103392. Handlebars.registerHelper('eachInMap', function (map, block) {
  103393. var out = '';
  103394. Object.keys(map).map(function (prop) {
  103395. var data = map[prop];
  103396. if (typeof data === 'object') {
  103397. data.id = data.id || prop;
  103398. out += block.fn(data);
  103399. }
  103400. else {
  103401. out += block.fn({ id: prop, value: data });
  103402. }
  103403. });
  103404. return out;
  103405. });
  103406. var Template = (function () {
  103407. function Template(name, _configuration) {
  103408. var _this = this;
  103409. this.name = name;
  103410. this._configuration = _configuration;
  103411. this.onInit = new babylonjs_1.Observable();
  103412. this.onLoaded = new babylonjs_1.Observable();
  103413. this.onAppended = new babylonjs_1.Observable();
  103414. this.onStateChange = new babylonjs_1.Observable();
  103415. this.onEventTriggered = new babylonjs_1.Observable();
  103416. this.loadRequests = [];
  103417. this.isLoaded = false;
  103418. this.isShown = false;
  103419. this.isInHtmlTree = false;
  103420. this.onInit.notifyObservers(this);
  103421. var htmlContentPromise = this.getTemplateAsHtml(_configuration);
  103422. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  103423. if (htmlTemplate) {
  103424. _this.htmlTemplate = htmlTemplate;
  103425. var compiledTemplate = Handlebars.compile(htmlTemplate);
  103426. var config = _this._configuration.params || {};
  103427. var rawHtml = compiledTemplate(config);
  103428. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  103429. _this.isLoaded = true;
  103430. _this.isShown = true;
  103431. _this.onLoaded.notifyObservers(_this);
  103432. }
  103433. return _this;
  103434. });
  103435. }
  103436. Template.prototype.updateParams = function (params) {
  103437. this._configuration.params = params;
  103438. if (this.isLoaded) {
  103439. this.dispose();
  103440. }
  103441. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  103442. var config = this._configuration.params || {};
  103443. var rawHtml = compiledTemplate(config);
  103444. this.fragment = document.createRange().createContextualFragment(rawHtml);
  103445. if (this.parent) {
  103446. this.appendTo(this.parent, true);
  103447. }
  103448. };
  103449. Object.defineProperty(Template.prototype, "configuration", {
  103450. get: function () {
  103451. return this._configuration;
  103452. },
  103453. enumerable: true,
  103454. configurable: true
  103455. });
  103456. Template.prototype.getChildElements = function () {
  103457. var childrenArray = [];
  103458. var children = this.fragment.children;
  103459. if (!children) {
  103460. children = this.fragment.querySelectorAll('*');
  103461. }
  103462. for (var i = 0; i < children.length; ++i) {
  103463. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  103464. }
  103465. return childrenArray;
  103466. };
  103467. Template.prototype.appendTo = function (parent, forceRemove) {
  103468. var _this = this;
  103469. if (this.parent) {
  103470. if (forceRemove) {
  103471. this.parent.removeChild(this.fragment);
  103472. }
  103473. else {
  103474. return;
  103475. }
  103476. }
  103477. this.parent = parent;
  103478. if (this._configuration.id) {
  103479. this.parent.id = this._configuration.id;
  103480. }
  103481. this.fragment = this.parent.appendChild(this.fragment);
  103482. setTimeout(function () {
  103483. _this.registerEvents();
  103484. _this.onAppended.notifyObservers(_this);
  103485. });
  103486. };
  103487. Template.prototype.show = function (visibilityFunction) {
  103488. var _this = this;
  103489. if (this.isHiding)
  103490. return Promise.resolve(this);
  103491. return Promise.resolve().then(function () {
  103492. _this.isShowing = true;
  103493. if (visibilityFunction) {
  103494. return visibilityFunction(_this);
  103495. }
  103496. else {
  103497. _this.parent.style.display = 'flex';
  103498. return _this;
  103499. }
  103500. }).then(function () {
  103501. _this.isShown = true;
  103502. _this.isShowing = false;
  103503. _this.onStateChange.notifyObservers(_this);
  103504. return _this;
  103505. });
  103506. };
  103507. Template.prototype.hide = function (visibilityFunction) {
  103508. var _this = this;
  103509. if (this.isShowing)
  103510. return Promise.resolve(this);
  103511. return Promise.resolve().then(function () {
  103512. _this.isHiding = true;
  103513. if (visibilityFunction) {
  103514. return visibilityFunction(_this);
  103515. }
  103516. else {
  103517. _this.parent.style.display = 'hide';
  103518. return _this;
  103519. }
  103520. }).then(function () {
  103521. _this.isShown = false;
  103522. _this.isHiding = false;
  103523. _this.onStateChange.notifyObservers(_this);
  103524. return _this;
  103525. });
  103526. };
  103527. Template.prototype.dispose = function () {
  103528. this.onAppended.clear();
  103529. this.onEventTriggered.clear();
  103530. this.onInit.clear();
  103531. this.onLoaded.clear();
  103532. this.onStateChange.clear();
  103533. this.isLoaded = false;
  103534. this.parent.removeChild(this.fragment);
  103535. this.loadRequests.forEach(function (request) {
  103536. request.abort();
  103537. });
  103538. };
  103539. Template.prototype.getTemplateAsHtml = function (templateConfig) {
  103540. var _this = this;
  103541. if (!templateConfig) {
  103542. return Promise.reject('No templateConfig provided');
  103543. }
  103544. else if (templateConfig.html !== undefined) {
  103545. return Promise.resolve(templateConfig.html);
  103546. }
  103547. else {
  103548. var location_1 = getTemplateLocation(templateConfig);
  103549. if (helper_1.isUrl(location_1)) {
  103550. return new Promise(function (resolve, reject) {
  103551. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  103552. resolve(data);
  103553. }, undefined, undefined, false, function (request, error) {
  103554. reject(error);
  103555. });
  103556. _this.loadRequests.push(fileRequest);
  103557. });
  103558. }
  103559. else {
  103560. location_1 = location_1.replace('#', '');
  103561. var element = document.getElementById(location_1);
  103562. if (element) {
  103563. return Promise.resolve(element.innerHTML);
  103564. }
  103565. else {
  103566. return Promise.reject('Template ID not found');
  103567. }
  103568. }
  103569. }
  103570. };
  103571. Template.prototype.registerEvents = function () {
  103572. var _this = this;
  103573. this.registeredEvents = this.registeredEvents || [];
  103574. if (this.registeredEvents.length) {
  103575. this.registeredEvents.forEach(function (evt) {
  103576. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  103577. });
  103578. }
  103579. if (this._configuration.events) {
  103580. var _loop_1 = function (eventName) {
  103581. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  103582. var functionToFire_1 = function (selector, event) {
  103583. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  103584. };
  103585. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  103586. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  103587. }
  103588. else if (typeof this_1._configuration.events[eventName] === 'object') {
  103589. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  103590. var event_1 = this_1._configuration.events[eventName] || {};
  103591. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  103592. if (selector && selector.indexOf('#') !== 0) {
  103593. selector = '#' + selector;
  103594. }
  103595. var htmlElement = _this.parent.querySelector(selector);
  103596. if (htmlElement) {
  103597. var binding = functionToFire_1.bind(_this, selector);
  103598. htmlElement.addEventListener(eventName, binding, false);
  103599. _this.registeredEvents.push({
  103600. htmlElement: htmlElement,
  103601. eventName: eventName,
  103602. function: binding
  103603. });
  103604. }
  103605. });
  103606. }
  103607. }
  103608. };
  103609. var this_1 = this;
  103610. for (var eventName in this._configuration.events) {
  103611. _loop_1(eventName);
  103612. }
  103613. }
  103614. };
  103615. return Template;
  103616. }());
  103617. exports.Template = Template;
  103618. function getTemplateLocation(templateConfig) {
  103619. if (!templateConfig || typeof templateConfig === 'string') {
  103620. return templateConfig;
  103621. }
  103622. else {
  103623. return templateConfig.location;
  103624. }
  103625. }
  103626. exports.getTemplateLocation = getTemplateLocation;
  103627. /***/ }),
  103628. /* 20 */
  103629. /***/ (function(module, exports, __webpack_require__) {
  103630. /**!
  103631. @license
  103632. handlebars v4.0.11
  103633. Copyright (C) 2011-2017 by Yehuda Katz
  103634. Permission is hereby granted, free of charge, to any person obtaining a copy
  103635. of this software and associated documentation files (the "Software"), to deal
  103636. in the Software without restriction, including without limitation the rights
  103637. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  103638. copies of the Software, and to permit persons to whom the Software is
  103639. furnished to do so, subject to the following conditions:
  103640. The above copyright notice and this permission notice shall be included in
  103641. all copies or substantial portions of the Software.
  103642. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  103643. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  103644. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  103645. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  103646. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  103647. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  103648. THE SOFTWARE.
  103649. */
  103650. !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],
  103651. 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){
  103652. 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"]}])});
  103653. /***/ }),
  103654. /* 21 */
  103655. /***/ (function(module, exports, __webpack_require__) {
  103656. "use strict";
  103657. Object.defineProperty(exports, "__esModule", { value: true });
  103658. var EventManager = (function () {
  103659. function EventManager(templateManager) {
  103660. var _this = this;
  103661. this.templateManager = templateManager;
  103662. this.callbacksContainer = {};
  103663. this.templateManager.onEventTriggered.add(function (eventData) {
  103664. _this.eventTriggered(eventData);
  103665. });
  103666. }
  103667. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  103668. if (!this.callbacksContainer[templateName]) {
  103669. this.callbacksContainer[templateName] = [];
  103670. }
  103671. this.callbacksContainer[templateName].push({
  103672. eventType: eventType,
  103673. callback: callback
  103674. });
  103675. };
  103676. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  103677. var callbackDefs = this.callbacksContainer[templateName] || [];
  103678. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  103679. };
  103680. EventManager.prototype.eventTriggered = function (data) {
  103681. var templateName = data.template.name;
  103682. var eventType = data.event.type;
  103683. var selector = data.selector;
  103684. var callbackDefs = this.callbacksContainer[templateName] || [];
  103685. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  103686. callbackDef.callback(data);
  103687. });
  103688. };
  103689. return EventManager;
  103690. }());
  103691. exports.EventManager = EventManager;
  103692. /***/ }),
  103693. /* 22 */
  103694. /***/ (function(module, exports, __webpack_require__) {
  103695. "use strict";
  103696. Object.defineProperty(exports, "__esModule", { value: true });
  103697. var mappers_1 = __webpack_require__(1);
  103698. var types_1 = __webpack_require__(23);
  103699. var deepmerge = __webpack_require__(13);
  103700. var babylonjs_1 = __webpack_require__(0);
  103701. var ConfigurationLoader = (function () {
  103702. function ConfigurationLoader() {
  103703. this.configurationCache = {};
  103704. this.loadRequests = [];
  103705. }
  103706. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  103707. var _this = this;
  103708. if (initConfig === void 0) { initConfig = {}; }
  103709. var loadedConfig = deepmerge({}, initConfig);
  103710. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  103711. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  103712. if (loadedConfig.configuration) {
  103713. var mapperType_1 = "json";
  103714. return Promise.resolve().then(function () {
  103715. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  103716. var url = '';
  103717. if (typeof loadedConfig.configuration === "string") {
  103718. url = loadedConfig.configuration;
  103719. }
  103720. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  103721. url = loadedConfig.configuration.url;
  103722. var type = loadedConfig.configuration.mapper;
  103723. if (!type) {
  103724. type = loadedConfig.configuration.url.split('.').pop();
  103725. }
  103726. mapperType_1 = type || mapperType_1;
  103727. }
  103728. return _this.loadFile(url);
  103729. }
  103730. else {
  103731. if (typeof loadedConfig.configuration === "object") {
  103732. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  103733. return loadedConfig.configuration.payload || {};
  103734. }
  103735. return {};
  103736. }
  103737. }).then(function (data) {
  103738. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  103739. var parsed = mapper.map(data);
  103740. var merged = deepmerge(loadedConfig, parsed);
  103741. if (callback)
  103742. callback(merged);
  103743. return merged;
  103744. });
  103745. }
  103746. else {
  103747. if (callback)
  103748. callback(loadedConfig);
  103749. return Promise.resolve(loadedConfig);
  103750. }
  103751. };
  103752. ConfigurationLoader.prototype.dispose = function () {
  103753. this.loadRequests.forEach(function (request) {
  103754. request.abort();
  103755. });
  103756. };
  103757. ConfigurationLoader.prototype.loadFile = function (url) {
  103758. var _this = this;
  103759. var cacheReference = this.configurationCache;
  103760. if (cacheReference[url]) {
  103761. return Promise.resolve(cacheReference[url]);
  103762. }
  103763. return new Promise(function (resolve, reject) {
  103764. var fileRequest = babylonjs_1.Tools.LoadFile(url, resolve, undefined, undefined, false, function (request, error) {
  103765. reject(error);
  103766. });
  103767. _this.loadRequests.push(fileRequest);
  103768. });
  103769. };
  103770. return ConfigurationLoader;
  103771. }());
  103772. exports.ConfigurationLoader = ConfigurationLoader;
  103773. exports.configurationLoader = new ConfigurationLoader();
  103774. exports.default = exports.configurationLoader;
  103775. /***/ }),
  103776. /* 23 */
  103777. /***/ (function(module, exports, __webpack_require__) {
  103778. "use strict";
  103779. Object.defineProperty(exports, "__esModule", { value: true });
  103780. var minimal_1 = __webpack_require__(24);
  103781. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  103782. var default_1 = __webpack_require__(25);
  103783. exports.defaultConfiguration = default_1.defaultConfiguration;
  103784. var getConfigurationType = function (type) {
  103785. switch (type) {
  103786. case 'default':
  103787. return default_1.defaultConfiguration;
  103788. case 'minimal':
  103789. return minimal_1.minimalConfiguration;
  103790. case 'none':
  103791. return {};
  103792. default:
  103793. return default_1.defaultConfiguration;
  103794. }
  103795. };
  103796. exports.getConfigurationType = getConfigurationType;
  103797. /***/ }),
  103798. /* 24 */
  103799. /***/ (function(module, exports, __webpack_require__) {
  103800. "use strict";
  103801. Object.defineProperty(exports, "__esModule", { value: true });
  103802. exports.minimalConfiguration = {
  103803. version: "0.1",
  103804. templates: {
  103805. main: {
  103806. html: __webpack_require__(6)
  103807. },
  103808. loadingScreen: {
  103809. html: __webpack_require__(7),
  103810. params: {
  103811. backgroundColor: "#000000",
  103812. loadingImage: __webpack_require__(8)
  103813. }
  103814. },
  103815. viewer: {
  103816. html: __webpack_require__(9),
  103817. },
  103818. overlay: {
  103819. html: __webpack_require__(10),
  103820. params: {
  103821. closeImage: __webpack_require__(11),
  103822. closeText: 'Close'
  103823. }
  103824. },
  103825. error: {
  103826. html: __webpack_require__(12)
  103827. }
  103828. },
  103829. engine: {
  103830. antialiasing: true
  103831. }
  103832. };
  103833. /***/ }),
  103834. /* 25 */
  103835. /***/ (function(module, exports, __webpack_require__) {
  103836. "use strict";
  103837. Object.defineProperty(exports, "__esModule", { value: true });
  103838. exports.defaultConfiguration = {
  103839. version: "3.2.0-alpha4",
  103840. templates: {
  103841. main: {
  103842. html: __webpack_require__(6)
  103843. },
  103844. loadingScreen: {
  103845. html: __webpack_require__(7),
  103846. params: {
  103847. backgroundColor: "#000000",
  103848. loadingImage: __webpack_require__(8)
  103849. }
  103850. },
  103851. viewer: {
  103852. html: __webpack_require__(9),
  103853. events: {
  103854. pointerout: true,
  103855. pointerdown: true,
  103856. pointerup: true
  103857. }
  103858. },
  103859. navBar: {
  103860. html: __webpack_require__(26),
  103861. params: {
  103862. buttons: {
  103863. "fullscreen-button": {
  103864. altText: "Fullscreen",
  103865. image: __webpack_require__(27)
  103866. }
  103867. },
  103868. visibilityTimeout: 2000
  103869. },
  103870. events: {
  103871. pointerdown: { 'fullscreen-button': true },
  103872. pointerover: true
  103873. }
  103874. },
  103875. overlay: {
  103876. html: __webpack_require__(10),
  103877. params: {
  103878. closeImage: __webpack_require__(11),
  103879. closeText: 'Close'
  103880. }
  103881. },
  103882. help: {
  103883. html: __webpack_require__(28)
  103884. },
  103885. share: {
  103886. html: __webpack_require__(29)
  103887. },
  103888. error: {
  103889. html: __webpack_require__(12)
  103890. }
  103891. },
  103892. camera: {
  103893. behaviors: {
  103894. autoRotate: 0,
  103895. framing: {
  103896. type: 2,
  103897. zoomOnBoundingInfo: true,
  103898. zoomStopsAnimation: false
  103899. }
  103900. }
  103901. },
  103902. skybox: {
  103903. pbr: true,
  103904. blur: 0.7,
  103905. infiniteDIstance: false,
  103906. },
  103907. ground: true,
  103908. engine: {
  103909. antialiasing: true
  103910. },
  103911. scene: {
  103912. imageProcessingConfiguration: {
  103913. exposure: 1.4,
  103914. contrast: 1.66,
  103915. toneMappingEnabled: true
  103916. }
  103917. }
  103918. };
  103919. /***/ }),
  103920. /* 26 */
  103921. /***/ (function(module, exports) {
  103922. 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>";
  103923. /***/ }),
  103924. /* 27 */
  103925. /***/ (function(module, exports) {
  103926. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  103927. /***/ }),
  103928. /* 28 */
  103929. /***/ (function(module, exports) {
  103930. module.exports = "HELP";
  103931. /***/ }),
  103932. /* 29 */
  103933. /***/ (function(module, exports) {
  103934. module.exports = "SHARE";
  103935. /***/ }),
  103936. /* 30 */
  103937. /***/ (function(module, exports, __webpack_require__) {
  103938. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  103939. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  103940. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  103941. 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;
  103942. return c > 3 && r && Object.defineProperty(target, key, r), r;
  103943. };
  103944. var __extends = (this && this.__extends) || (function () {
  103945. var extendStatics = Object.setPrototypeOf ||
  103946. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  103947. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  103948. return function (d, b) {
  103949. extendStatics(d, b);
  103950. function __() { this.constructor = d; }
  103951. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  103952. };
  103953. })();
  103954. (function universalModuleDefinition(root, factory) {
  103955. if(true)
  103956. module.exports = factory(__webpack_require__(0));
  103957. else if(typeof define === 'function' && define.amd)
  103958. define("babylonjs-loaders", ["babylonjs"], factory);
  103959. else if(typeof exports === 'object')
  103960. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  103961. else {
  103962. root["BABYLON"] = factory(root["BABYLON"]);
  103963. }
  103964. })(this, function(BABYLON) {
  103965. var BABYLON;
  103966. (function (BABYLON) {
  103967. var STLFileLoader = /** @class */ (function () {
  103968. function STLFileLoader() {
  103969. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  103970. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  103971. 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;
  103972. 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;
  103973. this.name = "stl";
  103974. // force data to come in as an ArrayBuffer
  103975. // we'll convert to string if it looks like it's an ASCII .stl
  103976. this.extensions = {
  103977. ".stl": { isBinary: true },
  103978. };
  103979. }
  103980. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  103981. var matches;
  103982. if (this.isBinary(data)) {
  103983. // binary .stl
  103984. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  103985. this.parseBinary(babylonMesh, data);
  103986. if (meshes) {
  103987. meshes.push(babylonMesh);
  103988. }
  103989. return true;
  103990. }
  103991. // ASCII .stl
  103992. // convert to string
  103993. var array_buffer = new Uint8Array(data);
  103994. var str = '';
  103995. for (var i = 0; i < data.byteLength; i++) {
  103996. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  103997. }
  103998. data = str;
  103999. while (matches = this.solidPattern.exec(data)) {
  104000. var meshName = matches[1];
  104001. var meshNameFromEnd = matches[3];
  104002. if (meshName != meshNameFromEnd) {
  104003. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  104004. return false;
  104005. }
  104006. // check meshesNames
  104007. if (meshesNames && meshName) {
  104008. if (meshesNames instanceof Array) {
  104009. if (!meshesNames.indexOf(meshName)) {
  104010. continue;
  104011. }
  104012. }
  104013. else {
  104014. if (meshName !== meshesNames) {
  104015. continue;
  104016. }
  104017. }
  104018. }
  104019. // stl mesh name can be empty as well
  104020. meshName = meshName || "stlmesh";
  104021. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  104022. this.parseASCII(babylonMesh, matches[2]);
  104023. if (meshes) {
  104024. meshes.push(babylonMesh);
  104025. }
  104026. }
  104027. return true;
  104028. };
  104029. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  104030. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  104031. if (result) {
  104032. scene.createDefaultCameraOrLight();
  104033. }
  104034. return result;
  104035. };
  104036. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  104037. var container = new BABYLON.AssetContainer(scene);
  104038. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  104039. container.removeAllFromScene();
  104040. return container;
  104041. };
  104042. STLFileLoader.prototype.isBinary = function (data) {
  104043. // check if file size is correct for binary stl
  104044. var faceSize, nFaces, reader;
  104045. reader = new DataView(data);
  104046. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  104047. nFaces = reader.getUint32(80, true);
  104048. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  104049. return true;
  104050. }
  104051. // check characters higher than ASCII to confirm binary
  104052. var fileLength = reader.byteLength;
  104053. for (var index = 0; index < fileLength; index++) {
  104054. if (reader.getUint8(index) > 127) {
  104055. return true;
  104056. }
  104057. }
  104058. return false;
  104059. };
  104060. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  104061. var reader = new DataView(data);
  104062. var faces = reader.getUint32(80, true);
  104063. var dataOffset = 84;
  104064. var faceLength = 12 * 4 + 2;
  104065. var offset = 0;
  104066. var positions = new Float32Array(faces * 3 * 3);
  104067. var normals = new Float32Array(faces * 3 * 3);
  104068. var indices = new Uint32Array(faces * 3);
  104069. var indicesCount = 0;
  104070. for (var face = 0; face < faces; face++) {
  104071. var start = dataOffset + face * faceLength;
  104072. var normalX = reader.getFloat32(start, true);
  104073. var normalY = reader.getFloat32(start + 4, true);
  104074. var normalZ = reader.getFloat32(start + 8, true);
  104075. for (var i = 1; i <= 3; i++) {
  104076. var vertexstart = start + i * 12;
  104077. // ordering is intentional to match ascii import
  104078. positions[offset] = reader.getFloat32(vertexstart, true);
  104079. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  104080. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  104081. normals[offset] = normalX;
  104082. normals[offset + 2] = normalY;
  104083. normals[offset + 1] = normalZ;
  104084. offset += 3;
  104085. }
  104086. indices[indicesCount] = indicesCount++;
  104087. indices[indicesCount] = indicesCount++;
  104088. indices[indicesCount] = indicesCount++;
  104089. }
  104090. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104091. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104092. mesh.setIndices(indices);
  104093. mesh.computeWorldMatrix(true);
  104094. };
  104095. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  104096. var positions = [];
  104097. var normals = [];
  104098. var indices = [];
  104099. var indicesCount = 0;
  104100. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  104101. var matches;
  104102. while (matches = this.facetsPattern.exec(solidData)) {
  104103. var facet = matches[1];
  104104. //one normal per face
  104105. var normalMatches = this.normalPattern.exec(facet);
  104106. this.normalPattern.lastIndex = 0;
  104107. if (!normalMatches) {
  104108. continue;
  104109. }
  104110. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  104111. var vertexMatch;
  104112. while (vertexMatch = this.vertexPattern.exec(facet)) {
  104113. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  104114. normals.push(normal[0], normal[1], normal[2]);
  104115. }
  104116. indices.push(indicesCount++, indicesCount++, indicesCount++);
  104117. this.vertexPattern.lastIndex = 0;
  104118. }
  104119. this.facetsPattern.lastIndex = 0;
  104120. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104121. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104122. mesh.setIndices(indices);
  104123. mesh.computeWorldMatrix(true);
  104124. };
  104125. return STLFileLoader;
  104126. }());
  104127. BABYLON.STLFileLoader = STLFileLoader;
  104128. if (BABYLON.SceneLoader) {
  104129. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  104130. }
  104131. })(BABYLON || (BABYLON = {}));
  104132. //# sourceMappingURL=babylon.stlFileLoader.js.map
  104133. var BABYLON;
  104134. (function (BABYLON) {
  104135. /**
  104136. * Class reading and parsing the MTL file bundled with the obj file.
  104137. */
  104138. var MTLFileLoader = /** @class */ (function () {
  104139. function MTLFileLoader() {
  104140. // All material loaded from the mtl will be set here
  104141. this.materials = [];
  104142. }
  104143. /**
  104144. * This function will read the mtl file and create each material described inside
  104145. * This function could be improve by adding :
  104146. * -some component missing (Ni, Tf...)
  104147. * -including the specific options available
  104148. *
  104149. * @param scene
  104150. * @param data
  104151. * @param rootUrl
  104152. */
  104153. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  104154. //Split the lines from the file
  104155. var lines = data.split('\n');
  104156. //Space char
  104157. var delimiter_pattern = /\s+/;
  104158. //Array with RGB colors
  104159. var color;
  104160. //New material
  104161. var material = null;
  104162. //Look at each line
  104163. for (var i = 0; i < lines.length; i++) {
  104164. var line = lines[i].trim();
  104165. // Blank line or comment
  104166. if (line.length === 0 || line.charAt(0) === '#') {
  104167. continue;
  104168. }
  104169. //Get the first parameter (keyword)
  104170. var pos = line.indexOf(' ');
  104171. var key = (pos >= 0) ? line.substring(0, pos) : line;
  104172. key = key.toLowerCase();
  104173. //Get the data following the key
  104174. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  104175. //This mtl keyword will create the new material
  104176. if (key === "newmtl") {
  104177. //Check if it is the first material.
  104178. // Materials specifications are described after this keyword.
  104179. if (material) {
  104180. //Add the previous material in the material array.
  104181. this.materials.push(material);
  104182. }
  104183. //Create a new material.
  104184. // value is the name of the material read in the mtl file
  104185. material = new BABYLON.StandardMaterial(value, scene);
  104186. }
  104187. else if (key === "kd" && material) {
  104188. // Diffuse color (color under white light) using RGB values
  104189. //value = "r g b"
  104190. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104191. //color = [r,g,b]
  104192. //Set tghe color into the material
  104193. material.diffuseColor = BABYLON.Color3.FromArray(color);
  104194. }
  104195. else if (key === "ka" && material) {
  104196. // Ambient color (color under shadow) using RGB values
  104197. //value = "r g b"
  104198. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104199. //color = [r,g,b]
  104200. //Set tghe color into the material
  104201. material.ambientColor = BABYLON.Color3.FromArray(color);
  104202. }
  104203. else if (key === "ks" && material) {
  104204. // Specular color (color when light is reflected from shiny surface) using RGB values
  104205. //value = "r g b"
  104206. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104207. //color = [r,g,b]
  104208. //Set the color into the material
  104209. material.specularColor = BABYLON.Color3.FromArray(color);
  104210. }
  104211. else if (key === "ke" && material) {
  104212. // Emissive color using RGB values
  104213. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104214. material.emissiveColor = BABYLON.Color3.FromArray(color);
  104215. }
  104216. else if (key === "ns" && material) {
  104217. //value = "Integer"
  104218. material.specularPower = parseFloat(value);
  104219. }
  104220. else if (key === "d" && material) {
  104221. //d is dissolve for current material. It mean alpha for BABYLON
  104222. material.alpha = parseFloat(value);
  104223. //Texture
  104224. //This part can be improved by adding the possible options of texture
  104225. }
  104226. else if (key === "map_ka" && material) {
  104227. // ambient texture map with a loaded image
  104228. //We must first get the folder of the image
  104229. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104230. }
  104231. else if (key === "map_kd" && material) {
  104232. // Diffuse texture map with a loaded image
  104233. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104234. }
  104235. else if (key === "map_ks" && material) {
  104236. // Specular texture map with a loaded image
  104237. //We must first get the folder of the image
  104238. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104239. }
  104240. else if (key === "map_ns") {
  104241. //Specular
  104242. //Specular highlight component
  104243. //We must first get the folder of the image
  104244. //
  104245. //Not supported by BABYLON
  104246. //
  104247. // continue;
  104248. }
  104249. else if (key === "map_bump" && material) {
  104250. //The bump texture
  104251. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104252. }
  104253. else if (key === "map_d" && material) {
  104254. // The dissolve of the material
  104255. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  104256. //Options for illumination
  104257. }
  104258. else if (key === "illum") {
  104259. //Illumination
  104260. if (value === "0") {
  104261. //That mean Kd == Kd
  104262. }
  104263. else if (value === "1") {
  104264. //Color on and Ambient on
  104265. }
  104266. else if (value === "2") {
  104267. //Highlight on
  104268. }
  104269. else if (value === "3") {
  104270. //Reflection on and Ray trace on
  104271. }
  104272. else if (value === "4") {
  104273. //Transparency: Glass on, Reflection: Ray trace on
  104274. }
  104275. else if (value === "5") {
  104276. //Reflection: Fresnel on and Ray trace on
  104277. }
  104278. else if (value === "6") {
  104279. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  104280. }
  104281. else if (value === "7") {
  104282. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  104283. }
  104284. else if (value === "8") {
  104285. //Reflection on and Ray trace off
  104286. }
  104287. else if (value === "9") {
  104288. //Transparency: Glass on, Reflection: Ray trace off
  104289. }
  104290. else if (value === "10") {
  104291. //Casts shadows onto invisible surfaces
  104292. }
  104293. }
  104294. else {
  104295. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  104296. }
  104297. }
  104298. //At the end of the file, add the last material
  104299. if (material) {
  104300. this.materials.push(material);
  104301. }
  104302. };
  104303. /**
  104304. * Gets the texture for the material.
  104305. *
  104306. * If the material is imported from input file,
  104307. * We sanitize the url to ensure it takes the textre from aside the material.
  104308. *
  104309. * @param rootUrl The root url to load from
  104310. * @param value The value stored in the mtl
  104311. * @return The Texture
  104312. */
  104313. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  104314. if (!value) {
  104315. return null;
  104316. }
  104317. var url = rootUrl;
  104318. // Load from input file.
  104319. if (rootUrl === "file:") {
  104320. var lastDelimiter = value.lastIndexOf("\\");
  104321. if (lastDelimiter === -1) {
  104322. lastDelimiter = value.lastIndexOf("/");
  104323. }
  104324. if (lastDelimiter > -1) {
  104325. url += value.substr(lastDelimiter + 1);
  104326. }
  104327. else {
  104328. url += value;
  104329. }
  104330. }
  104331. else {
  104332. url += value;
  104333. }
  104334. return new BABYLON.Texture(url, scene);
  104335. };
  104336. return MTLFileLoader;
  104337. }());
  104338. BABYLON.MTLFileLoader = MTLFileLoader;
  104339. var OBJFileLoader = /** @class */ (function () {
  104340. function OBJFileLoader() {
  104341. this.name = "obj";
  104342. this.extensions = ".obj";
  104343. this.obj = /^o/;
  104344. this.group = /^g/;
  104345. this.mtllib = /^mtllib /;
  104346. this.usemtl = /^usemtl /;
  104347. this.smooth = /^s /;
  104348. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  104349. // vn float float float
  104350. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  104351. // vt float float
  104352. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  104353. // f vertex vertex vertex ...
  104354. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  104355. // f vertex/uvs vertex/uvs vertex/uvs ...
  104356. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  104357. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  104358. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  104359. // f vertex//normal vertex//normal vertex//normal ...
  104360. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  104361. }
  104362. /**
  104363. * Calls synchronously the MTL file attached to this obj.
  104364. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  104365. * Without this function materials are not displayed in the first frame (but displayed after).
  104366. * In consequence it is impossible to get material information in your HTML file
  104367. *
  104368. * @param url The URL of the MTL file
  104369. * @param rootUrl
  104370. * @param onSuccess Callback function to be called when the MTL file is loaded
  104371. * @private
  104372. */
  104373. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  104374. //The complete path to the mtl file
  104375. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  104376. // Loads through the babylon tools to allow fileInput search.
  104377. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  104378. };
  104379. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  104380. //get the meshes from OBJ file
  104381. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  104382. //Push meshes from OBJ file into the variable mesh of this function
  104383. if (meshes) {
  104384. loadedMeshes.forEach(function (mesh) {
  104385. meshes.push(mesh);
  104386. });
  104387. }
  104388. return true;
  104389. };
  104390. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  104391. //Get the 3D model
  104392. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  104393. };
  104394. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  104395. var container = new BABYLON.AssetContainer(scene);
  104396. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  104397. container.removeAllFromScene();
  104398. return container;
  104399. };
  104400. /**
  104401. * Read the OBJ file and create an Array of meshes.
  104402. * Each mesh contains all information given by the OBJ and the MTL file.
  104403. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  104404. *
  104405. * @param meshesNames
  104406. * @param scene BABYLON.Scene The scene where are displayed the data
  104407. * @param data String The content of the obj file
  104408. * @param rootUrl String The path to the folder
  104409. * @returns Array<AbstractMesh>
  104410. * @private
  104411. */
  104412. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  104413. var positions = []; //values for the positions of vertices
  104414. var normals = []; //Values for the normals
  104415. var uvs = []; //Values for the textures
  104416. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  104417. var handledMesh; //The current mesh of meshes array
  104418. var indicesForBabylon = []; //The list of indices for VertexData
  104419. var wrappedPositionForBabylon = []; //The list of position in vectors
  104420. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  104421. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  104422. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  104423. var curPositionInIndices = 0;
  104424. var hasMeshes = false; //Meshes are defined in the file
  104425. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  104426. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  104427. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  104428. var triangles = []; //Indices from new triangles coming from polygons
  104429. var materialNameFromObj = ""; //The name of the current material
  104430. var fileToLoad = ""; //The name of the mtlFile to load
  104431. var materialsFromMTLFile = new MTLFileLoader();
  104432. var objMeshName = ""; //The name of the current obj mesh
  104433. var increment = 1; //Id for meshes created by the multimaterial
  104434. var isFirstMaterial = true;
  104435. /**
  104436. * Search for obj in the given array.
  104437. * This function is called to check if a couple of data already exists in an array.
  104438. *
  104439. * If found, returns the index of the founded tuple index. Returns -1 if not found
  104440. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  104441. * @param obj Array<number>
  104442. * @returns {boolean}
  104443. */
  104444. var isInArray = function (arr, obj) {
  104445. if (!arr[obj[0]])
  104446. arr[obj[0]] = { normals: [], idx: [] };
  104447. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  104448. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  104449. };
  104450. var isInArrayUV = function (arr, obj) {
  104451. if (!arr[obj[0]])
  104452. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  104453. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  104454. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  104455. return arr[obj[0]].idx[idx];
  104456. }
  104457. return -1;
  104458. };
  104459. /**
  104460. * This function set the data for each triangle.
  104461. * Data are position, normals and uvs
  104462. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  104463. * If the tuple already exist, add only their indice
  104464. *
  104465. * @param indicePositionFromObj Integer The index in positions array
  104466. * @param indiceUvsFromObj Integer The index in uvs array
  104467. * @param indiceNormalFromObj Integer The index in normals array
  104468. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  104469. * @param textureVectorFromOBJ Vector3 The value of uvs
  104470. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  104471. */
  104472. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  104473. //Check if this tuple already exists in the list of tuples
  104474. var _index;
  104475. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  104476. _index = isInArrayUV(tuplePosNorm, [
  104477. indicePositionFromObj,
  104478. indiceNormalFromObj,
  104479. indiceUvsFromObj
  104480. ]);
  104481. }
  104482. else {
  104483. _index = isInArray(tuplePosNorm, [
  104484. indicePositionFromObj,
  104485. indiceNormalFromObj
  104486. ]);
  104487. }
  104488. //If it not exists
  104489. if (_index == -1) {
  104490. //Add an new indice.
  104491. //The array of indices is only an array with his length equal to the number of triangles - 1.
  104492. //We add vertices data in this order
  104493. indicesForBabylon.push(wrappedPositionForBabylon.length);
  104494. //Push the position of vertice for Babylon
  104495. //Each element is a BABYLON.Vector3(x,y,z)
  104496. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  104497. //Push the uvs for Babylon
  104498. //Each element is a BABYLON.Vector3(u,v)
  104499. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  104500. //Push the normals for Babylon
  104501. //Each element is a BABYLON.Vector3(x,y,z)
  104502. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  104503. //Add the tuple in the comparison list
  104504. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  104505. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  104506. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  104507. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  104508. }
  104509. else {
  104510. //The tuple already exists
  104511. //Add the index of the already existing tuple
  104512. //At this index we can get the value of position, normal and uvs of vertex
  104513. indicesForBabylon.push(_index);
  104514. }
  104515. };
  104516. /**
  104517. * Transform BABYLON.Vector() object onto 3 digits in an array
  104518. */
  104519. var unwrapData = function () {
  104520. //Every array has the same length
  104521. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  104522. //Push the x, y, z values of each element in the unwrapped array
  104523. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  104524. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  104525. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  104526. }
  104527. // Reset arrays for the next new meshes
  104528. wrappedPositionForBabylon = [];
  104529. wrappedNormalsForBabylon = [];
  104530. wrappedUvsForBabylon = [];
  104531. tuplePosNorm = [];
  104532. curPositionInIndices = 0;
  104533. };
  104534. /**
  104535. * Create triangles from polygons by recursion
  104536. * The best to understand how it works is to draw it in the same time you get the recursion.
  104537. * It is important to notice that a triangle is a polygon
  104538. * We get 4 patterns of face defined in OBJ File :
  104539. * facePattern1 = ["1","2","3","4","5","6"]
  104540. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  104541. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  104542. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  104543. * Each pattern is divided by the same method
  104544. * @param face Array[String] The indices of elements
  104545. * @param v Integer The variable to increment
  104546. */
  104547. var getTriangles = function (face, v) {
  104548. //Work for each element of the array
  104549. if (v + 1 < face.length) {
  104550. //Add on the triangle variable the indexes to obtain triangles
  104551. triangles.push(face[0], face[v], face[v + 1]);
  104552. //Incrementation for recursion
  104553. v += 1;
  104554. //Recursion
  104555. getTriangles(face, v);
  104556. }
  104557. //Result obtained after 2 iterations:
  104558. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  104559. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  104560. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  104561. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  104562. };
  104563. /**
  104564. * Create triangles and push the data for each polygon for the pattern 1
  104565. * In this pattern we get vertice positions
  104566. * @param face
  104567. * @param v
  104568. */
  104569. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  104570. //Get the indices of triangles for each polygon
  104571. getTriangles(face, v);
  104572. //For each element in the triangles array.
  104573. //This var could contains 1 to an infinity of triangles
  104574. for (var k = 0; k < triangles.length; k++) {
  104575. // Set position indice
  104576. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  104577. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  104578. positions[indicePositionFromObj], //Get the vectors data
  104579. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  104580. );
  104581. }
  104582. //Reset variable for the next line
  104583. triangles = [];
  104584. };
  104585. /**
  104586. * Create triangles and push the data for each polygon for the pattern 2
  104587. * In this pattern we get vertice positions and uvsu
  104588. * @param face
  104589. * @param v
  104590. */
  104591. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  104592. //Get the indices of triangles for each polygon
  104593. getTriangles(face, v);
  104594. for (var k = 0; k < triangles.length; k++) {
  104595. //triangle[k] = "1/1"
  104596. //Split the data for getting position and uv
  104597. var point = triangles[k].split("/"); // ["1", "1"]
  104598. //Set position indice
  104599. var indicePositionFromObj = parseInt(point[0]) - 1;
  104600. //Set uv indice
  104601. var indiceUvsFromObj = parseInt(point[1]) - 1;
  104602. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  104603. positions[indicePositionFromObj], //Get the values for each element
  104604. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  104605. );
  104606. }
  104607. //Reset variable for the next line
  104608. triangles = [];
  104609. };
  104610. /**
  104611. * Create triangles and push the data for each polygon for the pattern 3
  104612. * In this pattern we get vertice positions, uvs and normals
  104613. * @param face
  104614. * @param v
  104615. */
  104616. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  104617. //Get the indices of triangles for each polygon
  104618. getTriangles(face, v);
  104619. for (var k = 0; k < triangles.length; k++) {
  104620. //triangle[k] = "1/1/1"
  104621. //Split the data for getting position, uv, and normals
  104622. var point = triangles[k].split("/"); // ["1", "1", "1"]
  104623. // Set position indice
  104624. var indicePositionFromObj = parseInt(point[0]) - 1;
  104625. // Set uv indice
  104626. var indiceUvsFromObj = parseInt(point[1]) - 1;
  104627. // Set normal indice
  104628. var indiceNormalFromObj = parseInt(point[2]) - 1;
  104629. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  104630. );
  104631. }
  104632. //Reset variable for the next line
  104633. triangles = [];
  104634. };
  104635. /**
  104636. * Create triangles and push the data for each polygon for the pattern 4
  104637. * In this pattern we get vertice positions and normals
  104638. * @param face
  104639. * @param v
  104640. */
  104641. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  104642. getTriangles(face, v);
  104643. for (var k = 0; k < triangles.length; k++) {
  104644. //triangle[k] = "1//1"
  104645. //Split the data for getting position and normals
  104646. var point = triangles[k].split("//"); // ["1", "1"]
  104647. // We check indices, and normals
  104648. var indicePositionFromObj = parseInt(point[0]) - 1;
  104649. var indiceNormalFromObj = parseInt(point[1]) - 1;
  104650. setData(indicePositionFromObj, 1, //Default value for uv
  104651. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  104652. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  104653. }
  104654. //Reset variable for the next line
  104655. triangles = [];
  104656. };
  104657. var addPreviousObjMesh = function () {
  104658. //Check if it is not the first mesh. Otherwise we don't have data.
  104659. if (meshesFromObj.length > 0) {
  104660. //Get the previous mesh for applying the data about the faces
  104661. //=> in obj file, faces definition append after the name of the mesh
  104662. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  104663. //Set the data into Array for the mesh
  104664. unwrapData();
  104665. // Reverse tab. Otherwise face are displayed in the wrong sens
  104666. indicesForBabylon.reverse();
  104667. //Set the information for the mesh
  104668. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  104669. handledMesh.indices = indicesForBabylon.slice();
  104670. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  104671. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  104672. handledMesh.uvs = unwrappedUVForBabylon.slice();
  104673. //Reset the array for the next mesh
  104674. indicesForBabylon = [];
  104675. unwrappedPositionsForBabylon = [];
  104676. unwrappedNormalsForBabylon = [];
  104677. unwrappedUVForBabylon = [];
  104678. }
  104679. };
  104680. //Main function
  104681. //Split the file into lines
  104682. var lines = data.split('\n');
  104683. //Look at each line
  104684. for (var i = 0; i < lines.length; i++) {
  104685. var line = lines[i].trim();
  104686. var result;
  104687. //Comment or newLine
  104688. if (line.length === 0 || line.charAt(0) === '#') {
  104689. continue;
  104690. //Get information about one position possible for the vertices
  104691. }
  104692. else if ((result = this.vertexPattern.exec(line)) !== null) {
  104693. //Create a Vector3 with the position x, y, z
  104694. //Value of result:
  104695. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  104696. //Add the Vector in the list of positions
  104697. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  104698. }
  104699. else if ((result = this.normalPattern.exec(line)) !== null) {
  104700. //Create a Vector3 with the normals x, y, z
  104701. //Value of result
  104702. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  104703. //Add the Vector in the list of normals
  104704. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  104705. }
  104706. else if ((result = this.uvPattern.exec(line)) !== null) {
  104707. //Create a Vector2 with the normals u, v
  104708. //Value of result
  104709. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  104710. //Add the Vector in the list of uvs
  104711. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  104712. //Identify patterns of faces
  104713. //Face could be defined in different type of pattern
  104714. }
  104715. else if ((result = this.facePattern3.exec(line)) !== null) {
  104716. //Value of result:
  104717. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  104718. //Set the data for this face
  104719. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  104720. 1);
  104721. }
  104722. else if ((result = this.facePattern4.exec(line)) !== null) {
  104723. //Value of result:
  104724. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  104725. //Set the data for this face
  104726. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  104727. 1);
  104728. }
  104729. else if ((result = this.facePattern2.exec(line)) !== null) {
  104730. //Value of result:
  104731. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  104732. //Set the data for this face
  104733. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  104734. 1);
  104735. }
  104736. else if ((result = this.facePattern1.exec(line)) !== null) {
  104737. //Value of result
  104738. //["f 1 2 3", "1 2 3"...]
  104739. //Set the data for this face
  104740. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  104741. 1);
  104742. //Define a mesh or an object
  104743. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  104744. }
  104745. else if (this.group.test(line) || this.obj.test(line)) {
  104746. //Create a new mesh corresponding to the name of the group.
  104747. //Definition of the mesh
  104748. var objMesh =
  104749. //Set the name of the current obj mesh
  104750. {
  104751. name: line.substring(2).trim(),
  104752. indices: undefined,
  104753. positions: undefined,
  104754. normals: undefined,
  104755. uvs: undefined,
  104756. materialName: ""
  104757. };
  104758. addPreviousObjMesh();
  104759. //Push the last mesh created with only the name
  104760. meshesFromObj.push(objMesh);
  104761. //Set this variable to indicate that now meshesFromObj has objects defined inside
  104762. hasMeshes = true;
  104763. isFirstMaterial = true;
  104764. increment = 1;
  104765. //Keyword for applying a material
  104766. }
  104767. else if (this.usemtl.test(line)) {
  104768. //Get the name of the material
  104769. materialNameFromObj = line.substring(7).trim();
  104770. //If this new material is in the same mesh
  104771. if (!isFirstMaterial) {
  104772. //Set the data for the previous mesh
  104773. addPreviousObjMesh();
  104774. //Create a new mesh
  104775. var objMesh =
  104776. //Set the name of the current obj mesh
  104777. {
  104778. name: objMeshName + "_mm" + increment.toString(),
  104779. indices: undefined,
  104780. positions: undefined,
  104781. normals: undefined,
  104782. uvs: undefined,
  104783. materialName: materialNameFromObj
  104784. };
  104785. increment++;
  104786. //If meshes are already defined
  104787. meshesFromObj.push(objMesh);
  104788. }
  104789. //Set the material name if the previous line define a mesh
  104790. if (hasMeshes && isFirstMaterial) {
  104791. //Set the material name to the previous mesh (1 material per mesh)
  104792. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  104793. isFirstMaterial = false;
  104794. }
  104795. //Keyword for loading the mtl file
  104796. }
  104797. else if (this.mtllib.test(line)) {
  104798. //Get the name of mtl file
  104799. fileToLoad = line.substring(7).trim();
  104800. //Apply smoothing
  104801. }
  104802. else if (this.smooth.test(line)) {
  104803. // smooth shading => apply smoothing
  104804. //Toda y I don't know it work with babylon and with obj.
  104805. //With the obj file an integer is set
  104806. }
  104807. else {
  104808. //If there is another possibility
  104809. console.log("Unhandled expression at line : " + line);
  104810. }
  104811. }
  104812. //At the end of the file, add the last mesh into the meshesFromObj array
  104813. if (hasMeshes) {
  104814. //Set the data for the last mesh
  104815. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  104816. //Reverse indices for displaying faces in the good sens
  104817. indicesForBabylon.reverse();
  104818. //Get the good array
  104819. unwrapData();
  104820. //Set array
  104821. handledMesh.indices = indicesForBabylon;
  104822. handledMesh.positions = unwrappedPositionsForBabylon;
  104823. handledMesh.normals = unwrappedNormalsForBabylon;
  104824. handledMesh.uvs = unwrappedUVForBabylon;
  104825. }
  104826. //If any o or g keyword found, create a mesj with a random id
  104827. if (!hasMeshes) {
  104828. // reverse tab of indices
  104829. indicesForBabylon.reverse();
  104830. //Get positions normals uvs
  104831. unwrapData();
  104832. //Set data for one mesh
  104833. meshesFromObj.push({
  104834. name: BABYLON.Geometry.RandomId(),
  104835. indices: indicesForBabylon,
  104836. positions: unwrappedPositionsForBabylon,
  104837. normals: unwrappedNormalsForBabylon,
  104838. uvs: unwrappedUVForBabylon,
  104839. materialName: materialNameFromObj
  104840. });
  104841. }
  104842. //Create a BABYLON.Mesh list
  104843. var babylonMeshesArray = []; //The mesh for babylon
  104844. var materialToUse = new Array();
  104845. //Set data for each mesh
  104846. for (var j = 0; j < meshesFromObj.length; j++) {
  104847. //check meshesNames (stlFileLoader)
  104848. if (meshesNames && meshesFromObj[j].name) {
  104849. if (meshesNames instanceof Array) {
  104850. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  104851. continue;
  104852. }
  104853. }
  104854. else {
  104855. if (meshesFromObj[j].name !== meshesNames) {
  104856. continue;
  104857. }
  104858. }
  104859. }
  104860. //Get the current mesh
  104861. //Set the data with VertexBuffer for each mesh
  104862. handledMesh = meshesFromObj[j];
  104863. //Create a BABYLON.Mesh with the name of the obj mesh
  104864. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  104865. //Push the name of the material to an array
  104866. //This is indispensable for the importMesh function
  104867. materialToUse.push(meshesFromObj[j].materialName);
  104868. var vertexData = new BABYLON.VertexData(); //The container for the values
  104869. //Set the data for the babylonMesh
  104870. vertexData.positions = handledMesh.positions;
  104871. vertexData.normals = handledMesh.normals;
  104872. vertexData.uvs = handledMesh.uvs;
  104873. vertexData.indices = handledMesh.indices;
  104874. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  104875. vertexData.applyToMesh(babylonMesh);
  104876. //Push the mesh into an array
  104877. babylonMeshesArray.push(babylonMesh);
  104878. }
  104879. //load the materials
  104880. //Check if we have a file to load
  104881. if (fileToLoad !== "") {
  104882. //Load the file synchronously
  104883. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  104884. //Create materials thanks MTLLoader function
  104885. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  104886. //Look at each material loaded in the mtl file
  104887. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  104888. //Three variables to get all meshes with the same material
  104889. var startIndex = 0;
  104890. var _indices = [];
  104891. var _index;
  104892. //The material from MTL file is used in the meshes loaded
  104893. //Push the indice in an array
  104894. //Check if the material is not used for another mesh
  104895. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  104896. _indices.push(_index);
  104897. startIndex = _index + 1;
  104898. }
  104899. //If the material is not used dispose it
  104900. if (_index == -1 && _indices.length == 0) {
  104901. //If the material is not needed, remove it
  104902. materialsFromMTLFile.materials[n].dispose();
  104903. }
  104904. else {
  104905. for (var o = 0; o < _indices.length; o++) {
  104906. //Apply the material to the BABYLON.Mesh for each mesh with the material
  104907. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  104908. }
  104909. }
  104910. }
  104911. });
  104912. }
  104913. //Return an array with all BABYLON.Mesh
  104914. return babylonMeshesArray;
  104915. };
  104916. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  104917. return OBJFileLoader;
  104918. }());
  104919. BABYLON.OBJFileLoader = OBJFileLoader;
  104920. if (BABYLON.SceneLoader) {
  104921. //Add this loader into the register plugin
  104922. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  104923. }
  104924. })(BABYLON || (BABYLON = {}));
  104925. //# sourceMappingURL=babylon.objFileLoader.js.map
  104926. var BABYLON;
  104927. (function (BABYLON) {
  104928. var GLTFLoaderCoordinateSystemMode;
  104929. (function (GLTFLoaderCoordinateSystemMode) {
  104930. /**
  104931. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  104932. */
  104933. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  104934. /**
  104935. * Sets the useRightHandedSystem flag on the scene.
  104936. */
  104937. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  104938. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  104939. var GLTFLoaderAnimationStartMode;
  104940. (function (GLTFLoaderAnimationStartMode) {
  104941. /**
  104942. * No animation will start.
  104943. */
  104944. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  104945. /**
  104946. * The first animation will start.
  104947. */
  104948. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  104949. /**
  104950. * All animations will start.
  104951. */
  104952. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  104953. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  104954. var GLTFLoaderState;
  104955. (function (GLTFLoaderState) {
  104956. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  104957. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  104958. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  104959. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  104960. var GLTFFileLoader = /** @class */ (function () {
  104961. function GLTFFileLoader() {
  104962. // #region Common options
  104963. /**
  104964. * Raised when the asset has been parsed.
  104965. * The data.json property stores the glTF JSON.
  104966. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  104967. */
  104968. this.onParsedObservable = new BABYLON.Observable();
  104969. // #endregion
  104970. // #region V2 options
  104971. /**
  104972. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  104973. */
  104974. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  104975. /**
  104976. * The animation start mode (NONE, FIRST, ALL).
  104977. */
  104978. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  104979. /**
  104980. * Set to true to compile materials before raising the success callback.
  104981. */
  104982. this.compileMaterials = false;
  104983. /**
  104984. * Set to true to also compile materials with clip planes.
  104985. */
  104986. this.useClipPlane = false;
  104987. /**
  104988. * Set to true to compile shadow generators before raising the success callback.
  104989. */
  104990. this.compileShadowGenerators = false;
  104991. /**
  104992. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  104993. */
  104994. this.onMeshLoadedObservable = new BABYLON.Observable();
  104995. /**
  104996. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  104997. */
  104998. this.onTextureLoadedObservable = new BABYLON.Observable();
  104999. /**
  105000. * Raised when the loader creates a material after parsing the glTF properties of the material.
  105001. */
  105002. this.onMaterialLoadedObservable = new BABYLON.Observable();
  105003. /**
  105004. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  105005. * For assets with LODs, raised when all of the LODs are complete.
  105006. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  105007. */
  105008. this.onCompleteObservable = new BABYLON.Observable();
  105009. /**
  105010. * Raised when the loader is disposed.
  105011. */
  105012. this.onDisposeObservable = new BABYLON.Observable();
  105013. /**
  105014. * Raised after a loader extension is created.
  105015. * Set additional options for a loader extension in this event.
  105016. */
  105017. this.onExtensionLoadedObservable = new BABYLON.Observable();
  105018. // #endregion
  105019. this._loader = null;
  105020. this.name = "gltf";
  105021. this.extensions = {
  105022. ".gltf": { isBinary: false },
  105023. ".glb": { isBinary: true }
  105024. };
  105025. }
  105026. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  105027. set: function (callback) {
  105028. if (this._onParsedObserver) {
  105029. this.onParsedObservable.remove(this._onParsedObserver);
  105030. }
  105031. this._onParsedObserver = this.onParsedObservable.add(callback);
  105032. },
  105033. enumerable: true,
  105034. configurable: true
  105035. });
  105036. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  105037. set: function (callback) {
  105038. if (this._onMeshLoadedObserver) {
  105039. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  105040. }
  105041. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  105042. },
  105043. enumerable: true,
  105044. configurable: true
  105045. });
  105046. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  105047. set: function (callback) {
  105048. if (this._onTextureLoadedObserver) {
  105049. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  105050. }
  105051. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  105052. },
  105053. enumerable: true,
  105054. configurable: true
  105055. });
  105056. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  105057. set: function (callback) {
  105058. if (this._onMaterialLoadedObserver) {
  105059. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  105060. }
  105061. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  105062. },
  105063. enumerable: true,
  105064. configurable: true
  105065. });
  105066. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  105067. set: function (callback) {
  105068. if (this._onCompleteObserver) {
  105069. this.onCompleteObservable.remove(this._onCompleteObserver);
  105070. }
  105071. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  105072. },
  105073. enumerable: true,
  105074. configurable: true
  105075. });
  105076. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  105077. set: function (callback) {
  105078. if (this._onDisposeObserver) {
  105079. this.onDisposeObservable.remove(this._onDisposeObserver);
  105080. }
  105081. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  105082. },
  105083. enumerable: true,
  105084. configurable: true
  105085. });
  105086. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  105087. set: function (callback) {
  105088. if (this._onExtensionLoadedObserver) {
  105089. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  105090. }
  105091. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  105092. },
  105093. enumerable: true,
  105094. configurable: true
  105095. });
  105096. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  105097. /**
  105098. * The loader state or null if not active.
  105099. */
  105100. get: function () {
  105101. return this._loader ? this._loader.state : null;
  105102. },
  105103. enumerable: true,
  105104. configurable: true
  105105. });
  105106. /**
  105107. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  105108. */
  105109. GLTFFileLoader.prototype.dispose = function () {
  105110. if (this._loader) {
  105111. this._loader.dispose();
  105112. this._loader = null;
  105113. }
  105114. this.onMeshLoadedObservable.clear();
  105115. this.onTextureLoadedObservable.clear();
  105116. this.onMaterialLoadedObservable.clear();
  105117. this.onDisposeObservable.notifyObservers(this);
  105118. this.onDisposeObservable.clear();
  105119. };
  105120. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105121. var _this = this;
  105122. return Promise.resolve().then(function () {
  105123. var loaderData = _this._parse(data);
  105124. _this._loader = _this._getLoader(loaderData);
  105125. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  105126. });
  105127. };
  105128. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105129. var _this = this;
  105130. return Promise.resolve().then(function () {
  105131. var loaderData = _this._parse(data);
  105132. _this._loader = _this._getLoader(loaderData);
  105133. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  105134. });
  105135. };
  105136. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  105137. var _this = this;
  105138. return Promise.resolve().then(function () {
  105139. var loaderData = _this._parse(data);
  105140. _this._loader = _this._getLoader(loaderData);
  105141. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  105142. var container = new BABYLON.AssetContainer(scene);
  105143. Array.prototype.push.apply(container.meshes, result.meshes);
  105144. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  105145. Array.prototype.push.apply(container.skeletons, result.skeletons);
  105146. container.removeAllFromScene();
  105147. return container;
  105148. });
  105149. });
  105150. };
  105151. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  105152. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  105153. };
  105154. GLTFFileLoader.prototype.createPlugin = function () {
  105155. return new GLTFFileLoader();
  105156. };
  105157. GLTFFileLoader.prototype._parse = function (data) {
  105158. var parsedData;
  105159. if (data instanceof ArrayBuffer) {
  105160. parsedData = GLTFFileLoader._parseBinary(data);
  105161. }
  105162. else {
  105163. parsedData = {
  105164. json: JSON.parse(data),
  105165. bin: null
  105166. };
  105167. }
  105168. this.onParsedObservable.notifyObservers(parsedData);
  105169. this.onParsedObservable.clear();
  105170. return parsedData;
  105171. };
  105172. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  105173. var _this = this;
  105174. var loaderVersion = { major: 2, minor: 0 };
  105175. var asset = loaderData.json.asset || {};
  105176. var version = GLTFFileLoader._parseVersion(asset.version);
  105177. if (!version) {
  105178. throw new Error("Invalid version: " + asset.version);
  105179. }
  105180. if (asset.minVersion !== undefined) {
  105181. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  105182. if (!minVersion) {
  105183. throw new Error("Invalid minimum version: " + asset.minVersion);
  105184. }
  105185. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  105186. throw new Error("Incompatible minimum version: " + asset.minVersion);
  105187. }
  105188. }
  105189. var createLoaders = {
  105190. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  105191. 2: GLTFFileLoader.CreateGLTFLoaderV2
  105192. };
  105193. var createLoader = createLoaders[version.major];
  105194. if (!createLoader) {
  105195. throw new Error("Unsupported version: " + asset.version);
  105196. }
  105197. var loader = createLoader();
  105198. loader.coordinateSystemMode = this.coordinateSystemMode;
  105199. loader.animationStartMode = this.animationStartMode;
  105200. loader.compileMaterials = this.compileMaterials;
  105201. loader.useClipPlane = this.useClipPlane;
  105202. loader.compileShadowGenerators = this.compileShadowGenerators;
  105203. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  105204. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  105205. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  105206. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  105207. loader.onCompleteObservable.add(function () {
  105208. _this.onMeshLoadedObservable.clear();
  105209. _this.onTextureLoadedObservable.clear();
  105210. _this.onMaterialLoadedObservable.clear();
  105211. _this.onCompleteObservable.notifyObservers(_this);
  105212. _this.onCompleteObservable.clear();
  105213. });
  105214. return loader;
  105215. };
  105216. GLTFFileLoader._parseBinary = function (data) {
  105217. var Binary = {
  105218. Magic: 0x46546C67
  105219. };
  105220. var binaryReader = new BinaryReader(data);
  105221. var magic = binaryReader.readUint32();
  105222. if (magic !== Binary.Magic) {
  105223. throw new Error("Unexpected magic: " + magic);
  105224. }
  105225. var version = binaryReader.readUint32();
  105226. switch (version) {
  105227. case 1: return GLTFFileLoader._parseV1(binaryReader);
  105228. case 2: return GLTFFileLoader._parseV2(binaryReader);
  105229. }
  105230. throw new Error("Unsupported version: " + version);
  105231. };
  105232. GLTFFileLoader._parseV1 = function (binaryReader) {
  105233. var ContentFormat = {
  105234. JSON: 0
  105235. };
  105236. var length = binaryReader.readUint32();
  105237. if (length != binaryReader.getLength()) {
  105238. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  105239. }
  105240. var contentLength = binaryReader.readUint32();
  105241. var contentFormat = binaryReader.readUint32();
  105242. var content;
  105243. switch (contentFormat) {
  105244. case ContentFormat.JSON: {
  105245. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  105246. break;
  105247. }
  105248. default: {
  105249. throw new Error("Unexpected content format: " + contentFormat);
  105250. }
  105251. }
  105252. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  105253. var body = binaryReader.readUint8Array(bytesRemaining);
  105254. return {
  105255. json: content,
  105256. bin: body
  105257. };
  105258. };
  105259. GLTFFileLoader._parseV2 = function (binaryReader) {
  105260. var ChunkFormat = {
  105261. JSON: 0x4E4F534A,
  105262. BIN: 0x004E4942
  105263. };
  105264. var length = binaryReader.readUint32();
  105265. if (length !== binaryReader.getLength()) {
  105266. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  105267. }
  105268. // JSON chunk
  105269. var chunkLength = binaryReader.readUint32();
  105270. var chunkFormat = binaryReader.readUint32();
  105271. if (chunkFormat !== ChunkFormat.JSON) {
  105272. throw new Error("First chunk format is not JSON");
  105273. }
  105274. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  105275. // Look for BIN chunk
  105276. var bin = null;
  105277. while (binaryReader.getPosition() < binaryReader.getLength()) {
  105278. var chunkLength_1 = binaryReader.readUint32();
  105279. var chunkFormat_1 = binaryReader.readUint32();
  105280. switch (chunkFormat_1) {
  105281. case ChunkFormat.JSON: {
  105282. throw new Error("Unexpected JSON chunk");
  105283. }
  105284. case ChunkFormat.BIN: {
  105285. bin = binaryReader.readUint8Array(chunkLength_1);
  105286. break;
  105287. }
  105288. default: {
  105289. // ignore unrecognized chunkFormat
  105290. binaryReader.skipBytes(chunkLength_1);
  105291. break;
  105292. }
  105293. }
  105294. }
  105295. return {
  105296. json: json,
  105297. bin: bin
  105298. };
  105299. };
  105300. GLTFFileLoader._parseVersion = function (version) {
  105301. if (version === "1.0" || version === "1.0.1") {
  105302. return {
  105303. major: 1,
  105304. minor: 0
  105305. };
  105306. }
  105307. var match = (version + "").match(/^(\d+)\.(\d+)/);
  105308. if (!match) {
  105309. return null;
  105310. }
  105311. return {
  105312. major: parseInt(match[1]),
  105313. minor: parseInt(match[2])
  105314. };
  105315. };
  105316. GLTFFileLoader._compareVersion = function (a, b) {
  105317. if (a.major > b.major)
  105318. return 1;
  105319. if (a.major < b.major)
  105320. return -1;
  105321. if (a.minor > b.minor)
  105322. return 1;
  105323. if (a.minor < b.minor)
  105324. return -1;
  105325. return 0;
  105326. };
  105327. GLTFFileLoader._decodeBufferToText = function (buffer) {
  105328. var result = "";
  105329. var length = buffer.byteLength;
  105330. for (var i = 0; i < length; i++) {
  105331. result += String.fromCharCode(buffer[i]);
  105332. }
  105333. return result;
  105334. };
  105335. // #endregion
  105336. // #region V1 options
  105337. GLTFFileLoader.IncrementalLoading = true;
  105338. GLTFFileLoader.HomogeneousCoordinates = false;
  105339. return GLTFFileLoader;
  105340. }());
  105341. BABYLON.GLTFFileLoader = GLTFFileLoader;
  105342. var BinaryReader = /** @class */ (function () {
  105343. function BinaryReader(arrayBuffer) {
  105344. this._arrayBuffer = arrayBuffer;
  105345. this._dataView = new DataView(arrayBuffer);
  105346. this._byteOffset = 0;
  105347. }
  105348. BinaryReader.prototype.getPosition = function () {
  105349. return this._byteOffset;
  105350. };
  105351. BinaryReader.prototype.getLength = function () {
  105352. return this._arrayBuffer.byteLength;
  105353. };
  105354. BinaryReader.prototype.readUint32 = function () {
  105355. var value = this._dataView.getUint32(this._byteOffset, true);
  105356. this._byteOffset += 4;
  105357. return value;
  105358. };
  105359. BinaryReader.prototype.readUint8Array = function (length) {
  105360. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  105361. this._byteOffset += length;
  105362. return value;
  105363. };
  105364. BinaryReader.prototype.skipBytes = function (length) {
  105365. this._byteOffset += length;
  105366. };
  105367. return BinaryReader;
  105368. }());
  105369. if (BABYLON.SceneLoader) {
  105370. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  105371. }
  105372. })(BABYLON || (BABYLON = {}));
  105373. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  105374. var BABYLON;
  105375. (function (BABYLON) {
  105376. var GLTF1;
  105377. (function (GLTF1) {
  105378. /**
  105379. * Enums
  105380. */
  105381. var EComponentType;
  105382. (function (EComponentType) {
  105383. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  105384. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  105385. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  105386. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  105387. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  105388. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  105389. var EShaderType;
  105390. (function (EShaderType) {
  105391. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  105392. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  105393. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  105394. var EParameterType;
  105395. (function (EParameterType) {
  105396. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  105397. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  105398. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  105399. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  105400. EParameterType[EParameterType["INT"] = 5124] = "INT";
  105401. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  105402. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  105403. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  105404. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  105405. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  105406. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  105407. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  105408. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  105409. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  105410. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  105411. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  105412. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  105413. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  105414. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  105415. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  105416. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  105417. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  105418. var ETextureWrapMode;
  105419. (function (ETextureWrapMode) {
  105420. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  105421. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  105422. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  105423. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  105424. var ETextureFilterType;
  105425. (function (ETextureFilterType) {
  105426. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  105427. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  105428. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  105429. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  105430. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  105431. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  105432. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  105433. var ETextureFormat;
  105434. (function (ETextureFormat) {
  105435. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  105436. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  105437. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  105438. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  105439. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  105440. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  105441. var ECullingType;
  105442. (function (ECullingType) {
  105443. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  105444. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  105445. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  105446. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  105447. var EBlendingFunction;
  105448. (function (EBlendingFunction) {
  105449. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  105450. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  105451. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  105452. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  105453. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  105454. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  105455. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  105456. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  105457. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  105458. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  105459. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  105460. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  105461. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  105462. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  105463. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  105464. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  105465. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105466. })(BABYLON || (BABYLON = {}));
  105467. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  105468. var BABYLON;
  105469. (function (BABYLON) {
  105470. var GLTF1;
  105471. (function (GLTF1) {
  105472. /**
  105473. * Tokenizer. Used for shaders compatibility
  105474. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  105475. */
  105476. var ETokenType;
  105477. (function (ETokenType) {
  105478. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  105479. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  105480. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  105481. })(ETokenType || (ETokenType = {}));
  105482. var Tokenizer = /** @class */ (function () {
  105483. function Tokenizer(toParse) {
  105484. this._pos = 0;
  105485. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  105486. this._toParse = toParse;
  105487. this._maxPos = toParse.length;
  105488. }
  105489. Tokenizer.prototype.getNextToken = function () {
  105490. if (this.isEnd())
  105491. return ETokenType.END_OF_INPUT;
  105492. this.currentString = this.read();
  105493. this.currentToken = ETokenType.UNKNOWN;
  105494. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  105495. this.currentToken = ETokenType.IDENTIFIER;
  105496. this.currentIdentifier = this.currentString;
  105497. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  105498. this.currentIdentifier += this.currentString;
  105499. this.forward();
  105500. }
  105501. }
  105502. return this.currentToken;
  105503. };
  105504. Tokenizer.prototype.peek = function () {
  105505. return this._toParse[this._pos];
  105506. };
  105507. Tokenizer.prototype.read = function () {
  105508. return this._toParse[this._pos++];
  105509. };
  105510. Tokenizer.prototype.forward = function () {
  105511. this._pos++;
  105512. };
  105513. Tokenizer.prototype.isEnd = function () {
  105514. return this._pos >= this._maxPos;
  105515. };
  105516. return Tokenizer;
  105517. }());
  105518. /**
  105519. * Values
  105520. */
  105521. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  105522. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  105523. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  105524. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  105525. /**
  105526. * Parse
  105527. */
  105528. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  105529. for (var buf in parsedBuffers) {
  105530. var parsedBuffer = parsedBuffers[buf];
  105531. gltfRuntime.buffers[buf] = parsedBuffer;
  105532. gltfRuntime.buffersCount++;
  105533. }
  105534. };
  105535. var parseShaders = function (parsedShaders, gltfRuntime) {
  105536. for (var sha in parsedShaders) {
  105537. var parsedShader = parsedShaders[sha];
  105538. gltfRuntime.shaders[sha] = parsedShader;
  105539. gltfRuntime.shaderscount++;
  105540. }
  105541. };
  105542. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  105543. for (var object in parsedObjects) {
  105544. var parsedObject = parsedObjects[object];
  105545. gltfRuntime[runtimeProperty][object] = parsedObject;
  105546. }
  105547. };
  105548. /**
  105549. * Utils
  105550. */
  105551. var normalizeUVs = function (buffer) {
  105552. if (!buffer) {
  105553. return;
  105554. }
  105555. for (var i = 0; i < buffer.length / 2; i++) {
  105556. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  105557. }
  105558. };
  105559. var getAttribute = function (attributeParameter) {
  105560. if (attributeParameter.semantic === "NORMAL") {
  105561. return "normal";
  105562. }
  105563. else if (attributeParameter.semantic === "POSITION") {
  105564. return "position";
  105565. }
  105566. else if (attributeParameter.semantic === "JOINT") {
  105567. return "matricesIndices";
  105568. }
  105569. else if (attributeParameter.semantic === "WEIGHT") {
  105570. return "matricesWeights";
  105571. }
  105572. else if (attributeParameter.semantic === "COLOR") {
  105573. return "color";
  105574. }
  105575. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  105576. var channel = Number(attributeParameter.semantic.split("_")[1]);
  105577. return "uv" + (channel === 0 ? "" : channel + 1);
  105578. }
  105579. return null;
  105580. };
  105581. /**
  105582. * Loads and creates animations
  105583. */
  105584. var loadAnimations = function (gltfRuntime) {
  105585. for (var anim in gltfRuntime.animations) {
  105586. var animation = gltfRuntime.animations[anim];
  105587. if (!animation.channels || !animation.samplers) {
  105588. continue;
  105589. }
  105590. var lastAnimation = null;
  105591. for (var i = 0; i < animation.channels.length; i++) {
  105592. // Get parameters and load buffers
  105593. var channel = animation.channels[i];
  105594. var sampler = animation.samplers[channel.sampler];
  105595. if (!sampler) {
  105596. continue;
  105597. }
  105598. var inputData = null;
  105599. var outputData = null;
  105600. if (animation.parameters) {
  105601. inputData = animation.parameters[sampler.input];
  105602. outputData = animation.parameters[sampler.output];
  105603. }
  105604. else {
  105605. inputData = sampler.input;
  105606. outputData = sampler.output;
  105607. }
  105608. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  105609. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  105610. var targetID = channel.target.id;
  105611. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  105612. if (targetNode === null) {
  105613. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  105614. }
  105615. if (targetNode === null) {
  105616. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  105617. continue;
  105618. }
  105619. var isBone = targetNode instanceof BABYLON.Bone;
  105620. // Get target path (position, rotation or scaling)
  105621. var targetPath = channel.target.path;
  105622. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  105623. if (targetPathIndex !== -1) {
  105624. targetPath = babylonAnimationPaths[targetPathIndex];
  105625. }
  105626. // Determine animation type
  105627. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  105628. if (!isBone) {
  105629. if (targetPath === "rotationQuaternion") {
  105630. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  105631. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  105632. }
  105633. else {
  105634. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  105635. }
  105636. }
  105637. // Create animation and key frames
  105638. var babylonAnimation = null;
  105639. var keys = [];
  105640. var arrayOffset = 0;
  105641. var modifyKey = false;
  105642. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  105643. babylonAnimation = lastAnimation;
  105644. modifyKey = true;
  105645. }
  105646. if (!modifyKey) {
  105647. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  105648. }
  105649. // For each frame
  105650. for (var j = 0; j < bufferInput.length; j++) {
  105651. var value = null;
  105652. if (targetPath === "rotationQuaternion") {
  105653. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  105654. arrayOffset += 4;
  105655. }
  105656. else {
  105657. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  105658. arrayOffset += 3;
  105659. }
  105660. if (isBone) {
  105661. var bone = targetNode;
  105662. var translation = BABYLON.Vector3.Zero();
  105663. var rotationQuaternion = new BABYLON.Quaternion();
  105664. var scaling = BABYLON.Vector3.Zero();
  105665. // Warning on decompose
  105666. var mat = bone.getBaseMatrix();
  105667. if (modifyKey && lastAnimation) {
  105668. mat = lastAnimation.getKeys()[j].value;
  105669. }
  105670. mat.decompose(scaling, rotationQuaternion, translation);
  105671. if (targetPath === "position") {
  105672. translation = value;
  105673. }
  105674. else if (targetPath === "rotationQuaternion") {
  105675. rotationQuaternion = value;
  105676. }
  105677. else {
  105678. scaling = value;
  105679. }
  105680. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  105681. }
  105682. if (!modifyKey) {
  105683. keys.push({
  105684. frame: bufferInput[j],
  105685. value: value
  105686. });
  105687. }
  105688. else if (lastAnimation) {
  105689. lastAnimation.getKeys()[j].value = value;
  105690. }
  105691. }
  105692. // Finish
  105693. if (!modifyKey && babylonAnimation) {
  105694. babylonAnimation.setKeys(keys);
  105695. targetNode.animations.push(babylonAnimation);
  105696. }
  105697. lastAnimation = babylonAnimation;
  105698. gltfRuntime.scene.stopAnimation(targetNode);
  105699. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  105700. }
  105701. }
  105702. };
  105703. /**
  105704. * Returns the bones transformation matrix
  105705. */
  105706. var configureBoneTransformation = function (node) {
  105707. var mat = null;
  105708. if (node.translation || node.rotation || node.scale) {
  105709. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  105710. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  105711. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  105712. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  105713. }
  105714. else {
  105715. mat = BABYLON.Matrix.FromArray(node.matrix);
  105716. }
  105717. return mat;
  105718. };
  105719. /**
  105720. * Returns the parent bone
  105721. */
  105722. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  105723. // Try to find
  105724. for (var i = 0; i < newSkeleton.bones.length; i++) {
  105725. if (newSkeleton.bones[i].name === jointName) {
  105726. return newSkeleton.bones[i];
  105727. }
  105728. }
  105729. // Not found, search in gltf nodes
  105730. var nodes = gltfRuntime.nodes;
  105731. for (var nde in nodes) {
  105732. var node = nodes[nde];
  105733. if (!node.jointName) {
  105734. continue;
  105735. }
  105736. var children = node.children;
  105737. for (var i = 0; i < children.length; i++) {
  105738. var child = gltfRuntime.nodes[children[i]];
  105739. if (!child.jointName) {
  105740. continue;
  105741. }
  105742. if (child.jointName === jointName) {
  105743. var mat = configureBoneTransformation(node);
  105744. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  105745. bone.id = nde;
  105746. return bone;
  105747. }
  105748. }
  105749. }
  105750. return null;
  105751. };
  105752. /**
  105753. * Returns the appropriate root node
  105754. */
  105755. var getNodeToRoot = function (nodesToRoot, id) {
  105756. for (var i = 0; i < nodesToRoot.length; i++) {
  105757. var nodeToRoot = nodesToRoot[i];
  105758. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  105759. var child = nodeToRoot.node.children[j];
  105760. if (child === id) {
  105761. return nodeToRoot.bone;
  105762. }
  105763. }
  105764. }
  105765. return null;
  105766. };
  105767. /**
  105768. * Returns the node with the joint name
  105769. */
  105770. var getJointNode = function (gltfRuntime, jointName) {
  105771. var nodes = gltfRuntime.nodes;
  105772. var node = nodes[jointName];
  105773. if (node) {
  105774. return {
  105775. node: node,
  105776. id: jointName
  105777. };
  105778. }
  105779. for (var nde in nodes) {
  105780. node = nodes[nde];
  105781. if (node.jointName === jointName) {
  105782. return {
  105783. node: node,
  105784. id: nde
  105785. };
  105786. }
  105787. }
  105788. return null;
  105789. };
  105790. /**
  105791. * Checks if a nodes is in joints
  105792. */
  105793. var nodeIsInJoints = function (skins, id) {
  105794. for (var i = 0; i < skins.jointNames.length; i++) {
  105795. if (skins.jointNames[i] === id) {
  105796. return true;
  105797. }
  105798. }
  105799. return false;
  105800. };
  105801. /**
  105802. * Fills the nodes to root for bones and builds hierarchy
  105803. */
  105804. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  105805. // Creates nodes for root
  105806. for (var nde in gltfRuntime.nodes) {
  105807. var node = gltfRuntime.nodes[nde];
  105808. var id = nde;
  105809. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  105810. continue;
  105811. }
  105812. // Create node to root bone
  105813. var mat = configureBoneTransformation(node);
  105814. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  105815. bone.id = id;
  105816. nodesToRoot.push({ bone: bone, node: node, id: id });
  105817. }
  105818. // Parenting
  105819. for (var i = 0; i < nodesToRoot.length; i++) {
  105820. var nodeToRoot = nodesToRoot[i];
  105821. var children = nodeToRoot.node.children;
  105822. for (var j = 0; j < children.length; j++) {
  105823. var child = null;
  105824. for (var k = 0; k < nodesToRoot.length; k++) {
  105825. if (nodesToRoot[k].id === children[j]) {
  105826. child = nodesToRoot[k];
  105827. break;
  105828. }
  105829. }
  105830. if (child) {
  105831. child.bone._parent = nodeToRoot.bone;
  105832. nodeToRoot.bone.children.push(child.bone);
  105833. }
  105834. }
  105835. }
  105836. };
  105837. /**
  105838. * Imports a skeleton
  105839. */
  105840. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  105841. if (!newSkeleton) {
  105842. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  105843. }
  105844. if (!skins.babylonSkeleton) {
  105845. return newSkeleton;
  105846. }
  105847. // Find the root bones
  105848. var nodesToRoot = [];
  105849. var nodesToRootToAdd = [];
  105850. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  105851. newSkeleton.bones = [];
  105852. // Joints
  105853. for (var i = 0; i < skins.jointNames.length; i++) {
  105854. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  105855. if (!jointNode) {
  105856. continue;
  105857. }
  105858. var node = jointNode.node;
  105859. if (!node) {
  105860. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  105861. continue;
  105862. }
  105863. var id = jointNode.id;
  105864. // Optimize, if the bone already exists...
  105865. var existingBone = gltfRuntime.scene.getBoneByID(id);
  105866. if (existingBone) {
  105867. newSkeleton.bones.push(existingBone);
  105868. continue;
  105869. }
  105870. // Search for parent bone
  105871. var foundBone = false;
  105872. var parentBone = null;
  105873. for (var j = 0; j < i; j++) {
  105874. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  105875. if (!jointNode_1) {
  105876. continue;
  105877. }
  105878. var joint = jointNode_1.node;
  105879. if (!joint) {
  105880. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  105881. continue;
  105882. }
  105883. var children = joint.children;
  105884. if (!children) {
  105885. continue;
  105886. }
  105887. foundBone = false;
  105888. for (var k = 0; k < children.length; k++) {
  105889. if (children[k] === id) {
  105890. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  105891. foundBone = true;
  105892. break;
  105893. }
  105894. }
  105895. if (foundBone) {
  105896. break;
  105897. }
  105898. }
  105899. // Create bone
  105900. var mat = configureBoneTransformation(node);
  105901. if (!parentBone && nodesToRoot.length > 0) {
  105902. parentBone = getNodeToRoot(nodesToRoot, id);
  105903. if (parentBone) {
  105904. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  105905. nodesToRootToAdd.push(parentBone);
  105906. }
  105907. }
  105908. }
  105909. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  105910. bone.id = id;
  105911. }
  105912. // Polish
  105913. var bones = newSkeleton.bones;
  105914. newSkeleton.bones = [];
  105915. for (var i = 0; i < skins.jointNames.length; i++) {
  105916. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  105917. if (!jointNode) {
  105918. continue;
  105919. }
  105920. for (var j = 0; j < bones.length; j++) {
  105921. if (bones[j].id === jointNode.id) {
  105922. newSkeleton.bones.push(bones[j]);
  105923. break;
  105924. }
  105925. }
  105926. }
  105927. newSkeleton.prepare();
  105928. // Finish
  105929. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  105930. newSkeleton.bones.push(nodesToRootToAdd[i]);
  105931. }
  105932. return newSkeleton;
  105933. };
  105934. /**
  105935. * Imports a mesh and its geometries
  105936. */
  105937. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  105938. if (!newMesh) {
  105939. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  105940. newMesh.id = id;
  105941. }
  105942. if (!node.babylonNode) {
  105943. return newMesh;
  105944. }
  105945. var subMaterials = [];
  105946. var vertexData = null;
  105947. var verticesStarts = new Array();
  105948. var verticesCounts = new Array();
  105949. var indexStarts = new Array();
  105950. var indexCounts = new Array();
  105951. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  105952. var meshID = meshes[meshIndex];
  105953. var mesh = gltfRuntime.meshes[meshID];
  105954. if (!mesh) {
  105955. continue;
  105956. }
  105957. // Positions, normals and UVs
  105958. for (var i = 0; i < mesh.primitives.length; i++) {
  105959. // Temporary vertex data
  105960. var tempVertexData = new BABYLON.VertexData();
  105961. var primitive = mesh.primitives[i];
  105962. if (primitive.mode !== 4) {
  105963. // continue;
  105964. }
  105965. var attributes = primitive.attributes;
  105966. var accessor = null;
  105967. var buffer = null;
  105968. // Set positions, normal and uvs
  105969. for (var semantic in attributes) {
  105970. // Link accessor and buffer view
  105971. accessor = gltfRuntime.accessors[attributes[semantic]];
  105972. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  105973. if (semantic === "NORMAL") {
  105974. tempVertexData.normals = new Float32Array(buffer.length);
  105975. tempVertexData.normals.set(buffer);
  105976. }
  105977. else if (semantic === "POSITION") {
  105978. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  105979. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  105980. for (var j = 0; j < buffer.length; j += 4) {
  105981. tempVertexData.positions[j] = buffer[j];
  105982. tempVertexData.positions[j + 1] = buffer[j + 1];
  105983. tempVertexData.positions[j + 2] = buffer[j + 2];
  105984. }
  105985. }
  105986. else {
  105987. tempVertexData.positions = new Float32Array(buffer.length);
  105988. tempVertexData.positions.set(buffer);
  105989. }
  105990. verticesCounts.push(tempVertexData.positions.length);
  105991. }
  105992. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  105993. var channel = Number(semantic.split("_")[1]);
  105994. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  105995. var uvs = new Float32Array(buffer.length);
  105996. uvs.set(buffer);
  105997. normalizeUVs(uvs);
  105998. tempVertexData.set(uvs, uvKind);
  105999. }
  106000. else if (semantic === "JOINT") {
  106001. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  106002. tempVertexData.matricesIndices.set(buffer);
  106003. }
  106004. else if (semantic === "WEIGHT") {
  106005. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  106006. tempVertexData.matricesWeights.set(buffer);
  106007. }
  106008. else if (semantic === "COLOR") {
  106009. tempVertexData.colors = new Float32Array(buffer.length);
  106010. tempVertexData.colors.set(buffer);
  106011. }
  106012. }
  106013. // Indices
  106014. accessor = gltfRuntime.accessors[primitive.indices];
  106015. if (accessor) {
  106016. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  106017. tempVertexData.indices = new Int32Array(buffer.length);
  106018. tempVertexData.indices.set(buffer);
  106019. indexCounts.push(tempVertexData.indices.length);
  106020. }
  106021. else {
  106022. // Set indices on the fly
  106023. var indices = [];
  106024. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  106025. indices.push(j);
  106026. }
  106027. tempVertexData.indices = new Int32Array(indices);
  106028. indexCounts.push(tempVertexData.indices.length);
  106029. }
  106030. if (!vertexData) {
  106031. vertexData = tempVertexData;
  106032. }
  106033. else {
  106034. vertexData.merge(tempVertexData);
  106035. }
  106036. // Sub material
  106037. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  106038. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  106039. // Update vertices start and index start
  106040. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  106041. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  106042. }
  106043. }
  106044. var material;
  106045. if (subMaterials.length > 1) {
  106046. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  106047. material.subMaterials = subMaterials;
  106048. }
  106049. else {
  106050. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  106051. }
  106052. if (subMaterials.length === 1) {
  106053. material = subMaterials[0];
  106054. }
  106055. if (!newMesh.material) {
  106056. newMesh.material = material;
  106057. }
  106058. // Apply geometry
  106059. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  106060. newMesh.computeWorldMatrix(true);
  106061. // Apply submeshes
  106062. newMesh.subMeshes = [];
  106063. var index = 0;
  106064. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106065. var meshID = meshes[meshIndex];
  106066. var mesh = gltfRuntime.meshes[meshID];
  106067. if (!mesh) {
  106068. continue;
  106069. }
  106070. for (var i = 0; i < mesh.primitives.length; i++) {
  106071. if (mesh.primitives[i].mode !== 4) {
  106072. //continue;
  106073. }
  106074. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  106075. index++;
  106076. }
  106077. }
  106078. // Finish
  106079. return newMesh;
  106080. };
  106081. /**
  106082. * Configure node transformation from position, rotation and scaling
  106083. */
  106084. var configureNode = function (newNode, position, rotation, scaling) {
  106085. if (newNode.position) {
  106086. newNode.position = position;
  106087. }
  106088. if (newNode.rotationQuaternion || newNode.rotation) {
  106089. newNode.rotationQuaternion = rotation;
  106090. }
  106091. if (newNode.scaling) {
  106092. newNode.scaling = scaling;
  106093. }
  106094. };
  106095. /**
  106096. * Configures node from transformation matrix
  106097. */
  106098. var configureNodeFromMatrix = function (newNode, node, parent) {
  106099. if (node.matrix) {
  106100. var position = new BABYLON.Vector3(0, 0, 0);
  106101. var rotation = new BABYLON.Quaternion();
  106102. var scaling = new BABYLON.Vector3(0, 0, 0);
  106103. var mat = BABYLON.Matrix.FromArray(node.matrix);
  106104. mat.decompose(scaling, rotation, position);
  106105. configureNode(newNode, position, rotation, scaling);
  106106. }
  106107. else if (node.translation && node.rotation && node.scale) {
  106108. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  106109. }
  106110. newNode.computeWorldMatrix(true);
  106111. };
  106112. /**
  106113. * Imports a node
  106114. */
  106115. var importNode = function (gltfRuntime, node, id, parent) {
  106116. var lastNode = null;
  106117. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  106118. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  106119. return null;
  106120. }
  106121. }
  106122. // Meshes
  106123. if (node.skin) {
  106124. if (node.meshes) {
  106125. var skin = gltfRuntime.skins[node.skin];
  106126. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  106127. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  106128. if (newMesh.skeleton === null) {
  106129. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  106130. if (!skin.babylonSkeleton) {
  106131. skin.babylonSkeleton = newMesh.skeleton;
  106132. }
  106133. }
  106134. lastNode = newMesh;
  106135. }
  106136. }
  106137. else if (node.meshes) {
  106138. /**
  106139. * Improve meshes property
  106140. */
  106141. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  106142. lastNode = newMesh;
  106143. }
  106144. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106145. var light = gltfRuntime.lights[node.light];
  106146. if (light) {
  106147. if (light.type === "ambient") {
  106148. var ambienLight = light[light.type];
  106149. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106150. hemiLight.name = node.name || "";
  106151. if (ambienLight.color) {
  106152. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  106153. }
  106154. lastNode = hemiLight;
  106155. }
  106156. else if (light.type === "directional") {
  106157. var directionalLight = light[light.type];
  106158. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106159. dirLight.name = node.name || "";
  106160. if (directionalLight.color) {
  106161. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  106162. }
  106163. lastNode = dirLight;
  106164. }
  106165. else if (light.type === "point") {
  106166. var pointLight = light[light.type];
  106167. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106168. ptLight.name = node.name || "";
  106169. if (pointLight.color) {
  106170. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  106171. }
  106172. lastNode = ptLight;
  106173. }
  106174. else if (light.type === "spot") {
  106175. var spotLight = light[light.type];
  106176. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  106177. spLight.name = node.name || "";
  106178. if (spotLight.color) {
  106179. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  106180. }
  106181. if (spotLight.fallOfAngle) {
  106182. spLight.angle = spotLight.fallOfAngle;
  106183. }
  106184. if (spotLight.fallOffExponent) {
  106185. spLight.exponent = spotLight.fallOffExponent;
  106186. }
  106187. lastNode = spLight;
  106188. }
  106189. }
  106190. }
  106191. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106192. var camera = gltfRuntime.cameras[node.camera];
  106193. if (camera) {
  106194. if (camera.type === "orthographic") {
  106195. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106196. orthoCamera.name = node.name || "";
  106197. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  106198. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  106199. lastNode = orthoCamera;
  106200. }
  106201. else if (camera.type === "perspective") {
  106202. var perspectiveCamera = camera[camera.type];
  106203. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106204. persCamera.name = node.name || "";
  106205. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  106206. if (!perspectiveCamera.aspectRatio) {
  106207. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  106208. }
  106209. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  106210. persCamera.maxZ = perspectiveCamera.zfar;
  106211. persCamera.minZ = perspectiveCamera.znear;
  106212. }
  106213. lastNode = persCamera;
  106214. }
  106215. }
  106216. }
  106217. // Empty node
  106218. if (!node.jointName) {
  106219. if (node.babylonNode) {
  106220. return node.babylonNode;
  106221. }
  106222. else if (lastNode === null) {
  106223. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  106224. node.babylonNode = dummy;
  106225. lastNode = dummy;
  106226. }
  106227. }
  106228. if (lastNode !== null) {
  106229. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  106230. configureNodeFromMatrix(lastNode, node, parent);
  106231. }
  106232. else {
  106233. var translation = node.translation || [0, 0, 0];
  106234. var rotation = node.rotation || [0, 0, 0, 1];
  106235. var scale = node.scale || [1, 1, 1];
  106236. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  106237. }
  106238. lastNode.updateCache(true);
  106239. node.babylonNode = lastNode;
  106240. }
  106241. return lastNode;
  106242. };
  106243. /**
  106244. * Traverses nodes and creates them
  106245. */
  106246. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  106247. if (meshIncluded === void 0) { meshIncluded = false; }
  106248. var node = gltfRuntime.nodes[id];
  106249. var newNode = null;
  106250. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  106251. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  106252. meshIncluded = true;
  106253. }
  106254. else {
  106255. meshIncluded = false;
  106256. }
  106257. }
  106258. else {
  106259. meshIncluded = true;
  106260. }
  106261. if (!node.jointName && meshIncluded) {
  106262. newNode = importNode(gltfRuntime, node, id, parent);
  106263. if (newNode !== null) {
  106264. newNode.id = id;
  106265. newNode.parent = parent;
  106266. }
  106267. }
  106268. if (node.children) {
  106269. for (var i = 0; i < node.children.length; i++) {
  106270. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  106271. }
  106272. }
  106273. };
  106274. /**
  106275. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  106276. */
  106277. var postLoad = function (gltfRuntime) {
  106278. // Nodes
  106279. var currentScene = gltfRuntime.currentScene;
  106280. if (currentScene) {
  106281. for (var i = 0; i < currentScene.nodes.length; i++) {
  106282. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106283. }
  106284. }
  106285. else {
  106286. for (var thing in gltfRuntime.scenes) {
  106287. currentScene = gltfRuntime.scenes[thing];
  106288. for (var i = 0; i < currentScene.nodes.length; i++) {
  106289. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106290. }
  106291. }
  106292. }
  106293. // Set animations
  106294. loadAnimations(gltfRuntime);
  106295. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  106296. var skeleton = gltfRuntime.scene.skeletons[i];
  106297. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  106298. }
  106299. };
  106300. /**
  106301. * onBind shaderrs callback to set uniforms and matrices
  106302. */
  106303. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  106304. var materialValues = material.values || technique.parameters;
  106305. for (var unif in unTreatedUniforms) {
  106306. var uniform = unTreatedUniforms[unif];
  106307. var type = uniform.type;
  106308. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  106309. if (uniform.semantic && !uniform.source && !uniform.node) {
  106310. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  106311. }
  106312. else if (uniform.semantic && (uniform.source || uniform.node)) {
  106313. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  106314. if (source === null) {
  106315. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  106316. }
  106317. if (source === null) {
  106318. continue;
  106319. }
  106320. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  106321. }
  106322. }
  106323. else {
  106324. var value = materialValues[technique.uniforms[unif]];
  106325. if (!value) {
  106326. continue;
  106327. }
  106328. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  106329. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  106330. if (texture === null || texture === undefined) {
  106331. continue;
  106332. }
  106333. shaderMaterial.getEffect().setTexture(unif, texture);
  106334. }
  106335. else {
  106336. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  106337. }
  106338. }
  106339. }
  106340. onSuccess(shaderMaterial);
  106341. };
  106342. /**
  106343. * Prepare uniforms to send the only one time
  106344. * Loads the appropriate textures
  106345. */
  106346. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  106347. var materialValues = material.values || technique.parameters;
  106348. var techniqueUniforms = technique.uniforms;
  106349. /**
  106350. * Prepare values here (not matrices)
  106351. */
  106352. for (var unif in unTreatedUniforms) {
  106353. var uniform = unTreatedUniforms[unif];
  106354. var type = uniform.type;
  106355. var value = materialValues[techniqueUniforms[unif]];
  106356. if (value === undefined) {
  106357. // In case the value is the same for all materials
  106358. value = uniform.value;
  106359. }
  106360. if (!value) {
  106361. continue;
  106362. }
  106363. var onLoadTexture = function (uniformName) {
  106364. return function (texture) {
  106365. if (uniform.value && uniformName) {
  106366. // Static uniform
  106367. shaderMaterial.setTexture(uniformName, texture);
  106368. delete unTreatedUniforms[uniformName];
  106369. }
  106370. };
  106371. };
  106372. // Texture (sampler2D)
  106373. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  106374. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  106375. }
  106376. else {
  106377. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  106378. // Static uniform
  106379. delete unTreatedUniforms[unif];
  106380. }
  106381. }
  106382. }
  106383. };
  106384. /**
  106385. * Shader compilation failed
  106386. */
  106387. var onShaderCompileError = function (program, shaderMaterial, onError) {
  106388. return function (effect, error) {
  106389. shaderMaterial.dispose(true);
  106390. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  106391. };
  106392. };
  106393. /**
  106394. * Shader compilation success
  106395. */
  106396. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  106397. return function (_) {
  106398. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  106399. shaderMaterial.onBind = function (mesh) {
  106400. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  106401. };
  106402. };
  106403. };
  106404. /**
  106405. * Returns the appropriate uniform if already handled by babylon
  106406. */
  106407. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  106408. for (var unif in technique.uniforms) {
  106409. var uniform = technique.uniforms[unif];
  106410. var uniformParameter = technique.parameters[uniform];
  106411. if (tokenizer.currentIdentifier === unif) {
  106412. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  106413. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  106414. if (transformIndex !== -1) {
  106415. delete unTreatedUniforms[unif];
  106416. return babylonTransforms[transformIndex];
  106417. }
  106418. }
  106419. }
  106420. }
  106421. return tokenizer.currentIdentifier;
  106422. };
  106423. /**
  106424. * All shaders loaded. Create materials one by one
  106425. */
  106426. var importMaterials = function (gltfRuntime) {
  106427. // Create materials
  106428. for (var mat in gltfRuntime.materials) {
  106429. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  106430. }
  106431. };
  106432. /**
  106433. * Implementation of the base glTF spec
  106434. */
  106435. var GLTFLoaderBase = /** @class */ (function () {
  106436. function GLTFLoaderBase() {
  106437. }
  106438. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  106439. var gltfRuntime = {
  106440. extensions: {},
  106441. accessors: {},
  106442. buffers: {},
  106443. bufferViews: {},
  106444. meshes: {},
  106445. lights: {},
  106446. cameras: {},
  106447. nodes: {},
  106448. images: {},
  106449. textures: {},
  106450. shaders: {},
  106451. programs: {},
  106452. samplers: {},
  106453. techniques: {},
  106454. materials: {},
  106455. animations: {},
  106456. skins: {},
  106457. extensionsUsed: [],
  106458. scenes: {},
  106459. buffersCount: 0,
  106460. shaderscount: 0,
  106461. scene: scene,
  106462. rootUrl: rootUrl,
  106463. loadedBufferCount: 0,
  106464. loadedBufferViews: {},
  106465. loadedShaderCount: 0,
  106466. importOnlyMeshes: false,
  106467. dummyNodes: []
  106468. };
  106469. // Parse
  106470. if (parsedData.extensions) {
  106471. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  106472. }
  106473. if (parsedData.extensionsUsed) {
  106474. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  106475. }
  106476. if (parsedData.buffers) {
  106477. parseBuffers(parsedData.buffers, gltfRuntime);
  106478. }
  106479. if (parsedData.bufferViews) {
  106480. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  106481. }
  106482. if (parsedData.accessors) {
  106483. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  106484. }
  106485. if (parsedData.meshes) {
  106486. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  106487. }
  106488. if (parsedData.lights) {
  106489. parseObject(parsedData.lights, "lights", gltfRuntime);
  106490. }
  106491. if (parsedData.cameras) {
  106492. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  106493. }
  106494. if (parsedData.nodes) {
  106495. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  106496. }
  106497. if (parsedData.images) {
  106498. parseObject(parsedData.images, "images", gltfRuntime);
  106499. }
  106500. if (parsedData.textures) {
  106501. parseObject(parsedData.textures, "textures", gltfRuntime);
  106502. }
  106503. if (parsedData.shaders) {
  106504. parseShaders(parsedData.shaders, gltfRuntime);
  106505. }
  106506. if (parsedData.programs) {
  106507. parseObject(parsedData.programs, "programs", gltfRuntime);
  106508. }
  106509. if (parsedData.samplers) {
  106510. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  106511. }
  106512. if (parsedData.techniques) {
  106513. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  106514. }
  106515. if (parsedData.materials) {
  106516. parseObject(parsedData.materials, "materials", gltfRuntime);
  106517. }
  106518. if (parsedData.animations) {
  106519. parseObject(parsedData.animations, "animations", gltfRuntime);
  106520. }
  106521. if (parsedData.skins) {
  106522. parseObject(parsedData.skins, "skins", gltfRuntime);
  106523. }
  106524. if (parsedData.scenes) {
  106525. gltfRuntime.scenes = parsedData.scenes;
  106526. }
  106527. if (parsedData.scene && parsedData.scenes) {
  106528. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  106529. }
  106530. return gltfRuntime;
  106531. };
  106532. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  106533. var buffer = gltfRuntime.buffers[id];
  106534. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  106535. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  106536. }
  106537. else {
  106538. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  106539. if (request) {
  106540. onError(request.status + " " + request.statusText);
  106541. }
  106542. });
  106543. }
  106544. };
  106545. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  106546. var texture = gltfRuntime.textures[id];
  106547. if (!texture || !texture.source) {
  106548. onError("");
  106549. return;
  106550. }
  106551. if (texture.babylonTexture) {
  106552. onSuccess(null);
  106553. return;
  106554. }
  106555. var source = gltfRuntime.images[texture.source];
  106556. if (BABYLON.Tools.IsBase64(source.uri)) {
  106557. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  106558. }
  106559. else {
  106560. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  106561. if (request) {
  106562. onError(request.status + " " + request.statusText);
  106563. }
  106564. });
  106565. }
  106566. };
  106567. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  106568. var texture = gltfRuntime.textures[id];
  106569. if (texture.babylonTexture) {
  106570. onSuccess(texture.babylonTexture);
  106571. return;
  106572. }
  106573. var sampler = gltfRuntime.samplers[texture.sampler];
  106574. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  106575. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  106576. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  106577. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  106578. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  106579. var blob = new Blob([buffer]);
  106580. var blobURL = URL.createObjectURL(blob);
  106581. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  106582. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  106583. if (sampler.wrapS !== undefined) {
  106584. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  106585. }
  106586. if (sampler.wrapT !== undefined) {
  106587. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  106588. }
  106589. newTexture.name = id;
  106590. texture.babylonTexture = newTexture;
  106591. onSuccess(newTexture);
  106592. };
  106593. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  106594. var shader = gltfRuntime.shaders[id];
  106595. if (BABYLON.Tools.IsBase64(shader.uri)) {
  106596. var shaderString = atob(shader.uri.split(",")[1]);
  106597. onSuccess(shaderString);
  106598. }
  106599. else {
  106600. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  106601. if (request) {
  106602. onError(request.status + " " + request.statusText);
  106603. }
  106604. });
  106605. }
  106606. };
  106607. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  106608. var material = gltfRuntime.materials[id];
  106609. if (!material.technique) {
  106610. if (onError) {
  106611. onError("No technique found.");
  106612. }
  106613. return;
  106614. }
  106615. var technique = gltfRuntime.techniques[material.technique];
  106616. if (!technique) {
  106617. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  106618. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  106619. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106620. onSuccess(defaultMaterial);
  106621. return;
  106622. }
  106623. var program = gltfRuntime.programs[technique.program];
  106624. var states = technique.states;
  106625. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  106626. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  106627. var newVertexShader = "";
  106628. var newPixelShader = "";
  106629. var vertexTokenizer = new Tokenizer(vertexShader);
  106630. var pixelTokenizer = new Tokenizer(pixelShader);
  106631. var unTreatedUniforms = {};
  106632. var uniforms = [];
  106633. var attributes = [];
  106634. var samplers = [];
  106635. // Fill uniform, sampler2D and attributes
  106636. for (var unif in technique.uniforms) {
  106637. var uniform = technique.uniforms[unif];
  106638. var uniformParameter = technique.parameters[uniform];
  106639. unTreatedUniforms[unif] = uniformParameter;
  106640. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  106641. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  106642. if (transformIndex !== -1) {
  106643. uniforms.push(babylonTransforms[transformIndex]);
  106644. delete unTreatedUniforms[unif];
  106645. }
  106646. else {
  106647. uniforms.push(unif);
  106648. }
  106649. }
  106650. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  106651. samplers.push(unif);
  106652. }
  106653. else {
  106654. uniforms.push(unif);
  106655. }
  106656. }
  106657. for (var attr in technique.attributes) {
  106658. var attribute = technique.attributes[attr];
  106659. var attributeParameter = technique.parameters[attribute];
  106660. if (attributeParameter.semantic) {
  106661. attributes.push(getAttribute(attributeParameter));
  106662. }
  106663. }
  106664. // Configure vertex shader
  106665. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  106666. var tokenType = vertexTokenizer.currentToken;
  106667. if (tokenType !== ETokenType.IDENTIFIER) {
  106668. newVertexShader += vertexTokenizer.currentString;
  106669. continue;
  106670. }
  106671. var foundAttribute = false;
  106672. for (var attr in technique.attributes) {
  106673. var attribute = technique.attributes[attr];
  106674. var attributeParameter = technique.parameters[attribute];
  106675. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  106676. newVertexShader += getAttribute(attributeParameter);
  106677. foundAttribute = true;
  106678. break;
  106679. }
  106680. }
  106681. if (foundAttribute) {
  106682. continue;
  106683. }
  106684. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  106685. }
  106686. // Configure pixel shader
  106687. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  106688. var tokenType = pixelTokenizer.currentToken;
  106689. if (tokenType !== ETokenType.IDENTIFIER) {
  106690. newPixelShader += pixelTokenizer.currentString;
  106691. continue;
  106692. }
  106693. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  106694. }
  106695. // Create shader material
  106696. var shaderPath = {
  106697. vertex: program.vertexShader + id,
  106698. fragment: program.fragmentShader + id
  106699. };
  106700. var options = {
  106701. attributes: attributes,
  106702. uniforms: uniforms,
  106703. samplers: samplers,
  106704. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  106705. };
  106706. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  106707. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  106708. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  106709. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  106710. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  106711. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  106712. if (states && states.functions) {
  106713. var functions = states.functions;
  106714. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  106715. shaderMaterial.backFaceCulling = false;
  106716. }
  106717. var blendFunc = functions.blendFuncSeparate;
  106718. if (blendFunc) {
  106719. 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) {
  106720. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  106721. }
  106722. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106723. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  106724. }
  106725. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106726. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  106727. }
  106728. 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) {
  106729. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  106730. }
  106731. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  106732. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  106733. }
  106734. 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) {
  106735. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  106736. }
  106737. }
  106738. }
  106739. };
  106740. return GLTFLoaderBase;
  106741. }());
  106742. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  106743. /**
  106744. * glTF V1 Loader
  106745. */
  106746. var GLTFLoader = /** @class */ (function () {
  106747. function GLTFLoader() {
  106748. // #region Stubs for IGLTFLoader interface
  106749. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  106750. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  106751. this.compileMaterials = false;
  106752. this.useClipPlane = false;
  106753. this.compileShadowGenerators = false;
  106754. this.onDisposeObservable = new BABYLON.Observable();
  106755. this.onMeshLoadedObservable = new BABYLON.Observable();
  106756. this.onTextureLoadedObservable = new BABYLON.Observable();
  106757. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106758. this.onCompleteObservable = new BABYLON.Observable();
  106759. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106760. this.state = null;
  106761. }
  106762. GLTFLoader.RegisterExtension = function (extension) {
  106763. if (GLTFLoader.Extensions[extension.name]) {
  106764. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  106765. return;
  106766. }
  106767. GLTFLoader.Extensions[extension.name] = extension;
  106768. };
  106769. GLTFLoader.prototype.dispose = function () { };
  106770. // #endregion
  106771. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  106772. var _this = this;
  106773. scene.useRightHandedSystem = true;
  106774. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  106775. gltfRuntime.importOnlyMeshes = true;
  106776. if (meshesNames === "") {
  106777. gltfRuntime.importMeshesNames = [];
  106778. }
  106779. else if (typeof meshesNames === "string") {
  106780. gltfRuntime.importMeshesNames = [meshesNames];
  106781. }
  106782. else if (meshesNames && !(meshesNames instanceof Array)) {
  106783. gltfRuntime.importMeshesNames = [meshesNames];
  106784. }
  106785. else {
  106786. gltfRuntime.importMeshesNames = [];
  106787. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  106788. }
  106789. // Create nodes
  106790. _this._createNodes(gltfRuntime);
  106791. var meshes = new Array();
  106792. var skeletons = new Array();
  106793. // Fill arrays of meshes and skeletons
  106794. for (var nde in gltfRuntime.nodes) {
  106795. var node = gltfRuntime.nodes[nde];
  106796. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  106797. meshes.push(node.babylonNode);
  106798. }
  106799. }
  106800. for (var skl in gltfRuntime.skins) {
  106801. var skin = gltfRuntime.skins[skl];
  106802. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  106803. skeletons.push(skin.babylonSkeleton);
  106804. }
  106805. }
  106806. // Load buffers, shaders, materials, etc.
  106807. _this._loadBuffersAsync(gltfRuntime, function () {
  106808. _this._loadShadersAsync(gltfRuntime, function () {
  106809. importMaterials(gltfRuntime);
  106810. postLoad(gltfRuntime);
  106811. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  106812. onSuccess(meshes, [], skeletons);
  106813. }
  106814. });
  106815. }, onProgress);
  106816. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  106817. onSuccess(meshes, [], skeletons);
  106818. }
  106819. }, onError);
  106820. return true;
  106821. };
  106822. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106823. var _this = this;
  106824. return new Promise(function (resolve, reject) {
  106825. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  106826. resolve({
  106827. meshes: meshes,
  106828. particleSystems: particleSystems,
  106829. skeletons: skeletons
  106830. });
  106831. }, onProgress, function (message) {
  106832. reject(new Error(message));
  106833. });
  106834. });
  106835. };
  106836. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  106837. var _this = this;
  106838. scene.useRightHandedSystem = true;
  106839. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  106840. // Load runtime extensios
  106841. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  106842. // Create nodes
  106843. _this._createNodes(gltfRuntime);
  106844. // Load buffers, shaders, materials, etc.
  106845. _this._loadBuffersAsync(gltfRuntime, function () {
  106846. _this._loadShadersAsync(gltfRuntime, function () {
  106847. importMaterials(gltfRuntime);
  106848. postLoad(gltfRuntime);
  106849. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  106850. onSuccess();
  106851. }
  106852. });
  106853. });
  106854. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  106855. onSuccess();
  106856. }
  106857. }, onError);
  106858. }, onError);
  106859. };
  106860. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106861. var _this = this;
  106862. return new Promise(function (resolve, reject) {
  106863. _this._loadAsync(scene, data, rootUrl, function () {
  106864. resolve();
  106865. }, onProgress, function (message) {
  106866. reject(new Error(message));
  106867. });
  106868. });
  106869. };
  106870. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  106871. var hasShaders = false;
  106872. var processShader = function (sha, shader) {
  106873. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  106874. gltfRuntime.loadedShaderCount++;
  106875. if (shaderString) {
  106876. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  106877. }
  106878. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  106879. onload();
  106880. }
  106881. }, function () {
  106882. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  106883. });
  106884. };
  106885. for (var sha in gltfRuntime.shaders) {
  106886. hasShaders = true;
  106887. var shader = gltfRuntime.shaders[sha];
  106888. if (shader) {
  106889. processShader.bind(this, sha, shader)();
  106890. }
  106891. else {
  106892. BABYLON.Tools.Error("No shader named: " + sha);
  106893. }
  106894. }
  106895. if (!hasShaders) {
  106896. onload();
  106897. }
  106898. };
  106899. ;
  106900. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  106901. var hasBuffers = false;
  106902. var processBuffer = function (buf, buffer) {
  106903. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  106904. gltfRuntime.loadedBufferCount++;
  106905. if (bufferView) {
  106906. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  106907. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  106908. }
  106909. gltfRuntime.loadedBufferViews[buf] = bufferView;
  106910. }
  106911. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  106912. onLoad();
  106913. }
  106914. }, function () {
  106915. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  106916. });
  106917. };
  106918. for (var buf in gltfRuntime.buffers) {
  106919. hasBuffers = true;
  106920. var buffer = gltfRuntime.buffers[buf];
  106921. if (buffer) {
  106922. processBuffer.bind(this, buf, buffer)();
  106923. }
  106924. else {
  106925. BABYLON.Tools.Error("No buffer named: " + buf);
  106926. }
  106927. }
  106928. if (!hasBuffers) {
  106929. onLoad();
  106930. }
  106931. };
  106932. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  106933. var currentScene = gltfRuntime.currentScene;
  106934. if (currentScene) {
  106935. // Only one scene even if multiple scenes are defined
  106936. for (var i = 0; i < currentScene.nodes.length; i++) {
  106937. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106938. }
  106939. }
  106940. else {
  106941. // Load all scenes
  106942. for (var thing in gltfRuntime.scenes) {
  106943. currentScene = gltfRuntime.scenes[thing];
  106944. for (var i = 0; i < currentScene.nodes.length; i++) {
  106945. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  106946. }
  106947. }
  106948. }
  106949. };
  106950. GLTFLoader.Extensions = {};
  106951. return GLTFLoader;
  106952. }());
  106953. GLTF1.GLTFLoader = GLTFLoader;
  106954. ;
  106955. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  106956. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106957. })(BABYLON || (BABYLON = {}));
  106958. //# sourceMappingURL=babylon.glTFLoader.js.map
  106959. var BABYLON;
  106960. (function (BABYLON) {
  106961. var GLTF1;
  106962. (function (GLTF1) {
  106963. /**
  106964. * Utils functions for GLTF
  106965. */
  106966. var GLTFUtils = /** @class */ (function () {
  106967. function GLTFUtils() {
  106968. }
  106969. /**
  106970. * Sets the given "parameter" matrix
  106971. * @param scene: the {BABYLON.Scene} object
  106972. * @param source: the source node where to pick the matrix
  106973. * @param parameter: the GLTF technique parameter
  106974. * @param uniformName: the name of the shader's uniform
  106975. * @param shaderMaterial: the shader material
  106976. */
  106977. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  106978. var mat = null;
  106979. if (parameter.semantic === "MODEL") {
  106980. mat = source.getWorldMatrix();
  106981. }
  106982. else if (parameter.semantic === "PROJECTION") {
  106983. mat = scene.getProjectionMatrix();
  106984. }
  106985. else if (parameter.semantic === "VIEW") {
  106986. mat = scene.getViewMatrix();
  106987. }
  106988. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  106989. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  106990. }
  106991. else if (parameter.semantic === "MODELVIEW") {
  106992. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  106993. }
  106994. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  106995. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  106996. }
  106997. else if (parameter.semantic === "MODELINVERSE") {
  106998. mat = source.getWorldMatrix().invert();
  106999. }
  107000. else if (parameter.semantic === "VIEWINVERSE") {
  107001. mat = scene.getViewMatrix().invert();
  107002. }
  107003. else if (parameter.semantic === "PROJECTIONINVERSE") {
  107004. mat = scene.getProjectionMatrix().invert();
  107005. }
  107006. else if (parameter.semantic === "MODELVIEWINVERSE") {
  107007. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  107008. }
  107009. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  107010. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  107011. }
  107012. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  107013. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  107014. }
  107015. else {
  107016. debugger;
  107017. }
  107018. if (mat) {
  107019. switch (parameter.type) {
  107020. case GLTF1.EParameterType.FLOAT_MAT2:
  107021. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  107022. break;
  107023. case GLTF1.EParameterType.FLOAT_MAT3:
  107024. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  107025. break;
  107026. case GLTF1.EParameterType.FLOAT_MAT4:
  107027. shaderMaterial.setMatrix(uniformName, mat);
  107028. break;
  107029. default: break;
  107030. }
  107031. }
  107032. };
  107033. /**
  107034. * Sets the given "parameter" matrix
  107035. * @param shaderMaterial: the shader material
  107036. * @param uniform: the name of the shader's uniform
  107037. * @param value: the value of the uniform
  107038. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  107039. */
  107040. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  107041. switch (type) {
  107042. case GLTF1.EParameterType.FLOAT:
  107043. shaderMaterial.setFloat(uniform, value);
  107044. return true;
  107045. case GLTF1.EParameterType.FLOAT_VEC2:
  107046. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  107047. return true;
  107048. case GLTF1.EParameterType.FLOAT_VEC3:
  107049. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  107050. return true;
  107051. case GLTF1.EParameterType.FLOAT_VEC4:
  107052. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  107053. return true;
  107054. default: return false;
  107055. }
  107056. };
  107057. /**
  107058. * Returns the wrap mode of the texture
  107059. * @param mode: the mode value
  107060. */
  107061. GLTFUtils.GetWrapMode = function (mode) {
  107062. switch (mode) {
  107063. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  107064. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  107065. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107066. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107067. }
  107068. };
  107069. /**
  107070. * Returns the byte stride giving an accessor
  107071. * @param accessor: the GLTF accessor objet
  107072. */
  107073. GLTFUtils.GetByteStrideFromType = function (accessor) {
  107074. // Needs this function since "byteStride" isn't requiered in glTF format
  107075. var type = accessor.type;
  107076. switch (type) {
  107077. case "VEC2": return 2;
  107078. case "VEC3": return 3;
  107079. case "VEC4": return 4;
  107080. case "MAT2": return 4;
  107081. case "MAT3": return 9;
  107082. case "MAT4": return 16;
  107083. default: return 1;
  107084. }
  107085. };
  107086. /**
  107087. * Returns the texture filter mode giving a mode value
  107088. * @param mode: the filter mode value
  107089. */
  107090. GLTFUtils.GetTextureFilterMode = function (mode) {
  107091. switch (mode) {
  107092. case GLTF1.ETextureFilterType.LINEAR:
  107093. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  107094. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  107095. case GLTF1.ETextureFilterType.NEAREST:
  107096. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  107097. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107098. }
  107099. };
  107100. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  107101. var byteOffset = bufferView.byteOffset + byteOffset;
  107102. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  107103. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  107104. throw new Error("Buffer access is out of range");
  107105. }
  107106. var buffer = loadedBufferView.buffer;
  107107. byteOffset += loadedBufferView.byteOffset;
  107108. switch (componentType) {
  107109. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  107110. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  107111. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  107112. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  107113. default: return new Float32Array(buffer, byteOffset, byteLength);
  107114. }
  107115. };
  107116. /**
  107117. * Returns a buffer from its accessor
  107118. * @param gltfRuntime: the GLTF runtime
  107119. * @param accessor: the GLTF accessor
  107120. */
  107121. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  107122. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  107123. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  107124. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  107125. };
  107126. /**
  107127. * Decodes a buffer view into a string
  107128. * @param view: the buffer view
  107129. */
  107130. GLTFUtils.DecodeBufferToText = function (view) {
  107131. var result = "";
  107132. var length = view.byteLength;
  107133. for (var i = 0; i < length; ++i) {
  107134. result += String.fromCharCode(view[i]);
  107135. }
  107136. return result;
  107137. };
  107138. /**
  107139. * Returns the default material of gltf. Related to
  107140. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  107141. * @param scene: the Babylon.js scene
  107142. */
  107143. GLTFUtils.GetDefaultMaterial = function (scene) {
  107144. if (!GLTFUtils._DefaultMaterial) {
  107145. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  107146. "precision highp float;",
  107147. "",
  107148. "uniform mat4 worldView;",
  107149. "uniform mat4 projection;",
  107150. "",
  107151. "attribute vec3 position;",
  107152. "",
  107153. "void main(void)",
  107154. "{",
  107155. " gl_Position = projection * worldView * vec4(position, 1.0);",
  107156. "}"
  107157. ].join("\n");
  107158. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  107159. "precision highp float;",
  107160. "",
  107161. "uniform vec4 u_emission;",
  107162. "",
  107163. "void main(void)",
  107164. "{",
  107165. " gl_FragColor = u_emission;",
  107166. "}"
  107167. ].join("\n");
  107168. var shaderPath = {
  107169. vertex: "GLTFDefaultMaterial",
  107170. fragment: "GLTFDefaultMaterial"
  107171. };
  107172. var options = {
  107173. attributes: ["position"],
  107174. uniforms: ["worldView", "projection", "u_emission"],
  107175. samplers: new Array(),
  107176. needAlphaBlending: false
  107177. };
  107178. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  107179. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  107180. }
  107181. return GLTFUtils._DefaultMaterial;
  107182. };
  107183. // The GLTF default material
  107184. GLTFUtils._DefaultMaterial = null;
  107185. return GLTFUtils;
  107186. }());
  107187. GLTF1.GLTFUtils = GLTFUtils;
  107188. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107189. })(BABYLON || (BABYLON = {}));
  107190. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  107191. var BABYLON;
  107192. (function (BABYLON) {
  107193. var GLTF1;
  107194. (function (GLTF1) {
  107195. var GLTFLoaderExtension = /** @class */ (function () {
  107196. function GLTFLoaderExtension(name) {
  107197. this._name = name;
  107198. }
  107199. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  107200. get: function () {
  107201. return this._name;
  107202. },
  107203. enumerable: true,
  107204. configurable: true
  107205. });
  107206. /**
  107207. * Defines an override for loading the runtime
  107208. * Return true to stop further extensions from loading the runtime
  107209. */
  107210. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107211. return false;
  107212. };
  107213. /**
  107214. * Defines an onverride for creating gltf runtime
  107215. * Return true to stop further extensions from creating the runtime
  107216. */
  107217. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107218. return false;
  107219. };
  107220. /**
  107221. * Defines an override for loading buffers
  107222. * Return true to stop further extensions from loading this buffer
  107223. */
  107224. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107225. return false;
  107226. };
  107227. /**
  107228. * Defines an override for loading texture buffers
  107229. * Return true to stop further extensions from loading this texture data
  107230. */
  107231. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107232. return false;
  107233. };
  107234. /**
  107235. * Defines an override for creating textures
  107236. * Return true to stop further extensions from loading this texture
  107237. */
  107238. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107239. return false;
  107240. };
  107241. /**
  107242. * Defines an override for loading shader strings
  107243. * Return true to stop further extensions from loading this shader data
  107244. */
  107245. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107246. return false;
  107247. };
  107248. /**
  107249. * Defines an override for loading materials
  107250. * Return true to stop further extensions from loading this material
  107251. */
  107252. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107253. return false;
  107254. };
  107255. // ---------
  107256. // Utilities
  107257. // ---------
  107258. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107259. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107260. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  107261. }, function () {
  107262. setTimeout(function () {
  107263. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  107264. });
  107265. });
  107266. };
  107267. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107268. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107269. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  107270. }, function () {
  107271. setTimeout(function () {
  107272. onSuccess();
  107273. });
  107274. });
  107275. };
  107276. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107277. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107278. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  107279. }, function () {
  107280. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  107281. });
  107282. };
  107283. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  107284. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  107285. };
  107286. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107287. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107288. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  107289. }, function () {
  107290. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  107291. });
  107292. };
  107293. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107294. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107295. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  107296. }, function () {
  107297. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  107298. });
  107299. };
  107300. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107301. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107302. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  107303. }, function () {
  107304. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  107305. });
  107306. };
  107307. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107308. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  107309. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  107310. }, function () {
  107311. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  107312. });
  107313. };
  107314. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  107315. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  107316. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  107317. if (func(loaderExtension)) {
  107318. return;
  107319. }
  107320. }
  107321. defaultFunc();
  107322. };
  107323. return GLTFLoaderExtension;
  107324. }());
  107325. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  107326. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107327. })(BABYLON || (BABYLON = {}));
  107328. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  107329. var BABYLON;
  107330. (function (BABYLON) {
  107331. var GLTF1;
  107332. (function (GLTF1) {
  107333. var BinaryExtensionBufferName = "binary_glTF";
  107334. ;
  107335. ;
  107336. var GLTFBinaryExtension = /** @class */ (function (_super) {
  107337. __extends(GLTFBinaryExtension, _super);
  107338. function GLTFBinaryExtension() {
  107339. return _super.call(this, "KHR_binary_glTF") || this;
  107340. }
  107341. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  107342. var extensionsUsed = data.json.extensionsUsed;
  107343. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  107344. return false;
  107345. }
  107346. this._bin = data.bin;
  107347. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  107348. return true;
  107349. };
  107350. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107351. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  107352. return false;
  107353. }
  107354. if (id !== BinaryExtensionBufferName) {
  107355. return false;
  107356. }
  107357. onSuccess(this._bin);
  107358. return true;
  107359. };
  107360. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107361. var texture = gltfRuntime.textures[id];
  107362. var source = gltfRuntime.images[texture.source];
  107363. if (!source.extensions || !(this.name in source.extensions)) {
  107364. return false;
  107365. }
  107366. var sourceExt = source.extensions[this.name];
  107367. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  107368. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  107369. onSuccess(buffer);
  107370. return true;
  107371. };
  107372. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107373. var shader = gltfRuntime.shaders[id];
  107374. if (!shader.extensions || !(this.name in shader.extensions)) {
  107375. return false;
  107376. }
  107377. var binaryExtensionShader = shader.extensions[this.name];
  107378. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  107379. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  107380. setTimeout(function () {
  107381. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  107382. onSuccess(shaderString);
  107383. });
  107384. return true;
  107385. };
  107386. return GLTFBinaryExtension;
  107387. }(GLTF1.GLTFLoaderExtension));
  107388. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  107389. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  107390. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107391. })(BABYLON || (BABYLON = {}));
  107392. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  107393. var BABYLON;
  107394. (function (BABYLON) {
  107395. var GLTF1;
  107396. (function (GLTF1) {
  107397. ;
  107398. ;
  107399. ;
  107400. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  107401. __extends(GLTFMaterialsCommonExtension, _super);
  107402. function GLTFMaterialsCommonExtension() {
  107403. return _super.call(this, "KHR_materials_common") || this;
  107404. }
  107405. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  107406. if (!gltfRuntime.extensions)
  107407. return false;
  107408. var extension = gltfRuntime.extensions[this.name];
  107409. if (!extension)
  107410. return false;
  107411. // Create lights
  107412. var lights = extension.lights;
  107413. if (lights) {
  107414. for (var thing in lights) {
  107415. var light = lights[thing];
  107416. switch (light.type) {
  107417. case "ambient":
  107418. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  107419. var ambient = light.ambient;
  107420. if (ambient) {
  107421. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  107422. }
  107423. break;
  107424. case "point":
  107425. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  107426. var point = light.point;
  107427. if (point) {
  107428. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  107429. }
  107430. break;
  107431. case "directional":
  107432. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  107433. var directional = light.directional;
  107434. if (directional) {
  107435. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  107436. }
  107437. break;
  107438. case "spot":
  107439. var spot = light.spot;
  107440. if (spot) {
  107441. 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);
  107442. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  107443. }
  107444. break;
  107445. default:
  107446. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  107447. break;
  107448. }
  107449. }
  107450. }
  107451. return false;
  107452. };
  107453. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107454. var material = gltfRuntime.materials[id];
  107455. if (!material || !material.extensions)
  107456. return false;
  107457. var extension = material.extensions[this.name];
  107458. if (!extension)
  107459. return false;
  107460. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  107461. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107462. if (extension.technique === "CONSTANT") {
  107463. standardMaterial.disableLighting = true;
  107464. }
  107465. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  107466. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  107467. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  107468. // Ambient
  107469. if (typeof extension.values.ambient === "string") {
  107470. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  107471. }
  107472. else {
  107473. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  107474. }
  107475. // Diffuse
  107476. if (typeof extension.values.diffuse === "string") {
  107477. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  107478. }
  107479. else {
  107480. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  107481. }
  107482. // Emission
  107483. if (typeof extension.values.emission === "string") {
  107484. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  107485. }
  107486. else {
  107487. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  107488. }
  107489. // Specular
  107490. if (typeof extension.values.specular === "string") {
  107491. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  107492. }
  107493. else {
  107494. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  107495. }
  107496. return true;
  107497. };
  107498. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  107499. // Create buffer from texture url
  107500. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  107501. // Create texture from buffer
  107502. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  107503. }, onError);
  107504. };
  107505. return GLTFMaterialsCommonExtension;
  107506. }(GLTF1.GLTFLoaderExtension));
  107507. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  107508. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  107509. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107510. })(BABYLON || (BABYLON = {}));
  107511. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  107512. var BABYLON;
  107513. (function (BABYLON) {
  107514. var GLTF2;
  107515. (function (GLTF2) {
  107516. var ArrayItem = /** @class */ (function () {
  107517. function ArrayItem() {
  107518. }
  107519. ArrayItem.Assign = function (values) {
  107520. if (values) {
  107521. for (var index = 0; index < values.length; index++) {
  107522. values[index]._index = index;
  107523. }
  107524. }
  107525. };
  107526. return ArrayItem;
  107527. }());
  107528. GLTF2.ArrayItem = ArrayItem;
  107529. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107530. })(BABYLON || (BABYLON = {}));
  107531. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  107532. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  107533. var BABYLON;
  107534. (function (BABYLON) {
  107535. var GLTF2;
  107536. (function (GLTF2) {
  107537. var GLTFLoader = /** @class */ (function () {
  107538. function GLTFLoader() {
  107539. this._completePromises = new Array();
  107540. this._disposed = false;
  107541. this._state = null;
  107542. this._extensions = {};
  107543. this._defaultSampler = {};
  107544. this._requests = new Array();
  107545. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  107546. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  107547. this.compileMaterials = false;
  107548. this.useClipPlane = false;
  107549. this.compileShadowGenerators = false;
  107550. this.onDisposeObservable = new BABYLON.Observable();
  107551. this.onMeshLoadedObservable = new BABYLON.Observable();
  107552. this.onTextureLoadedObservable = new BABYLON.Observable();
  107553. this.onMaterialLoadedObservable = new BABYLON.Observable();
  107554. this.onExtensionLoadedObservable = new BABYLON.Observable();
  107555. this.onCompleteObservable = new BABYLON.Observable();
  107556. }
  107557. GLTFLoader._Register = function (name, factory) {
  107558. if (GLTFLoader._Factories[name]) {
  107559. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  107560. return;
  107561. }
  107562. GLTFLoader._Factories[name] = factory;
  107563. // Keep the order of registration so that extensions registered first are called first.
  107564. GLTFLoader._Names.push(name);
  107565. };
  107566. Object.defineProperty(GLTFLoader.prototype, "state", {
  107567. get: function () {
  107568. return this._state;
  107569. },
  107570. enumerable: true,
  107571. configurable: true
  107572. });
  107573. GLTFLoader.prototype.dispose = function () {
  107574. if (this._disposed) {
  107575. return;
  107576. }
  107577. this._disposed = true;
  107578. this.onDisposeObservable.notifyObservers(this);
  107579. this.onDisposeObservable.clear();
  107580. this._clear();
  107581. };
  107582. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107583. var _this = this;
  107584. return Promise.resolve().then(function () {
  107585. var nodes = null;
  107586. if (meshesNames) {
  107587. var nodeMap_1 = {};
  107588. if (_this._gltf.nodes) {
  107589. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  107590. var node = _a[_i];
  107591. if (node.name) {
  107592. nodeMap_1[node.name] = node;
  107593. }
  107594. }
  107595. }
  107596. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  107597. nodes = names.map(function (name) {
  107598. var node = nodeMap_1[name];
  107599. if (!node) {
  107600. throw new Error("Failed to find node " + name);
  107601. }
  107602. return node;
  107603. });
  107604. }
  107605. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  107606. return {
  107607. meshes: _this._getMeshes(),
  107608. particleSystems: [],
  107609. skeletons: _this._getSkeletons(),
  107610. };
  107611. });
  107612. });
  107613. };
  107614. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107615. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  107616. };
  107617. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  107618. var _this = this;
  107619. return Promise.resolve().then(function () {
  107620. _this._loadExtensions();
  107621. _this._babylonScene = scene;
  107622. _this._rootUrl = rootUrl;
  107623. _this._progressCallback = onProgress;
  107624. _this._state = BABYLON.GLTFLoaderState.Loading;
  107625. _this._loadData(data);
  107626. _this._checkExtensions();
  107627. var promises = new Array();
  107628. if (nodes) {
  107629. promises.push(_this._loadNodesAsync(nodes));
  107630. }
  107631. else {
  107632. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  107633. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  107634. }
  107635. if (_this.compileMaterials) {
  107636. promises.push(_this._compileMaterialsAsync());
  107637. }
  107638. if (_this.compileShadowGenerators) {
  107639. promises.push(_this._compileShadowGeneratorsAsync());
  107640. }
  107641. return Promise.all(promises).then(function () {
  107642. _this._state = BABYLON.GLTFLoaderState.Ready;
  107643. _this._startAnimations();
  107644. BABYLON.Tools.SetImmediate(function () {
  107645. if (!_this._disposed) {
  107646. Promise.all(_this._completePromises).then(function () {
  107647. _this._state = BABYLON.GLTFLoaderState.Complete;
  107648. _this.onCompleteObservable.notifyObservers(_this);
  107649. _this.onCompleteObservable.clear();
  107650. _this._clear();
  107651. }).catch(function (error) {
  107652. BABYLON.Tools.Error("glTF Loader: " + error.message);
  107653. _this._clear();
  107654. });
  107655. }
  107656. });
  107657. });
  107658. }).catch(function (error) {
  107659. BABYLON.Tools.Error("glTF Loader: " + error.message);
  107660. _this._clear();
  107661. throw error;
  107662. });
  107663. };
  107664. GLTFLoader.prototype._loadExtensions = function () {
  107665. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  107666. var name_1 = _a[_i];
  107667. var extension = GLTFLoader._Factories[name_1](this);
  107668. this._extensions[name_1] = extension;
  107669. this.onExtensionLoadedObservable.notifyObservers(extension);
  107670. }
  107671. this.onExtensionLoadedObservable.clear();
  107672. };
  107673. GLTFLoader.prototype._loadData = function (data) {
  107674. this._gltf = data.json;
  107675. this._setupData();
  107676. if (data.bin) {
  107677. var buffers = this._gltf.buffers;
  107678. if (buffers && buffers[0] && !buffers[0].uri) {
  107679. var binaryBuffer = buffers[0];
  107680. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  107681. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  107682. }
  107683. binaryBuffer._data = Promise.resolve(data.bin);
  107684. }
  107685. else {
  107686. BABYLON.Tools.Warn("Unexpected BIN chunk");
  107687. }
  107688. }
  107689. };
  107690. GLTFLoader.prototype._setupData = function () {
  107691. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  107692. GLTF2.ArrayItem.Assign(this._gltf.animations);
  107693. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  107694. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  107695. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  107696. GLTF2.ArrayItem.Assign(this._gltf.images);
  107697. GLTF2.ArrayItem.Assign(this._gltf.materials);
  107698. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  107699. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  107700. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  107701. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  107702. GLTF2.ArrayItem.Assign(this._gltf.skins);
  107703. GLTF2.ArrayItem.Assign(this._gltf.textures);
  107704. if (this._gltf.nodes) {
  107705. var nodeParents = {};
  107706. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  107707. var node = _a[_i];
  107708. if (node.children) {
  107709. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  107710. var index = _c[_b];
  107711. nodeParents[index] = node._index;
  107712. }
  107713. }
  107714. }
  107715. var rootNode = this._createRootNode();
  107716. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  107717. var node = _e[_d];
  107718. var parentIndex = nodeParents[node._index];
  107719. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  107720. }
  107721. }
  107722. };
  107723. GLTFLoader.prototype._checkExtensions = function () {
  107724. if (this._gltf.extensionsRequired) {
  107725. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  107726. var name_2 = _a[_i];
  107727. var extension = this._extensions[name_2];
  107728. if (!extension || !extension.enabled) {
  107729. throw new Error("Require extension " + name_2 + " is not available");
  107730. }
  107731. }
  107732. }
  107733. };
  107734. GLTFLoader.prototype._createRootNode = function () {
  107735. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  107736. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  107737. switch (this.coordinateSystemMode) {
  107738. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  107739. if (!this._babylonScene.useRightHandedSystem) {
  107740. rootNode.rotation = [0, 1, 0, 0];
  107741. rootNode.scale = [1, 1, -1];
  107742. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  107743. }
  107744. break;
  107745. }
  107746. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  107747. this._babylonScene.useRightHandedSystem = true;
  107748. break;
  107749. }
  107750. default: {
  107751. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  107752. }
  107753. }
  107754. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  107755. return rootNode;
  107756. };
  107757. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  107758. var promises = new Array();
  107759. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  107760. var node = nodes_1[_i];
  107761. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  107762. }
  107763. promises.push(this._loadAnimationsAsync());
  107764. return Promise.all(promises).then(function () { });
  107765. };
  107766. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  107767. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  107768. if (promise) {
  107769. return promise;
  107770. }
  107771. var promises = new Array();
  107772. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  107773. var index = _a[_i];
  107774. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  107775. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  107776. }
  107777. promises.push(this._loadAnimationsAsync());
  107778. return Promise.all(promises).then(function () { });
  107779. };
  107780. GLTFLoader.prototype._getMeshes = function () {
  107781. var meshes = new Array();
  107782. // Root mesh is always first.
  107783. meshes.push(this._rootBabylonMesh);
  107784. var nodes = this._gltf.nodes;
  107785. if (nodes) {
  107786. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  107787. var node = nodes_2[_i];
  107788. if (node._babylonMesh) {
  107789. meshes.push(node._babylonMesh);
  107790. }
  107791. if (node._primitiveBabylonMeshes) {
  107792. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  107793. var babylonMesh = _b[_a];
  107794. meshes.push(babylonMesh);
  107795. }
  107796. }
  107797. }
  107798. }
  107799. return meshes;
  107800. };
  107801. GLTFLoader.prototype._getSkeletons = function () {
  107802. var skeletons = new Array();
  107803. var skins = this._gltf.skins;
  107804. if (skins) {
  107805. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  107806. var skin = skins_1[_i];
  107807. if (skin._babylonSkeleton) {
  107808. skeletons.push(skin._babylonSkeleton);
  107809. }
  107810. }
  107811. }
  107812. return skeletons;
  107813. };
  107814. GLTFLoader.prototype._startAnimations = function () {
  107815. var animations = this._gltf.animations;
  107816. if (!animations) {
  107817. return;
  107818. }
  107819. switch (this.animationStartMode) {
  107820. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  107821. // do nothing
  107822. break;
  107823. }
  107824. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  107825. var animation = animations[0];
  107826. animation._babylonAnimationGroup.start(true);
  107827. break;
  107828. }
  107829. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  107830. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  107831. var animation = animations_1[_i];
  107832. animation._babylonAnimationGroup.start(true);
  107833. }
  107834. break;
  107835. }
  107836. default: {
  107837. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  107838. return;
  107839. }
  107840. }
  107841. };
  107842. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  107843. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  107844. if (promise) {
  107845. return promise;
  107846. }
  107847. if (node._babylonMesh) {
  107848. throw new Error(context + ": Invalid recursive node hierarchy");
  107849. }
  107850. var promises = new Array();
  107851. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  107852. node._babylonMesh = babylonMesh;
  107853. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  107854. node._babylonAnimationTargets.push(babylonMesh);
  107855. GLTFLoader._LoadTransform(node, babylonMesh);
  107856. if (node.mesh != undefined) {
  107857. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  107858. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  107859. }
  107860. if (node.children) {
  107861. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  107862. var index = _a[_i];
  107863. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  107864. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  107865. }
  107866. }
  107867. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  107868. return Promise.all(promises).then(function () { });
  107869. };
  107870. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  107871. // TODO: instancing
  107872. var promises = new Array();
  107873. var primitives = mesh.primitives;
  107874. if (!primitives || primitives.length === 0) {
  107875. throw new Error(context + ": Primitives are missing");
  107876. }
  107877. GLTF2.ArrayItem.Assign(primitives);
  107878. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  107879. var primitive = primitives_1[_i];
  107880. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  107881. }
  107882. if (node.skin != undefined) {
  107883. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  107884. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  107885. }
  107886. return Promise.all(promises).then(function () {
  107887. if (node._primitiveBabylonMeshes) {
  107888. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  107889. var primitiveBabylonMesh = _a[_i];
  107890. primitiveBabylonMesh._refreshBoundingInfo(true);
  107891. }
  107892. }
  107893. });
  107894. };
  107895. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  107896. var _this = this;
  107897. var promises = new Array();
  107898. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  107899. babylonMesh.setEnabled(false);
  107900. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  107901. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  107902. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  107903. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  107904. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  107905. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  107906. }));
  107907. if (primitive.material == undefined) {
  107908. babylonMesh.material = this._getDefaultMaterial();
  107909. }
  107910. else {
  107911. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  107912. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  107913. }
  107914. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  107915. return Promise.all(promises).then(function () {
  107916. babylonMesh.setEnabled(true);
  107917. });
  107918. };
  107919. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  107920. var _this = this;
  107921. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  107922. if (promise) {
  107923. return promise;
  107924. }
  107925. var attributes = primitive.attributes;
  107926. if (!attributes) {
  107927. throw new Error(context + ": Attributes are missing");
  107928. }
  107929. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  107930. // TODO: handle other primitive modes
  107931. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  107932. }
  107933. var promises = new Array();
  107934. var babylonVertexData = new BABYLON.VertexData();
  107935. if (primitive.indices == undefined) {
  107936. var positionAccessorIndex = attributes["POSITION"];
  107937. if (positionAccessorIndex != undefined) {
  107938. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  107939. babylonVertexData.indices = new Uint32Array(accessor.count);
  107940. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  107941. babylonVertexData.indices[i] = i;
  107942. }
  107943. }
  107944. }
  107945. else {
  107946. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  107947. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  107948. babylonVertexData.indices = data;
  107949. }));
  107950. }
  107951. var loadAttribute = function (attribute, kind) {
  107952. if (attributes[attribute] == undefined) {
  107953. return;
  107954. }
  107955. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  107956. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  107957. babylonMesh._delayInfo.push(kind);
  107958. }
  107959. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  107960. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  107961. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  107962. if (attribute === "COLOR_0") {
  107963. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  107964. babylonMesh.hasVertexAlpha = true;
  107965. if (accessor.type === "VEC3") {
  107966. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  107967. }
  107968. }
  107969. babylonVertexData.set(attributeData, kind);
  107970. }));
  107971. };
  107972. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  107973. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  107974. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  107975. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  107976. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  107977. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  107978. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  107979. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  107980. return Promise.all(promises).then(function () {
  107981. return babylonVertexData;
  107982. });
  107983. };
  107984. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  107985. if (!primitive.targets) {
  107986. return;
  107987. }
  107988. if (node._numMorphTargets == undefined) {
  107989. node._numMorphTargets = primitive.targets.length;
  107990. }
  107991. else if (primitive.targets.length !== node._numMorphTargets) {
  107992. throw new Error(context + ": Primitives do not have the same number of targets");
  107993. }
  107994. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  107995. for (var index = 0; index < primitive.targets.length; index++) {
  107996. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  107997. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  107998. // TODO: tell the target whether it has positions, normals, tangents
  107999. }
  108000. };
  108001. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  108002. if (!primitive.targets) {
  108003. return Promise.resolve();
  108004. }
  108005. var promises = new Array();
  108006. var morphTargetManager = babylonMesh.morphTargetManager;
  108007. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  108008. var babylonMorphTarget = morphTargetManager.getTarget(index);
  108009. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  108010. }
  108011. return Promise.all(promises).then(function () { });
  108012. };
  108013. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  108014. var _this = this;
  108015. var promises = new Array();
  108016. var loadAttribute = function (attribute, setData) {
  108017. if (attributes[attribute] == undefined) {
  108018. return;
  108019. }
  108020. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  108021. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108022. setData(data);
  108023. }));
  108024. };
  108025. loadAttribute("POSITION", function (data) {
  108026. if (babylonVertexData.positions) {
  108027. for (var i = 0; i < data.length; i++) {
  108028. data[i] += babylonVertexData.positions[i];
  108029. }
  108030. babylonMorphTarget.setPositions(data);
  108031. }
  108032. });
  108033. loadAttribute("NORMAL", function (data) {
  108034. if (babylonVertexData.normals) {
  108035. for (var i = 0; i < data.length; i++) {
  108036. data[i] += babylonVertexData.normals[i];
  108037. }
  108038. babylonMorphTarget.setNormals(data);
  108039. }
  108040. });
  108041. loadAttribute("TANGENT", function (data) {
  108042. if (babylonVertexData.tangents) {
  108043. // Tangent data for morph targets is stored as xyz delta.
  108044. // The vertexData.tangent is stored as xyzw.
  108045. // So we need to skip every fourth vertexData.tangent.
  108046. for (var i = 0, j = 0; i < data.length; i++) {
  108047. data[i] += babylonVertexData.tangents[j++];
  108048. if ((i + 1) % 3 == 0) {
  108049. j++;
  108050. }
  108051. }
  108052. babylonMorphTarget.setTangents(data);
  108053. }
  108054. });
  108055. return Promise.all(promises).then(function () { });
  108056. };
  108057. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  108058. if (accessor.componentType == 5126 /* FLOAT */) {
  108059. return data;
  108060. }
  108061. var factor = 1;
  108062. if (accessor.normalized) {
  108063. switch (accessor.componentType) {
  108064. case 5121 /* UNSIGNED_BYTE */: {
  108065. factor = 1 / 255;
  108066. break;
  108067. }
  108068. case 5123 /* UNSIGNED_SHORT */: {
  108069. factor = 1 / 65535;
  108070. break;
  108071. }
  108072. default: {
  108073. throw new Error(context + ": Invalid component type " + accessor.componentType);
  108074. }
  108075. }
  108076. }
  108077. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  108078. for (var i = 0; i < result.length; i++) {
  108079. result[i] = data[i] * factor;
  108080. }
  108081. return result;
  108082. };
  108083. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  108084. var result = new Float32Array(data.length / 3 * 4);
  108085. var offset = 0;
  108086. for (var i = 0; i < result.length; i++) {
  108087. if ((i + 1) % 4 === 0) {
  108088. result[i] = 1;
  108089. }
  108090. else {
  108091. result[i] = data[offset++];
  108092. }
  108093. }
  108094. return result;
  108095. };
  108096. GLTFLoader._LoadTransform = function (node, babylonNode) {
  108097. var position = BABYLON.Vector3.Zero();
  108098. var rotation = BABYLON.Quaternion.Identity();
  108099. var scaling = BABYLON.Vector3.One();
  108100. if (node.matrix) {
  108101. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  108102. matrix.decompose(scaling, rotation, position);
  108103. }
  108104. else {
  108105. if (node.translation)
  108106. position = BABYLON.Vector3.FromArray(node.translation);
  108107. if (node.rotation)
  108108. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  108109. if (node.scale)
  108110. scaling = BABYLON.Vector3.FromArray(node.scale);
  108111. }
  108112. babylonNode.position = position;
  108113. babylonNode.rotationQuaternion = rotation;
  108114. babylonNode.scaling = scaling;
  108115. };
  108116. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  108117. var _this = this;
  108118. var assignSkeleton = function () {
  108119. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  108120. var babylonMesh = _a[_i];
  108121. babylonMesh.skeleton = skin._babylonSkeleton;
  108122. }
  108123. node._babylonMesh.parent = _this._rootBabylonMesh;
  108124. node._babylonMesh.position = BABYLON.Vector3.Zero();
  108125. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  108126. node._babylonMesh.scaling = BABYLON.Vector3.One();
  108127. };
  108128. if (skin._loaded) {
  108129. return skin._loaded.then(function () {
  108130. assignSkeleton();
  108131. });
  108132. }
  108133. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  108134. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  108135. var skeletonId = "skeleton" + skin._index;
  108136. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  108137. skin._babylonSkeleton = babylonSkeleton;
  108138. _this._loadBones(context, skin, inverseBindMatricesData);
  108139. assignSkeleton();
  108140. }));
  108141. };
  108142. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  108143. if (skin.inverseBindMatrices == undefined) {
  108144. return Promise.resolve(null);
  108145. }
  108146. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  108147. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108148. return data;
  108149. });
  108150. };
  108151. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  108152. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  108153. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  108154. node._babylonAnimationTargets.push(babylonBone);
  108155. return babylonBone;
  108156. };
  108157. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  108158. var babylonBones = {};
  108159. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  108160. var index = _a[_i];
  108161. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  108162. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  108163. }
  108164. };
  108165. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  108166. var babylonBone = babylonBones[node._index];
  108167. if (babylonBone) {
  108168. return babylonBone;
  108169. }
  108170. var boneIndex = skin.joints.indexOf(node._index);
  108171. var baseMatrix = BABYLON.Matrix.Identity();
  108172. if (inverseBindMatricesData && boneIndex !== -1) {
  108173. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  108174. baseMatrix.invertToRef(baseMatrix);
  108175. }
  108176. var babylonParentBone = null;
  108177. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  108178. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  108179. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  108180. }
  108181. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  108182. babylonBones[node._index] = babylonBone;
  108183. return babylonBone;
  108184. };
  108185. GLTFLoader.prototype._getNodeMatrix = function (node) {
  108186. return node.matrix ?
  108187. BABYLON.Matrix.FromArray(node.matrix) :
  108188. 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());
  108189. };
  108190. GLTFLoader.prototype._loadAnimationsAsync = function () {
  108191. var animations = this._gltf.animations;
  108192. if (!animations) {
  108193. return Promise.resolve();
  108194. }
  108195. var promises = new Array();
  108196. for (var index = 0; index < animations.length; index++) {
  108197. var animation = animations[index];
  108198. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  108199. }
  108200. return Promise.all(promises).then(function () { });
  108201. };
  108202. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  108203. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  108204. animation._babylonAnimationGroup = babylonAnimationGroup;
  108205. var promises = new Array();
  108206. GLTF2.ArrayItem.Assign(animation.channels);
  108207. GLTF2.ArrayItem.Assign(animation.samplers);
  108208. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  108209. var channel = _a[_i];
  108210. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  108211. }
  108212. return Promise.all(promises).then(function () {
  108213. babylonAnimationGroup.normalize();
  108214. });
  108215. };
  108216. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  108217. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  108218. if (!targetNode._babylonMesh) {
  108219. return Promise.resolve();
  108220. }
  108221. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  108222. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  108223. var targetPath;
  108224. var animationType;
  108225. switch (channel.target.path) {
  108226. case "translation" /* TRANSLATION */: {
  108227. targetPath = "position";
  108228. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108229. break;
  108230. }
  108231. case "rotation" /* ROTATION */: {
  108232. targetPath = "rotationQuaternion";
  108233. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  108234. break;
  108235. }
  108236. case "scale" /* SCALE */: {
  108237. targetPath = "scaling";
  108238. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  108239. break;
  108240. }
  108241. case "weights" /* WEIGHTS */: {
  108242. targetPath = "influence";
  108243. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  108244. break;
  108245. }
  108246. default: {
  108247. throw new Error(context + ": Invalid target path " + channel.target.path);
  108248. }
  108249. }
  108250. var outputBufferOffset = 0;
  108251. var getNextOutputValue;
  108252. switch (targetPath) {
  108253. case "position": {
  108254. getNextOutputValue = function () {
  108255. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  108256. outputBufferOffset += 3;
  108257. return value;
  108258. };
  108259. break;
  108260. }
  108261. case "rotationQuaternion": {
  108262. getNextOutputValue = function () {
  108263. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  108264. outputBufferOffset += 4;
  108265. return value;
  108266. };
  108267. break;
  108268. }
  108269. case "scaling": {
  108270. getNextOutputValue = function () {
  108271. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  108272. outputBufferOffset += 3;
  108273. return value;
  108274. };
  108275. break;
  108276. }
  108277. case "influence": {
  108278. getNextOutputValue = function () {
  108279. var value = new Array(targetNode._numMorphTargets);
  108280. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  108281. value[i] = data.output[outputBufferOffset++];
  108282. }
  108283. return value;
  108284. };
  108285. break;
  108286. }
  108287. }
  108288. var getNextKey;
  108289. switch (data.interpolation) {
  108290. case "STEP" /* STEP */: {
  108291. getNextKey = function (frameIndex) { return ({
  108292. frame: data.input[frameIndex],
  108293. value: getNextOutputValue(),
  108294. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  108295. }); };
  108296. break;
  108297. }
  108298. case "LINEAR" /* LINEAR */: {
  108299. getNextKey = function (frameIndex) { return ({
  108300. frame: data.input[frameIndex],
  108301. value: getNextOutputValue()
  108302. }); };
  108303. break;
  108304. }
  108305. case "CUBICSPLINE" /* CUBICSPLINE */: {
  108306. getNextKey = function (frameIndex) { return ({
  108307. frame: data.input[frameIndex],
  108308. inTangent: getNextOutputValue(),
  108309. value: getNextOutputValue(),
  108310. outTangent: getNextOutputValue()
  108311. }); };
  108312. break;
  108313. }
  108314. }
  108315. var keys;
  108316. if (data.input.length === 1) {
  108317. var key = getNextKey(0);
  108318. keys = [
  108319. { frame: key.frame, value: key.value },
  108320. { frame: key.frame + 1, value: key.value }
  108321. ];
  108322. }
  108323. else {
  108324. keys = new Array(data.input.length);
  108325. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  108326. keys[frameIndex] = getNextKey(frameIndex);
  108327. }
  108328. }
  108329. if (targetPath === "influence") {
  108330. var _loop_1 = function (targetIndex) {
  108331. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  108332. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  108333. babylonAnimation.setKeys(keys.map(function (key) { return ({
  108334. frame: key.frame,
  108335. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  108336. value: key.value[targetIndex],
  108337. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  108338. }); }));
  108339. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  108340. var babylonMesh = _a[_i];
  108341. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  108342. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  108343. }
  108344. };
  108345. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  108346. _loop_1(targetIndex);
  108347. }
  108348. }
  108349. else {
  108350. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  108351. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  108352. babylonAnimation.setKeys(keys);
  108353. if (targetNode._babylonAnimationTargets) {
  108354. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  108355. var target = _a[_i];
  108356. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  108357. }
  108358. }
  108359. }
  108360. });
  108361. };
  108362. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  108363. if (sampler._data) {
  108364. return sampler._data;
  108365. }
  108366. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  108367. switch (interpolation) {
  108368. case "STEP" /* STEP */:
  108369. case "LINEAR" /* LINEAR */:
  108370. case "CUBICSPLINE" /* CUBICSPLINE */: {
  108371. break;
  108372. }
  108373. default: {
  108374. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  108375. }
  108376. }
  108377. var inputData;
  108378. var outputData;
  108379. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  108380. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  108381. sampler._data = Promise.all([
  108382. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  108383. inputData = data;
  108384. }),
  108385. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  108386. outputData = data;
  108387. })
  108388. ]).then(function () {
  108389. return {
  108390. input: inputData,
  108391. interpolation: interpolation,
  108392. output: outputData,
  108393. };
  108394. });
  108395. return sampler._data;
  108396. };
  108397. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  108398. if (buffer._data) {
  108399. return buffer._data;
  108400. }
  108401. if (!buffer.uri) {
  108402. throw new Error(context + ": Uri is missing");
  108403. }
  108404. buffer._data = this._loadUriAsync(context, buffer.uri);
  108405. return buffer._data;
  108406. };
  108407. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  108408. if (bufferView._data) {
  108409. return bufferView._data;
  108410. }
  108411. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  108412. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  108413. try {
  108414. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  108415. }
  108416. catch (e) {
  108417. throw new Error(context + ": " + e.message);
  108418. }
  108419. });
  108420. return bufferView._data;
  108421. };
  108422. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  108423. var _this = this;
  108424. if (accessor.sparse) {
  108425. throw new Error(context + ": Sparse accessors are not currently supported");
  108426. }
  108427. if (accessor._data) {
  108428. return accessor._data;
  108429. }
  108430. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  108431. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  108432. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  108433. var byteOffset = accessor.byteOffset || 0;
  108434. var byteStride = bufferView.byteStride;
  108435. if (byteStride === 0) {
  108436. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  108437. }
  108438. try {
  108439. switch (accessor.componentType) {
  108440. case 5120 /* BYTE */: {
  108441. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  108442. }
  108443. case 5121 /* UNSIGNED_BYTE */: {
  108444. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  108445. }
  108446. case 5122 /* SHORT */: {
  108447. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  108448. }
  108449. case 5123 /* UNSIGNED_SHORT */: {
  108450. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  108451. }
  108452. case 5125 /* UNSIGNED_INT */: {
  108453. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  108454. }
  108455. case 5126 /* FLOAT */: {
  108456. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  108457. }
  108458. default: {
  108459. throw new Error(context + ": Invalid component type " + accessor.componentType);
  108460. }
  108461. }
  108462. }
  108463. catch (e) {
  108464. throw new Error(context + ": " + e);
  108465. }
  108466. });
  108467. return accessor._data;
  108468. };
  108469. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  108470. byteOffset += data.byteOffset;
  108471. var targetLength = count * numComponents;
  108472. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  108473. return new typedArray(data.buffer, byteOffset, targetLength);
  108474. }
  108475. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  108476. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  108477. var targetBuffer = new typedArray(targetLength);
  108478. var sourceIndex = 0;
  108479. var targetIndex = 0;
  108480. while (targetIndex < targetLength) {
  108481. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  108482. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  108483. targetIndex++;
  108484. }
  108485. sourceIndex += elementStride;
  108486. }
  108487. return targetBuffer;
  108488. };
  108489. GLTFLoader.prototype._getDefaultMaterial = function () {
  108490. var id = "__gltf_default";
  108491. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  108492. if (!babylonMaterial) {
  108493. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  108494. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  108495. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  108496. babylonMaterial.metallic = 1;
  108497. babylonMaterial.roughness = 1;
  108498. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  108499. }
  108500. return babylonMaterial;
  108501. };
  108502. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  108503. var promises = new Array();
  108504. var babylonMaterial = material._babylonMaterial;
  108505. // Ensure metallic workflow
  108506. babylonMaterial.metallic = 1;
  108507. babylonMaterial.roughness = 1;
  108508. var properties = material.pbrMetallicRoughness;
  108509. if (properties) {
  108510. if (properties.baseColorFactor) {
  108511. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  108512. babylonMaterial.alpha = properties.baseColorFactor[3];
  108513. }
  108514. else {
  108515. babylonMaterial.albedoColor = BABYLON.Color3.White();
  108516. }
  108517. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  108518. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  108519. if (properties.baseColorTexture) {
  108520. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  108521. babylonMaterial.albedoTexture = texture;
  108522. }));
  108523. }
  108524. if (properties.metallicRoughnessTexture) {
  108525. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  108526. babylonMaterial.metallicTexture = texture;
  108527. }));
  108528. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  108529. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  108530. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  108531. }
  108532. }
  108533. this._loadMaterialAlphaProperties(context, material);
  108534. return Promise.all(promises).then(function () { });
  108535. };
  108536. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  108537. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  108538. if (promise) {
  108539. return promise;
  108540. }
  108541. material._babylonMeshes = material._babylonMeshes || [];
  108542. material._babylonMeshes.push(babylonMesh);
  108543. if (material._loaded) {
  108544. babylonMesh.material = material._babylonMaterial;
  108545. return material._loaded;
  108546. }
  108547. var promises = new Array();
  108548. var babylonMaterial = this._createMaterial(material);
  108549. material._babylonMaterial = babylonMaterial;
  108550. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  108551. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  108552. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  108553. babylonMesh.material = babylonMaterial;
  108554. return (material._loaded = Promise.all(promises).then(function () { }));
  108555. };
  108556. GLTFLoader.prototype._createMaterial = function (material) {
  108557. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  108558. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  108559. return babylonMaterial;
  108560. };
  108561. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  108562. var promises = new Array();
  108563. var babylonMaterial = material._babylonMaterial;
  108564. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  108565. if (material.doubleSided) {
  108566. babylonMaterial.backFaceCulling = false;
  108567. babylonMaterial.twoSidedLighting = true;
  108568. }
  108569. if (material.normalTexture) {
  108570. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  108571. babylonMaterial.bumpTexture = texture;
  108572. }));
  108573. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  108574. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  108575. if (material.normalTexture.scale != undefined) {
  108576. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  108577. }
  108578. }
  108579. if (material.occlusionTexture) {
  108580. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  108581. babylonMaterial.ambientTexture = texture;
  108582. }));
  108583. babylonMaterial.useAmbientInGrayScale = true;
  108584. if (material.occlusionTexture.strength != undefined) {
  108585. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  108586. }
  108587. }
  108588. if (material.emissiveTexture) {
  108589. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  108590. babylonMaterial.emissiveTexture = texture;
  108591. }));
  108592. }
  108593. return Promise.all(promises).then(function () { });
  108594. };
  108595. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  108596. var babylonMaterial = material._babylonMaterial;
  108597. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  108598. switch (alphaMode) {
  108599. case "OPAQUE" /* OPAQUE */: {
  108600. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  108601. break;
  108602. }
  108603. case "MASK" /* MASK */: {
  108604. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  108605. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  108606. if (babylonMaterial.alpha) {
  108607. if (babylonMaterial.alpha === 0) {
  108608. babylonMaterial.alphaCutOff = 1;
  108609. }
  108610. else {
  108611. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  108612. }
  108613. babylonMaterial.alpha = 1;
  108614. }
  108615. if (babylonMaterial.albedoTexture) {
  108616. babylonMaterial.albedoTexture.hasAlpha = true;
  108617. }
  108618. break;
  108619. }
  108620. case "BLEND" /* BLEND */: {
  108621. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  108622. if (babylonMaterial.albedoTexture) {
  108623. babylonMaterial.albedoTexture.hasAlpha = true;
  108624. babylonMaterial.useAlphaFromAlbedoTexture = true;
  108625. }
  108626. break;
  108627. }
  108628. default: {
  108629. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  108630. }
  108631. }
  108632. };
  108633. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  108634. var _this = this;
  108635. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  108636. context = "#/textures/" + textureInfo.index;
  108637. var promises = new Array();
  108638. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  108639. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  108640. var deferred = new BABYLON.Deferred();
  108641. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  108642. if (!_this._disposed) {
  108643. deferred.resolve();
  108644. }
  108645. }, function (message, exception) {
  108646. if (!_this._disposed) {
  108647. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  108648. }
  108649. });
  108650. promises.push(deferred.promise);
  108651. babylonTexture.name = texture.name || "texture" + texture._index;
  108652. babylonTexture.wrapU = samplerData.wrapU;
  108653. babylonTexture.wrapV = samplerData.wrapV;
  108654. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  108655. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  108656. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  108657. babylonTexture.updateURL(objectURL);
  108658. }));
  108659. assign(babylonTexture);
  108660. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  108661. return Promise.all(promises).then(function () { });
  108662. };
  108663. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  108664. if (!sampler._data) {
  108665. sampler._data = {
  108666. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  108667. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  108668. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  108669. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  108670. };
  108671. }
  108672. ;
  108673. return sampler._data;
  108674. };
  108675. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  108676. if (image._objectURL) {
  108677. return image._objectURL;
  108678. }
  108679. var promise;
  108680. if (image.uri) {
  108681. promise = this._loadUriAsync(context, image.uri);
  108682. }
  108683. else {
  108684. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  108685. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  108686. }
  108687. image._objectURL = promise.then(function (data) {
  108688. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  108689. });
  108690. return image._objectURL;
  108691. };
  108692. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  108693. var _this = this;
  108694. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  108695. if (promise) {
  108696. return promise;
  108697. }
  108698. if (!GLTFLoader._ValidateUri(uri)) {
  108699. throw new Error(context + ": Uri '" + uri + "' is invalid");
  108700. }
  108701. if (BABYLON.Tools.IsBase64(uri)) {
  108702. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  108703. }
  108704. return new Promise(function (resolve, reject) {
  108705. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  108706. if (!_this._disposed) {
  108707. resolve(new Uint8Array(data));
  108708. }
  108709. }, function (event) {
  108710. if (!_this._disposed) {
  108711. try {
  108712. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  108713. request._lengthComputable = event.lengthComputable;
  108714. request._loaded = event.loaded;
  108715. request._total = event.total;
  108716. _this._onProgress();
  108717. }
  108718. }
  108719. catch (e) {
  108720. reject(e);
  108721. }
  108722. }
  108723. }, _this._babylonScene.database, true, function (request, exception) {
  108724. if (!_this._disposed) {
  108725. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  108726. }
  108727. });
  108728. _this._requests.push(request);
  108729. });
  108730. };
  108731. GLTFLoader.prototype._onProgress = function () {
  108732. if (!this._progressCallback) {
  108733. return;
  108734. }
  108735. var lengthComputable = true;
  108736. var loaded = 0;
  108737. var total = 0;
  108738. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108739. var request = _a[_i];
  108740. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  108741. return;
  108742. }
  108743. lengthComputable = lengthComputable && request._lengthComputable;
  108744. loaded += request._loaded;
  108745. total += request._total;
  108746. }
  108747. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  108748. };
  108749. GLTFLoader._GetProperty = function (context, array, index) {
  108750. if (!array || index == undefined || !array[index]) {
  108751. throw new Error(context + ": Failed to find index " + index);
  108752. }
  108753. return array[index];
  108754. };
  108755. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  108756. // Set defaults if undefined
  108757. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  108758. switch (mode) {
  108759. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  108760. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  108761. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108762. default:
  108763. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  108764. return BABYLON.Texture.WRAP_ADDRESSMODE;
  108765. }
  108766. };
  108767. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  108768. // Set defaults if undefined
  108769. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  108770. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  108771. if (magFilter === 9729 /* LINEAR */) {
  108772. switch (minFilter) {
  108773. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  108774. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  108775. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  108776. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  108777. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  108778. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  108779. default:
  108780. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  108781. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  108782. }
  108783. }
  108784. else {
  108785. if (magFilter !== 9728 /* NEAREST */) {
  108786. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  108787. }
  108788. switch (minFilter) {
  108789. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  108790. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  108791. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  108792. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  108793. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  108794. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  108795. default:
  108796. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  108797. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  108798. }
  108799. }
  108800. };
  108801. GLTFLoader._GetNumComponents = function (context, type) {
  108802. switch (type) {
  108803. case "SCALAR": return 1;
  108804. case "VEC2": return 2;
  108805. case "VEC3": return 3;
  108806. case "VEC4": return 4;
  108807. case "MAT2": return 4;
  108808. case "MAT3": return 9;
  108809. case "MAT4": return 16;
  108810. }
  108811. throw new Error(context + ": Invalid type " + type);
  108812. };
  108813. GLTFLoader._ValidateUri = function (uri) {
  108814. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  108815. };
  108816. GLTFLoader.prototype._compileMaterialsAsync = function () {
  108817. var promises = new Array();
  108818. if (this._gltf.materials) {
  108819. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  108820. var material = _a[_i];
  108821. var babylonMaterial = material._babylonMaterial;
  108822. var babylonMeshes = material._babylonMeshes;
  108823. if (babylonMaterial && babylonMeshes) {
  108824. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  108825. var babylonMesh = babylonMeshes_1[_b];
  108826. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  108827. if (this.useClipPlane) {
  108828. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  108829. }
  108830. }
  108831. }
  108832. }
  108833. }
  108834. return Promise.all(promises).then(function () { });
  108835. };
  108836. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  108837. var promises = new Array();
  108838. var lights = this._babylonScene.lights;
  108839. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  108840. var light = lights_1[_i];
  108841. var generator = light.getShadowGenerator();
  108842. if (generator) {
  108843. promises.push(generator.forceCompilationAsync());
  108844. }
  108845. }
  108846. return Promise.all(promises).then(function () { });
  108847. };
  108848. GLTFLoader.prototype._clear = function () {
  108849. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  108850. var request = _a[_i];
  108851. request.abort();
  108852. }
  108853. this._requests.length = 0;
  108854. if (this._gltf && this._gltf.images) {
  108855. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  108856. var image = _c[_b];
  108857. if (image._objectURL) {
  108858. image._objectURL.then(function (value) {
  108859. URL.revokeObjectURL(value);
  108860. });
  108861. image._objectURL = undefined;
  108862. }
  108863. }
  108864. }
  108865. delete this._gltf;
  108866. delete this._babylonScene;
  108867. this._completePromises.length = 0;
  108868. for (var name_3 in this._extensions) {
  108869. this._extensions[name_3].dispose();
  108870. }
  108871. this._extensions = {};
  108872. delete this._rootBabylonMesh;
  108873. delete this._progressCallback;
  108874. this.onMeshLoadedObservable.clear();
  108875. this.onTextureLoadedObservable.clear();
  108876. this.onMaterialLoadedObservable.clear();
  108877. };
  108878. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  108879. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  108880. var name_4 = _a[_i];
  108881. var extension = this._extensions[name_4];
  108882. if (extension.enabled) {
  108883. var promise = actionAsync(extension);
  108884. if (promise) {
  108885. return promise;
  108886. }
  108887. }
  108888. }
  108889. return null;
  108890. };
  108891. GLTFLoader._Names = new Array();
  108892. GLTFLoader._Factories = {};
  108893. return GLTFLoader;
  108894. }());
  108895. GLTF2.GLTFLoader = GLTFLoader;
  108896. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  108897. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108898. })(BABYLON || (BABYLON = {}));
  108899. //# sourceMappingURL=babylon.glTFLoader.js.map
  108900. var BABYLON;
  108901. (function (BABYLON) {
  108902. var GLTF2;
  108903. (function (GLTF2) {
  108904. var GLTFLoaderExtension = /** @class */ (function () {
  108905. function GLTFLoaderExtension(loader) {
  108906. this.enabled = true;
  108907. this._loader = loader;
  108908. }
  108909. GLTFLoaderExtension.prototype.dispose = function () {
  108910. delete this._loader;
  108911. };
  108912. // #region Overridable Methods
  108913. /** Override this method to modify the default behavior for loading scenes. */
  108914. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  108915. /** Override this method to modify the default behavior for loading nodes. */
  108916. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  108917. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  108918. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  108919. /** Override this method to modify the default behavior for loading materials. */
  108920. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  108921. /** Override this method to modify the default behavior for loading uris. */
  108922. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  108923. // #endregion
  108924. /** Helper method called by a loader extension to load an glTF extension. */
  108925. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  108926. if (!property.extensions) {
  108927. return null;
  108928. }
  108929. var extensions = property.extensions;
  108930. var extension = extensions[this.name];
  108931. if (!extension) {
  108932. return null;
  108933. }
  108934. // Clear out the extension before executing the action to avoid recursing into the same property.
  108935. delete extensions[this.name];
  108936. try {
  108937. return actionAsync(context + "/extensions/" + this.name, extension);
  108938. }
  108939. finally {
  108940. // Restore the extension after executing the action.
  108941. extensions[this.name] = extension;
  108942. }
  108943. };
  108944. /** Helper method called by the loader to allow extensions to override loading scenes. */
  108945. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  108946. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  108947. };
  108948. /** Helper method called by the loader to allow extensions to override loading nodes. */
  108949. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  108950. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  108951. };
  108952. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  108953. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  108954. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  108955. };
  108956. /** Helper method called by the loader to allow extensions to override loading materials. */
  108957. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  108958. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  108959. };
  108960. /** Helper method called by the loader to allow extensions to override loading uris. */
  108961. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  108962. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  108963. };
  108964. return GLTFLoaderExtension;
  108965. }());
  108966. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  108967. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108968. })(BABYLON || (BABYLON = {}));
  108969. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  108970. var BABYLON;
  108971. (function (BABYLON) {
  108972. var GLTF2;
  108973. (function (GLTF2) {
  108974. var Extensions;
  108975. (function (Extensions) {
  108976. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  108977. var NAME = "MSFT_lod";
  108978. var MSFT_lod = /** @class */ (function (_super) {
  108979. __extends(MSFT_lod, _super);
  108980. function MSFT_lod() {
  108981. var _this = _super !== null && _super.apply(this, arguments) || this;
  108982. _this.name = NAME;
  108983. /**
  108984. * Maximum number of LODs to load, starting from the lowest LOD.
  108985. */
  108986. _this.maxLODsToLoad = Number.MAX_VALUE;
  108987. _this._loadingNodeLOD = null;
  108988. _this._loadNodeSignals = {};
  108989. _this._loadingMaterialLOD = null;
  108990. _this._loadMaterialSignals = {};
  108991. return _this;
  108992. }
  108993. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  108994. var _this = this;
  108995. return this._loadExtensionAsync(context, node, function (context, extension) {
  108996. var firstPromise;
  108997. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  108998. var _loop_1 = function (indexLOD) {
  108999. var nodeLOD = nodeLODs[indexLOD];
  109000. if (indexLOD !== 0) {
  109001. _this._loadingNodeLOD = nodeLOD;
  109002. if (!_this._loadNodeSignals[nodeLOD._index]) {
  109003. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  109004. }
  109005. }
  109006. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  109007. if (indexLOD !== 0) {
  109008. var previousNodeLOD = nodeLODs[indexLOD - 1];
  109009. previousNodeLOD._babylonMesh.setEnabled(false);
  109010. }
  109011. if (indexLOD !== nodeLODs.length - 1) {
  109012. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  109013. if (_this._loadNodeSignals[nodeIndex]) {
  109014. _this._loadNodeSignals[nodeIndex].resolve();
  109015. delete _this._loadNodeSignals[nodeIndex];
  109016. }
  109017. }
  109018. });
  109019. if (indexLOD === 0) {
  109020. firstPromise = promise;
  109021. }
  109022. else {
  109023. _this._loader._completePromises.push(promise);
  109024. _this._loadingNodeLOD = null;
  109025. }
  109026. };
  109027. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  109028. _loop_1(indexLOD);
  109029. }
  109030. return firstPromise;
  109031. });
  109032. };
  109033. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  109034. var _this = this;
  109035. // Don't load material LODs if already loading a node LOD.
  109036. if (this._loadingNodeLOD) {
  109037. return null;
  109038. }
  109039. return this._loadExtensionAsync(context, material, function (context, extension) {
  109040. var firstPromise;
  109041. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  109042. var _loop_2 = function (indexLOD) {
  109043. var materialLOD = materialLODs[indexLOD];
  109044. if (indexLOD !== 0) {
  109045. _this._loadingMaterialLOD = materialLOD;
  109046. if (!_this._loadMaterialSignals[materialLOD._index]) {
  109047. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  109048. }
  109049. }
  109050. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  109051. if (indexLOD !== materialLODs.length - 1) {
  109052. var materialIndex = materialLODs[indexLOD + 1]._index;
  109053. if (_this._loadMaterialSignals[materialIndex]) {
  109054. _this._loadMaterialSignals[materialIndex].resolve();
  109055. delete _this._loadMaterialSignals[materialIndex];
  109056. }
  109057. }
  109058. });
  109059. if (indexLOD === 0) {
  109060. firstPromise = promise;
  109061. }
  109062. else {
  109063. _this._loader._completePromises.push(promise);
  109064. _this._loadingMaterialLOD = null;
  109065. }
  109066. };
  109067. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  109068. _loop_2(indexLOD);
  109069. }
  109070. return firstPromise;
  109071. });
  109072. };
  109073. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  109074. var _this = this;
  109075. // Defer the loading of uris if loading a material or node LOD.
  109076. if (this._loadingMaterialLOD) {
  109077. var index = this._loadingMaterialLOD._index;
  109078. return this._loadMaterialSignals[index].promise.then(function () {
  109079. return _this._loader._loadUriAsync(context, uri);
  109080. });
  109081. }
  109082. else if (this._loadingNodeLOD) {
  109083. var index = this._loadingNodeLOD._index;
  109084. return this._loadNodeSignals[index].promise.then(function () {
  109085. return _this._loader._loadUriAsync(context, uri);
  109086. });
  109087. }
  109088. return null;
  109089. };
  109090. /**
  109091. * Gets an array of LOD properties from lowest to highest.
  109092. */
  109093. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  109094. if (this.maxLODsToLoad <= 0) {
  109095. throw new Error("maxLODsToLoad must be greater than zero");
  109096. }
  109097. var properties = new Array();
  109098. for (var i = ids.length - 1; i >= 0; i--) {
  109099. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  109100. if (properties.length === this.maxLODsToLoad) {
  109101. return properties;
  109102. }
  109103. }
  109104. properties.push(property);
  109105. return properties;
  109106. };
  109107. return MSFT_lod;
  109108. }(GLTF2.GLTFLoaderExtension));
  109109. Extensions.MSFT_lod = MSFT_lod;
  109110. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  109111. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109112. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109113. })(BABYLON || (BABYLON = {}));
  109114. //# sourceMappingURL=MSFT_lod.js.map
  109115. var BABYLON;
  109116. (function (BABYLON) {
  109117. var GLTF2;
  109118. (function (GLTF2) {
  109119. var Extensions;
  109120. (function (Extensions) {
  109121. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  109122. var NAME = "KHR_draco_mesh_compression";
  109123. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  109124. __extends(KHR_draco_mesh_compression, _super);
  109125. function KHR_draco_mesh_compression(loader) {
  109126. var _this = _super.call(this, loader) || this;
  109127. _this.name = NAME;
  109128. _this._dracoCompression = null;
  109129. // Disable extension if decoder is not available.
  109130. if (!BABYLON.DracoCompression.DecoderUrl) {
  109131. _this.enabled = false;
  109132. }
  109133. return _this;
  109134. }
  109135. KHR_draco_mesh_compression.prototype.dispose = function () {
  109136. if (this._dracoCompression) {
  109137. this._dracoCompression.dispose();
  109138. }
  109139. _super.prototype.dispose.call(this);
  109140. };
  109141. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109142. var _this = this;
  109143. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  109144. if (primitive.mode != undefined) {
  109145. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  109146. primitive.mode !== 4 /* TRIANGLES */) {
  109147. throw new Error(context + ": Unsupported mode " + primitive.mode);
  109148. }
  109149. // TODO: handle triangle strips
  109150. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  109151. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  109152. }
  109153. }
  109154. var attributes = {};
  109155. var loadAttribute = function (name, kind) {
  109156. var uniqueId = extension.attributes[name];
  109157. if (uniqueId == undefined) {
  109158. return;
  109159. }
  109160. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109161. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109162. babylonMesh._delayInfo.push(kind);
  109163. }
  109164. attributes[kind] = uniqueId;
  109165. };
  109166. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109167. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109168. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109169. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109170. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109171. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109172. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109173. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  109174. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  109175. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  109176. try {
  109177. if (!_this._dracoCompression) {
  109178. _this._dracoCompression = new BABYLON.DracoCompression();
  109179. }
  109180. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  109181. }
  109182. catch (e) {
  109183. throw new Error(context + ": " + e.message);
  109184. }
  109185. });
  109186. });
  109187. };
  109188. return KHR_draco_mesh_compression;
  109189. }(GLTF2.GLTFLoaderExtension));
  109190. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  109191. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  109192. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109193. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109194. })(BABYLON || (BABYLON = {}));
  109195. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  109196. var BABYLON;
  109197. (function (BABYLON) {
  109198. var GLTF2;
  109199. (function (GLTF2) {
  109200. var Extensions;
  109201. (function (Extensions) {
  109202. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  109203. var NAME = "KHR_materials_pbrSpecularGlossiness";
  109204. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  109205. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  109206. function KHR_materials_pbrSpecularGlossiness() {
  109207. var _this = _super !== null && _super.apply(this, arguments) || this;
  109208. _this.name = NAME;
  109209. return _this;
  109210. }
  109211. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  109212. var _this = this;
  109213. return this._loadExtensionAsync(context, material, function (context, extension) {
  109214. material._babylonMeshes = material._babylonMeshes || [];
  109215. material._babylonMeshes.push(babylonMesh);
  109216. if (material._loaded) {
  109217. babylonMesh.material = material._babylonMaterial;
  109218. return material._loaded;
  109219. }
  109220. var promises = new Array();
  109221. var babylonMaterial = _this._loader._createMaterial(material);
  109222. material._babylonMaterial = babylonMaterial;
  109223. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  109224. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  109225. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109226. babylonMesh.material = babylonMaterial;
  109227. return (material._loaded = Promise.all(promises).then(function () { }));
  109228. });
  109229. };
  109230. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  109231. var promises = new Array();
  109232. var babylonMaterial = material._babylonMaterial;
  109233. if (properties.diffuseFactor) {
  109234. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  109235. babylonMaterial.alpha = properties.diffuseFactor[3];
  109236. }
  109237. else {
  109238. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109239. }
  109240. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  109241. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  109242. if (properties.diffuseTexture) {
  109243. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  109244. babylonMaterial.albedoTexture = texture;
  109245. }));
  109246. }
  109247. if (properties.specularGlossinessTexture) {
  109248. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  109249. babylonMaterial.reflectivityTexture = texture;
  109250. }));
  109251. babylonMaterial.reflectivityTexture.hasAlpha = true;
  109252. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  109253. }
  109254. loader._loadMaterialAlphaProperties(context, material);
  109255. return Promise.all(promises).then(function () { });
  109256. };
  109257. return KHR_materials_pbrSpecularGlossiness;
  109258. }(GLTF2.GLTFLoaderExtension));
  109259. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  109260. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  109261. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109262. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109263. })(BABYLON || (BABYLON = {}));
  109264. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  109265. var BABYLON;
  109266. (function (BABYLON) {
  109267. var GLTF2;
  109268. (function (GLTF2) {
  109269. var Extensions;
  109270. (function (Extensions) {
  109271. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  109272. var NAME = "KHR_lights";
  109273. var LightType;
  109274. (function (LightType) {
  109275. LightType["AMBIENT"] = "ambient";
  109276. LightType["DIRECTIONAL"] = "directional";
  109277. LightType["POINT"] = "point";
  109278. LightType["SPOT"] = "spot";
  109279. })(LightType || (LightType = {}));
  109280. var KHR_lights = /** @class */ (function (_super) {
  109281. __extends(KHR_lights, _super);
  109282. function KHR_lights() {
  109283. var _this = _super !== null && _super.apply(this, arguments) || this;
  109284. _this.name = NAME;
  109285. return _this;
  109286. }
  109287. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  109288. var _this = this;
  109289. return this._loadExtensionAsync(context, scene, function (context, extension) {
  109290. var promise = _this._loader._loadSceneAsync(context, scene);
  109291. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  109292. if (light.type !== LightType.AMBIENT) {
  109293. throw new Error(context + ": Only ambient lights are allowed on a scene");
  109294. }
  109295. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  109296. return promise;
  109297. });
  109298. };
  109299. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  109300. var _this = this;
  109301. return this._loadExtensionAsync(context, node, function (context, extension) {
  109302. var promise = _this._loader._loadNodeAsync(context, node);
  109303. var babylonLight;
  109304. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  109305. var name = node._babylonMesh.name;
  109306. switch (light.type) {
  109307. case LightType.AMBIENT: {
  109308. throw new Error(context + ": Ambient lights are not allowed on a node");
  109309. }
  109310. case LightType.DIRECTIONAL: {
  109311. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  109312. break;
  109313. }
  109314. case LightType.POINT: {
  109315. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  109316. break;
  109317. }
  109318. case LightType.SPOT: {
  109319. var spotLight = light;
  109320. // TODO: support inner and outer cone angles
  109321. //const innerConeAngle = spotLight.innerConeAngle || 0;
  109322. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  109323. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  109324. break;
  109325. }
  109326. default: {
  109327. throw new Error(context + ": Invalid light type " + light.type);
  109328. }
  109329. }
  109330. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  109331. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  109332. babylonLight.parent = node._babylonMesh;
  109333. return promise;
  109334. });
  109335. };
  109336. Object.defineProperty(KHR_lights.prototype, "_lights", {
  109337. get: function () {
  109338. var extensions = this._loader._gltf.extensions;
  109339. if (!extensions || !extensions[this.name]) {
  109340. throw new Error("#/extensions: " + this.name + " not found");
  109341. }
  109342. var extension = extensions[this.name];
  109343. return extension.lights;
  109344. },
  109345. enumerable: true,
  109346. configurable: true
  109347. });
  109348. return KHR_lights;
  109349. }(GLTF2.GLTFLoaderExtension));
  109350. Extensions.KHR_lights = KHR_lights;
  109351. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  109352. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109353. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109354. })(BABYLON || (BABYLON = {}));
  109355. //# sourceMappingURL=KHR_lights.js.map
  109356. return BABYLON;
  109357. });
  109358. /***/ }),
  109359. /* 31 */
  109360. /***/ (function(module, exports, __webpack_require__) {
  109361. /*!
  109362. * PEP v0.4.3 | https://github.com/jquery/PEP
  109363. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  109364. */
  109365. !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);
  109366. // define inherited MouseEvent properties
  109367. // skip bubbles and cancelable since they're set above in initEvent()
  109368. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  109369. // Spec requires that pointers without pressure specified use 0.5 for down
  109370. // state and 0 for up state.
  109371. var f=0;
  109372. // add x/y properties aliased to clientX/Y
  109373. // define the properties of the PointerEvent interface
  109374. 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(){
  109375. // only activate if this platform does not have pointer events
  109376. 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}})}/**
  109377. * This is the constructor for new PointerEvents.
  109378. *
  109379. * New Pointer Events must be given a type, and an optional dictionary of
  109380. * initialization properties.
  109381. *
  109382. * Due to certain platform requirements, events returned from the constructor
  109383. * identify as MouseEvents.
  109384. *
  109385. * @constructor
  109386. * @param {String} inType The type of the event to create.
  109387. * @param {Object} [inDict] An optional dictionary of initial event properties.
  109388. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  109389. */
  109390. 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},
  109391. // return value, key, map
  109392. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  109393. // MouseEvent
  109394. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  109395. // DOM Level 3
  109396. "buttons",
  109397. // PointerEvent
  109398. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  109399. // event instance
  109400. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  109401. // MouseEvent
  109402. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  109403. // DOM Level 3
  109404. 0,
  109405. // PointerEvent
  109406. 0,0,0,0,0,0,"",0,!1,
  109407. // event instance
  109408. "",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),
  109409. // Scope objects for native events.
  109410. // This exists for ease of testing.
  109411. eventSources:Object.create(null),eventSourceList:[],/**
  109412. * Add a new event source that will generate pointer events.
  109413. *
  109414. * `inSource` must contain an array of event names named `events`, and
  109415. * functions with the names specified in the `events` array.
  109416. * @param {string} name A name for the event source
  109417. * @param {Object} source A new source of platform events.
  109418. */
  109419. 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++)
  109420. // call eventsource register
  109421. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  109422. // call eventsource register
  109423. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  109424. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  109425. return!1}},
  109426. // EVENTS
  109427. 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)},
  109428. // LISTENER LOGIC
  109429. eventHandler:function(a){
  109430. // This is used to prevent multiple dispatch of pointerevents from
  109431. // platform events. This can happen when two elements in different scopes
  109432. // are set up to create pointer events, which is relevant to Shadow DOM.
  109433. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  109434. // set up event listeners
  109435. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  109436. // remove event listeners
  109437. 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)},
  109438. // EVENT CREATION AND TRACKING
  109439. /**
  109440. * Creates a new Event of type `inType`, based on the information in
  109441. * `inEvent`.
  109442. *
  109443. * @param {string} inType A string representing the type of event to create
  109444. * @param {Event} inEvent A platform event with a target
  109445. * @return {Event} A PointerEvent of type `inType`
  109446. */
  109447. makeEvent:function(b,c){
  109448. // relatedTarget must be null if pointer is captured
  109449. 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},
  109450. // make and dispatch an event in one call
  109451. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  109452. * Returns a snapshot of inEvent, with writable properties.
  109453. *
  109454. * @param {Event} inEvent An event that contains properties to copy.
  109455. * @return {Object} An object containing shallow copies of `inEvent`'s
  109456. * properties.
  109457. */
  109458. 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],
  109459. // Work around SVGInstanceElement shadow tree
  109460. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  109461. // This is the behavior implemented by Firefox.
  109462. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  109463. // keep the semantics of preventDefault
  109464. 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){
  109465. // Order of conditions due to document.contains() missing in IE.
  109466. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  109467. // Touch: Do not propagate if node is detached.
  109468. 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)}},/**
  109469. * Dispatches the event to its target.
  109470. *
  109471. * @param {Event} inEvent The event to be dispatched.
  109472. * @return {Boolean} True if an event handler returns true, false otherwise.
  109473. */
  109474. 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(
  109475. // is element a shadow host?
  109476. e=this.targetingShadow(f);e;){if(
  109477. // find the the element inside the shadow root
  109478. d=e.elementFromPoint(b,c)){
  109479. // shadowed element may contain a shadow root
  109480. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  109481. // check for older shadows
  109482. e=this.olderShadow(e)}
  109483. // light dom element is the target
  109484. return f}},owner:function(a){
  109485. // walk up until you hit the shadow root or document
  109486. for(var b=a;b.parentNode;)b=b.parentNode;
  109487. // the owner element is expected to be a Document or ShadowRoot
  109488. 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);
  109489. // if x, y is not in this root, fall back to document search
  109490. 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){
  109491. // Only watch scopes that can target find, as these are top-level.
  109492. // Otherwise we can see duplicate additions and removals that add noise.
  109493. //
  109494. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  109495. // a removal without an insertion when a node is redistributed among
  109496. // shadows. Since it all ends up correct in the document, watching only
  109497. // the document will yield the correct mutations to watch.
  109498. 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))},
  109499. // register all touch-action = none nodes on document load
  109500. 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){
  109501. // find children with touch-action
  109502. var b=x(a,this.findElements,this);
  109503. // flatten the list
  109504. // make sure the added nodes are accounted for
  109505. 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){}
  109506. // handler block for native mouse events
  109507. 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:[],
  109508. // collide with the global mouse listener
  109509. 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++){
  109510. // simulated mouse events will be swallowed near a primary touchend
  109511. 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);
  109512. // Update buttons state after possible out-of-document mouseup.
  109513. 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];
  109514. // Produces wrong state of buttons in Browsers without `buttons` support
  109515. // when a mouse button that was pressed outside the document is released
  109516. // inside and other buttons are still pressed down.
  109517. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  109518. // Support: Firefox <=44 only
  109519. // FF Ubuntu includes the lifted button in the `buttons` property on
  109520. // mouseup.
  109521. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  109522. 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),
  109523. // set touch-action on shadows as well
  109524. 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),
  109525. // remove touch-action from shadow
  109526. 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);
  109527. // simply update scrollType if listeners are already established
  109528. 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){
  109529. // set primary touch if there no pointers, or the only pointer is the mouse
  109530. (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,
  109531. // forward modifier keys
  109532. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  109533. // forward touch preventDefaults
  109534. 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))},
  109535. // For single axis scrollers, determines whether the element should emit
  109536. // pointer events or behave as a scroller
  109537. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  109538. // this element is a touch-action: none, should never scroll
  109539. b=!1;else if("XY"===c)
  109540. // this element should always scroll
  109541. 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]);
  109542. // if delta in the scroll axis > delta other axis, scroll instead of
  109543. // making events
  109544. 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},
  109545. // In some instances, a touchstart can happen without a touchend. This
  109546. // leaves the pointermap in a broken state.
  109547. // Therefore, on every touchstart, we remove the touches that did not fire a
  109548. // touchend event.
  109549. // To keep state globally consistent, we fire a
  109550. // pointercancel for this "abandoned" touch
  109551. vacuumTouches:function(a){var b=a.touches;
  109552. // pointermap.size should be < tl.length here, as the touchstart has not
  109553. // been processed yet.
  109554. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  109555. // Never remove pointerId == 1, which is mouse.
  109556. // Touch identifiers are 2 smaller than their pointerId, which is the
  109557. // index in pointermap.
  109558. 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);
  109559. // a finger drifted off the screen, ignore it
  109560. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  109561. // recover from retargeting by shadow
  109562. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  109563. // clean up case when finger leaves the screen
  109564. 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)},
  109565. // prevent synth mouse events from creating pointer events
  109566. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  109567. // only the primary finger will synth mouse events
  109568. if(this.isPrimaryTouch(c)){
  109569. // remember x/y of last touch
  109570. 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});
  109571. /***/ }),
  109572. /* 32 */
  109573. /***/ (function(module, exports, __webpack_require__) {
  109574. "use strict";
  109575. Object.defineProperty(exports, "__esModule", { value: true });
  109576. var defaultViewer_1 = __webpack_require__(4);
  109577. var mappers_1 = __webpack_require__(1);
  109578. function InitTags(selector) {
  109579. if (selector === void 0) { selector = 'babylon'; }
  109580. var elements = document.querySelectorAll(selector);
  109581. for (var i = 0; i < elements.length; ++i) {
  109582. var element = elements.item(i);
  109583. var configMapper = mappers_1.mapperManager.getMapper('dom');
  109584. var config = configMapper.map(element);
  109585. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  109586. }
  109587. }
  109588. exports.InitTags = InitTags;
  109589. /***/ })
  109590. /******/ ]);
  109591. return BabylonViewer;
  109592. });